instruction
stringlengths
27
22.5k
chosen
stringlengths
27
28.2k
rejected
stringlengths
19
24.9k
__index_level_0__
int64
0
10k
<p>My site has a drop-down menu built in CSS and JavaScript that drops down over a Flash animation. In IE (6&amp;7) the drop-down menus drop over the Flash animation, however, in Firefox (2&amp;3) the menus appear underneath the Flash animation. Is there any way to get this dynamic menu to flow OVER the Flash in Firefox?</p> <p><img src="https://lh3.ggpht.com/guterl/SMnyzAeha6I/AAAAAAAAABI/BGWJes9d9FA/s288/ie_sample.gif" alt="alt text"></p> <p>In IE 7 menu appears over the Flash:</p> <p>In Firefox the menu appears under the Flash: (How can I fix this?!)</p> <p><img src="https://lh3.ggpht.com/guterl/SMnyzHYVLrI/AAAAAAAAABQ/924qQaD3K0o/s288/firefox_sample.gif" alt="alt text"></p>
<p>Try setting wmode to transparent - see <a href="http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_15523" rel="noreferrer">here</a></p>
<p>Have you tried the iframe trick (i.e. floating an iframe behind the menu, thus putting hte flash layers behind.)</p>
8,269
<p>Does anyone know of a good example of how to expose a WCF service programatically without the use of a configuration file? I know the service object model is much richer now with WCF, so I know it's possible. I just have not seen an example of how to do so. Conversely, I would like to see how consuming without a configuration file is done as well.</p> <p>Before anyone asks, I have a very specific need to do this without configuration files. I would normally not recommend such a practice, but as I said, there is a very specific need in this case.</p>
<p>Consuming a web service without a config file is very simple, as I've discovered. You simply need to create a binding object and address object and pass them either to the constructor of the client proxy or to a generic ChannelFactory instance. You can look at the default app.config to see what settings to use, then create a static helper method somewhere that instantiates your proxy:</p> <pre><code>internal static MyServiceSoapClient CreateWebServiceInstance() { BasicHttpBinding binding = new BasicHttpBinding(); // I think most (or all) of these are defaults--I just copied them from app.config: binding.SendTimeout = TimeSpan.FromMinutes( 1 ); binding.OpenTimeout = TimeSpan.FromMinutes( 1 ); binding.CloseTimeout = TimeSpan.FromMinutes( 1 ); binding.ReceiveTimeout = TimeSpan.FromMinutes( 10 ); binding.AllowCookies = false; binding.BypassProxyOnLocal = false; binding.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard; binding.MessageEncoding = WSMessageEncoding.Text; binding.TextEncoding = System.Text.Encoding.UTF8; binding.TransferMode = TransferMode.Buffered; binding.UseDefaultWebProxy = true; return new MyServiceSoapClient( binding, new EndpointAddress( "http://www.mysite.com/MyService.asmx" ) ); } </code></pre>
<p>All WCF configuration can be done programatically. So it's possible to create both servers and clients without a config file. </p> <p>I recommend the book "Programming WCF Services" by Juval Lowy, which contains many examples of programmatic configuration.</p>
7,820
<p>How can I determine all of the assemblies that my .NET desktop application has loaded? I'd like to put them in the about box so I can query customers over the phone to determine what version of XYZ they have on their PC.</p> <p>It would be nice to see both managed and unmanaged assemblies. I realize the list will get long but I plan to slap an incremental search on it.</p>
<pre><code>using System; using System.Reflection; using System.Windows.Forms; public class MyAppDomain { public static void Main(string[] args) { AppDomain ad = AppDomain.CurrentDomain; Assembly[] loadedAssemblies = ad.GetAssemblies(); Console.WriteLine("Here are the assemblies loaded in this appdomain\n"); foreach(Assembly a in loadedAssemblies) { Console.WriteLine(a.FullName); } } } </code></pre>
<p>Looks like <code>AppDomain.CurrentDomain.GetAssemblies();</code> will do the trick :)</p>
4,134
<p>I've been utilizing the <a href="http://en.wikipedia.org/wiki/Command_pattern" rel="nofollow noreferrer">command pattern</a> in my Flex projects, with asynchronous callback routes required between:</p> <ul> <li>whoever instantiated a given command object and the command object,</li> <li>the command object and the "data access" object (i.e. someone who handles the remote procedure calls over the network to the servers) that the command object calls.</li> </ul> <p>Each of these two callback routes has to be able to be a one-to-one relationship. This is due to the fact that I might have several instances of a given command class running the exact same job at the same time but with slightly different parameters, and I don't want their callbacks getting mixed up. Using events, the default way of handling asynchronicity in AS3, is thus pretty much out since they're inherently based on one-to-many relationships.</p> <p>Currently I have done this using <strong>callback function references</strong> with specific kinds of signatures, but I was wondering <em>if someone knew of a better (or an alternative) way?</em></p> <p>Here's an example to illustrate my current method:</p> <ul> <li>I might have a view object that spawns a <code>DeleteObjectCommand</code> instance due to some user action, passing references to two of its own private member functions (one for success, one for failure: let's say <code>"deleteObjectSuccessHandler()"</code> and <code>"deleteObjectFailureHandler()"</code> in this example) as callback function references to the command class's constructor.</li> <li>Then the command object would repeat this pattern with its connection to the "data access" object.</li> <li>When the RPC over the network has successfully been completed (or has failed), the appropriate callback functions are called, first by the "data access" object and then the command object, so that finally the view object that instantiated the operation in the first place gets notified by having its <code>deleteObjectSuccessHandler()</code> or <code>deleteObjectFailureHandler()</code> called.</li> </ul>
<p>I'll try one more idea:</p> <p>Have your Data Access Object return their own AsyncTokens (or some other objects that encapsulate a pending call), instead of the AsyncToken that comes from the RPC call. So, in the DAO it would look something like this (this is very sketchy code):</p> <pre><code>public function deleteThing( id : String ) : DeferredResponse { var deferredResponse : DeferredResponse = new DeferredResponse(); var asyncToken : AsyncToken = theRemoteObject.deleteThing(id); var result : Function = function( o : Object ) : void { deferredResponse.notifyResultListeners(o); } var fault : Function = function( o : Object ) : void { deferredResponse.notifyFaultListeners(o); } asyncToken.addResponder(new ClosureResponder(result, fault)); return localAsyncToken; } </code></pre> <p>The <code>DeferredResponse</code> and <code>ClosureResponder</code> classes don't exist, of course. Instead of inventing your own you could use <code>AsyncToken</code> instead of <code>DeferredResponse</code>, but the public version of <code>AsyncToken</code> doesn't seem to have any way of triggering the responders, so you would probably have to subclass it anyway. <code>ClosureResponder</code> is just an implementation of <code>IResponder</code> that can call a function on success or failure.</p> <p>Anyway, the way the code above does it's business is that it calls an RPC service, creates an object encapsulating the pending call, returns that object, and then when the RPC returns, one of the closures <code>result</code> or <code>fault</code> gets called, and since they still have references to the scope as it was when the RPC call was made, they can trigger the methods on the pending call/deferred response.</p> <p>In the command it would look something like this:</p> <pre><code>public function execute( ) : void { var deferredResponse : DeferredResponse = dao.deleteThing("3"); deferredResponse.addEventListener(ResultEvent.RESULT, onResult); deferredResponse.addEventListener(FaultEvent.FAULT, onFault); } </code></pre> <p>or, you could repeat the pattern, having the <code>execute</code> method return a deferred response of its own that would get triggered when the deferred response that the command gets from the DAO is triggered.</p> <p>But. I don't think this is particularly pretty. You could probably do something nicer, less complex and less entangled by using one of the many application frameworks that exist to solve more or less exactly this kind of problem. My suggestion would be <a href="http://mate.asfusion.com" rel="nofollow noreferrer">Mate</a>.</p>
<p>The AbstractCollection is the best way to deal with Persistent Objects in Flex / AIR. The GenericDAO provides the answer.</p> <p>DAO is the Object which manages to perform CRUD Operation and other Common Operations to be done over a ValueObject ( known as Pojo in Java ). GenericDAO is a reusable DAO class which can be used generically. Goal:</p> <p>In JAVA IBM GenericDAO, to add a new DAO, the steps to be done is simply, Add a valueobject (pojo). Add a hbm.xml mapping file for the valueobject. Add the 10-line Spring configuration file for the DAO.</p> <p>Similarly, in AS3 Project Swiz DAO. We want to attain a similar feet of achievement.</p> <p>Client Side GenericDAO model: As we were working on a Client Side language, also we should be managing a persistent object Collection (for every valueObject) . Usage: Source: <a href="http://github.com/nsdevaraj/SwizDAO" rel="nofollow noreferrer">http://github.com/nsdevaraj/SwizDAO</a></p>
7,639
<p>Hello again ladies and gents!</p> <p>OK, following on from my other question on <a href="https://stackoverflow.com/questions/6681/aspnet-web-service-results-proxy-classes-and-type-conversion">ASP.NET Web Service Results, Proxy Classes and Type Conversion</a>. I've come to a part in my project where I need to get my thinking cap on.</p> <p>Basically, we have a large, complex custom object that needs to be returned from a Web Service and consumed in the client application.</p> <p>Now, based on the previous discussion, we know this is going to then take the form of the proxy class(es) as the return type. To overcome this, we need to basically copy the properties from one to the other.</p> <p>In this case, that is something that I would really, really, <em>really!</em> like to avoid!</p> <p>So, it got me thinking, <strong>how else could we do this?</strong></p> <p>My current thoughts are to enable the object for complete serialization to XML and then return the XML as a string from the Web Service. We then de-serialize at the client. This will mean a fair bit of attribute decorating, but at least the code at both endpoints will be light, namely by just using the .NET XML Serializer.</p> <h2>What are your thoughts on this?</h2>
<p>The .Net XML (de)serialisation is pretty nicely implemented. At first thought, I don't think this is a bad idea at all.</p> <p>If the two applications import the same C# class(es) definition(s), then this is a relatively nice way of getting copy-constructor behaviour for free. If the class structure changes, then everything will work when both sides get the new class definition, without needing to make any additional changes on the web-service consumption/construction side.</p> <p>There's a slight overhead in marshalling and demarshalling the XML, but that is probably dwarved by the overhead of the remote web service call. .Net XML serialisation is well understood by most programmers and should produce an easy to maintain solution.</p>
<p>I had some great answers on a very similar topic yesterday that might be useful for you:</p> <p><a href="https://stackoverflow.com/questions/16529/communication-between-javascript-and-the-server">Communication between javascript and the server</a></p>
3,831
<p>I've always had trouble getting prints to stick directly on my bed, but had great reliability when use rafts. This didn't present a problem when I was using PLA, but I recently got a roll of PETG and it is very hard to remove rafts, so I am once again trying to figure out whats wrong.</p> <p>I am printing the same file (currently a simple square for testing) with the same settings, except I am turning rafts on/off. When rafts are on, my print sticks perfectly. When rafts are off, my print doesn't stick at all - not even the skirt (which sticks fine on the raft print). With rafts on, I can watch my printer lay down a nice line for the skirt / first layer. With rafts off, I watched plastic ooze out of the nozzle and ride along with the print head, not sticking to the plate at all.</p> <p>I have a stock Monoprice Maker Select v2 with the PEI surface it shipped with. I haven't tried any bed additions/changes to get better adhesion, since I know rafts stick fine with what I have. I figure there must be some settings I can change to make my first layer stick too. I am using Simplify3D &amp; have tried a few basic tweaks, but I am largely stabbing in the dark.</p> <p>What are the specific characteristics of a first layer raft, in comparison to a first layer of my print, that might make it stick better?</p>
<p>You could experiment with the 'cleaning' part of the startup gcode shown <a href="http://reprap.org/wiki/Start_GCode_routines" rel="nofollow noreferrer">here</a></p> <pre><code>G1 X100 Y0 F4000 ; move half way along the front edge G1 Z1 ; move nozzle close to bed M109 S200 ; heat nozzle to 200 degC and wait until reached G4 P10000 ; wait 10 seconds for nozzle length to stabilize G1 E10 ; extrude 10 mm of filament G1 z15 F12000 E5 ; move 15 mm up, fast, while extruding 5mm G92 E0 ; reset extruder </code></pre> <p>I'm not completely persuaded that it helps a lot, but the idea is to fill the extruder (with some pressure from the bed at a 1mm gap) right before starting the skirt. Typically, I still find the first line of skirt may be quite blobby, but a 2nd line of skirt seems much better. Obviously you need the bed alignment right too. A raft seems to have enough 'extra' extrusion to mask these issues a little bit.</p> <p>Later reflection suggests that these introductory G-code snippets (I've now started using the PRUSA one of a line along the edge of the bed) risk problems with flexible filament, so it might be best to err on the side of conservative for the extrude volume rather than assume that more is better here.</p> <p>You can find other similar solutions in this question: <a href="https://3dprinting.stackexchange.com/questions/6355/writing-g-code-swiping-at-start-of-print/6357?s=2|10.4629#6357">Writing G-code : swiping at start of print</a></p>
<p>You could experiment with the 'cleaning' part of the startup gcode shown <a href="http://reprap.org/wiki/Start_GCode_routines" rel="nofollow noreferrer">here</a></p> <pre><code>G1 X100 Y0 F4000 ; move half way along the front edge G1 Z1 ; move nozzle close to bed M109 S200 ; heat nozzle to 200 degC and wait until reached G4 P10000 ; wait 10 seconds for nozzle length to stabilize G1 E10 ; extrude 10 mm of filament G1 z15 F12000 E5 ; move 15 mm up, fast, while extruding 5mm G92 E0 ; reset extruder </code></pre> <p>I'm not completely persuaded that it helps a lot, but the idea is to fill the extruder (with some pressure from the bed at a 1mm gap) right before starting the skirt. Typically, I still find the first line of skirt may be quite blobby, but a 2nd line of skirt seems much better. Obviously you need the bed alignment right too. A raft seems to have enough 'extra' extrusion to mask these issues a little bit.</p> <p>Later reflection suggests that these introductory G-code snippets (I've now started using the PRUSA one of a line along the edge of the bed) risk problems with flexible filament, so it might be best to err on the side of conservative for the extrude volume rather than assume that more is better here.</p> <p>You can find other similar solutions in this question: <a href="https://3dprinting.stackexchange.com/questions/6355/writing-g-code-swiping-at-start-of-print/6357?s=2|10.4629#6357">Writing G-code : swiping at start of print</a></p>
617
<p>I've got a utility that outputs a list of files required by a game. How can I run that utility within a C program and grab its output so I can act on it within the same program?</p> <p>UPDATE: Good call on the lack of information. The utility spits out a series of strings, and this is supposed to be portable across Mac/Windows/Linux. Please note, I'm looking for a programmatic way to execute the utility and retain its output (which goes to stdout).</p>
<p>For simple problems in Unix-ish environments try <a href="http://pubs.opengroup.org/onlinepubs/009696799/functions/popen.html" rel="noreferrer"><code>popen()</code></a>. </p> <p>From the man page:</p> <blockquote> <p>The popen() function opens a process by creating a pipe, forking and invoking the shell.</p> </blockquote> <p>If you use the read mode this is exactly what you asked for. I don't know if it is implemented in Windows.</p> <p>For more complicated problems you want to look up inter-process communication.</p>
<pre><code>//execute external process and read exactly binary or text output //can read image from Zip file for example string run(const char* cmd){ FILE* pipe = popen(cmd, "r"); if (!pipe) return "ERROR"; char buffer[262144]; string data; string result; int dist=0; int size; //TIME_START while(!feof(pipe)) { size=(int)fread(buffer,1,262144, pipe); //cout&lt;&lt;buffer&lt;&lt;" size="&lt;&lt;size&lt;&lt;endl; data.resize(data.size()+size); memcpy(&amp;data[dist],buffer,size); dist+=size; } //TIME_PRINT_ pclose(pipe); return data; } </code></pre>
6,471
<p>Sorry for the subject line sounding like an even nerdier Harry Potter title.</p> <p>I'm trying to use AS3's Socket class to write a simple FTP program to export as an AIR app in Flex Builder 3. I'm using an FTP server on my local network to test the program. I can successfully connect to the server (the easy part) but I can't send any commands. I'm pretty sure that you have to use the ByteArray class to send these commands but there's some crucial piece of information that I'm missing apparently. Does anyone know how to do this? Thanks! Dave</p>
<p>The FTP protocol predates UTF encoding. Switch to ANSI/ASCII for better results. If you do opt for writeMultiByte instead of writeUTFBytes, be aware that it is buggy in linux. <a href="http://www.flexiblefactory.co.uk/flexible/?p=75" rel="nofollow noreferrer">Here's</a> one way around it.</p> <p>There's another question <a href="https://stackoverflow.com/questions/285290/trying-to-send-an-http-request-over-sockets">here</a> where the line ending turns out to be the culprit, so make sure that you get it right (as suggested above).</p> <p>As said before, if this is running from the web, all socket connections will require a crossdomain policy, but this is NOT file based over HTTP. Recent changes to the security rules mean that any socket based connection must first get a crossdomain from a policy server hosted on port 843 of the target host.</p> <p>Quoting from Adobe:</p> <blockquote> <p>A SWF file may no longer make a socket connection to its own domain without a socket policy file. Prior to version 9,0,115,0, a SWF file was permitted to make socket connections to ports 1024 or greater in its own domain without a policy file.</p> <p>HTTP policy files may no longer be used to authorize socket connections. Prior to version 9,0,115,0, an HTTP policy file, served from the master location of /crossdomain.xml on port 80, could be used to authorize a socket connection to any port 1024 or greater on the same host.</p> </blockquote> <p>Essentially, what this means is that you must be in control of the target FTP host, and install supplementary software on it to get this working.</p>
<p>We will need more info to resolve this.. What you're saying here appears correct to me. You're using the Socket class to send data though, not ByteArray.</p> <p>Are you sure data is not being sent? How are you receiving the response? It may be that it's working fine but you're just not aware of it? As i said, tell us more about what you're doing..</p> <p>Lee Brimelow has a <a href="http://gotoandlearn.com/play?id=69" rel="nofollow noreferrer">screencast on gotoAndLearn</a> of writing an POP3 client. It's essentially the same of what you're doing so take a look.</p>
8,857
<p>How do I capture the output of "%windir%/system32/pnputil.exe -e"? (assume windows vista 32-bit)</p> <p>Bonus for technical explanation of why the app normally writes output to the cmd shell, but when stdout and/or stderr are redirected then the app writes nothing to the console or to stdout/stderr?</p> <pre> C:\Windows\System32>PnPutil.exe --help Microsoft PnP Utility {...} C:\Windows\System32>pnputil -e > c:\foo.txt C:\Windows\System32>type c:\foo.txt C:\Windows\System32>dir c:\foo.txt Volume in drive C has no label. Volume Serial Number is XXXX-XXXX Directory of c:\ 09/10/2008 12:10 PM 0 foo.txt 1 File(s) 0 bytes </pre>
<p>Doesn't seem like there is an easy way at all. You would have to start hooking the call to WriteConsole and dumping the string buffers. See <a href="http://objectmix.com/tcl/366746-autoexpect-under-windows-later-mac-linux.html#post1359780" rel="nofollow noreferrer">this post</a> for a similar discussion.</p> <p>Of course, if this is a one off for interactive use then just select all the output from the command window and copy it to the clipboard. (Make sure you cmd window buffer is big enough to store all the output).</p>
<p>Some applications are written so that it works in piping scenarios well e.g.</p> <pre><code>svn status | find "? " </code></pre> <p>is a command that pipes output of <code>svn status</code> into <code>find "? "</code> so it would filter subversion output down to unknown files (marked with a question mark) in my repos.</p> <p>Imagine if svn status would also output a header that says "Copyright ? 2009" That very specific header line would also show up. Which is <em>not</em> what I expect.</p> <p>So certain tools, like those of Sysinternals' will write any header information <em>only</em> if it is printed directly to the command window, if any kind of redirection is detected, then those header information will not be written as by the reason above.</p> <p>Header information becomes noise when used in piping/automation scenarios.</p> <p>I suppose if you can't use <code>&gt;</code> to output to a file, its because the tool is hardwired not to do so. You'll need an indirect means to capture it.</p> <p>Hope this helps.</p>
7,819
<p>You can embed the <a href="http://ipython.scipy.org/" rel="noreferrer">IPython</a> shell inside of your application so that it launches the shell in the foreground. Is there a way to embed a telnet server in a python app so that you can telnet to a certain port and launch a remote IPython shell? </p> <p>Any tips for redirecting the input/output streams for IPython or how to hook it up to a telnet server library or recommendations for other libraries that could be used to implement this are much appreciated. </p>
<p>Python includes a <a href="http://www.python.org/doc/lib/module-telnetlib.html" rel="nofollow noreferrer">telnet client</a>, but not a telnet server. You can implement a telnet server using <a href="http://twistedmatrix.com" rel="nofollow noreferrer">Twisted</a>. <a href="http://twistedmatrix.com/pipermail/twisted-python/2004-August/008335.html" rel="nofollow noreferrer">Here's an example</a>. As for hooking these things together, that's up to you.</p>
<p>I think you should base your server class on the <a href="http://www.python.org/doc/lib/module-SocketServer.html" rel="nofollow noreferrer"><code>SocketServer</code></a> class from the standard library. You'll need to write a <code>RequestHandler</code> to read and echo input but a lot of the heavy lifting is already done for you.</p> <p>You can use the <a href="http://docs.python.org/lib/node632.html" rel="nofollow noreferrer"><code>ThreadingMixIn</code></a> to make the server multi-threaded very easily. </p>
7,054
<p>How have you implemented Internationalization (i18n) in actual projects you've worked on?</p> <p>I took an interest in making software cross-cultural after I read the famous post by Joel, <a href="http://www.joelonsoftware.com/articles/Unicode.html" rel="noreferrer">The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)</a>. However, I have yet to able to take advantage of this in a real project, besides making sure I used Unicode strings where possible. But making all your strings Unicode and ensuring you understand what encoding everything you work with is in is just the tip of the i18n iceberg.</p> <p>Everything I have worked on to date has been for use by a controlled set of US English speaking people, or i18n just wasn't something we had time to work on before pushing the project live. So I am looking for any tips or war stories people have about making software more localized in real world projects.</p>
<p>It has been a while, so this is not comprehensive.</p> <p><strong>Character Sets</strong></p> <p>Unicode is great, but you can't get away with ignoring other character sets. The default character set on Windows XP (English) is Cp1252. On the web, you don't know what a browser will send you (though hopefully your container will handle most of this). And don't be surprised when there are bugs in whatever implementation you are using. Character sets can have interesting interactions with filenames when they move to between machines.</p> <p><strong>Translating Strings</strong></p> <p>Translators are, generally speaking, not coders. If you send a source file to a translator, they will break it. Strings should be extracted to resource files (e.g. properties files in Java or resource DLLs in Visual C++). Translators should be given files that are difficult to break and tools that don't let them break them.</p> <p>Translators do not know where strings come from in a product. It is difficult to translate a string without context. If you do not provide guidance, the quality of the translation will suffer.</p> <p>While on the subject of context, you may see the same string "foo" crop up in multiple times and think it would be more efficient to have all instances in the UI point to the same resource. This is a bad idea. Words may be very context-sensitive in some languages.</p> <p>Translating strings costs money. If you release a new version of a product, it makes sense to recover the old versions. Have tools to recover strings from your old resource files.</p> <p>String concatenation and manual manipulation of strings should be minimized. Use the format functions where applicable.</p> <p>Translators need to be able to modify hotkeys. <kbd>Ctrl</kbd>+<kbd>P</kbd> is print in English; the Germans use <kbd>Ctrl</kbd>+<kbd>D</kbd>.</p> <p>If you have a translation process that requires someone to manually cut and paste strings at any time, you are asking for trouble.</p> <p><strong>Dates, Times, Calendars, Currency, Number Formats, Time Zones</strong></p> <p>These can all vary from country to country. A comma may be used to denote decimal places. Times may be in 24hour notation. Not everyone uses the Gregorian calendar. You need to be unambiguous, too. If you take care to display dates as MM/DD/YYYY for the USA and DD/MM/YYYY for the UK on your website, the dates are ambiguous unless the user knows you've done it.</p> <p><strong>Especially Currency</strong></p> <p>The Locale functions provided in the class libraries will give you the local currency symbol, but you can't just stick a pound (sterling) or euro symbol in front of a value that gives a price in dollars.</p> <p><strong>User Interfaces</strong></p> <p>Layout should be dynamic. Not only are strings likely to double in length on translation, the entire UI may need to be inverted (Hebrew; Arabic) so that the controls run from right to left. And that is before we get to Asia.</p> <p><strong>Testing Prior To Translation</strong></p> <ul> <li>Use static analysis of your code to locate problems. At a bare minimum, leverage the tools built into your IDE. (Eclipse users can go to Window > Preferences > Java > Compiler > Errors/Warnings and check for non-externalised strings.)</li> <li>Smoke test by simulating translation. It isn't difficult to parse a resource file and replace strings with a pseudo-translated version that doubles the length and inserts funky characters. You don't have to speak a language to use a foreign operating system. Modern systems should let you log in as a foreign user with translated strings and foreign locale. If you are familiar with your OS, you can figure out what does what without knowing a single word of the language.</li> <li>Keyboard maps and character set references are very useful.</li> <li>Virtualisation would be very useful here.</li> </ul> <p><strong>Non-technical Issues</strong></p> <p>Sometimes you have to be sensitive to cultural differences (offence or incomprehension may result). A mistake you often see is the use of flags as a visual cue choosing a website language or geography. Unless you want your software to declare sides in global politics, this is a bad idea. If you were French and offered the option for English with St. George's flag (the flag of England is a red cross on a white field), this might result in confusion for many English speakers - assume similar issues will arise with foreign languages and countries. Icons need to be vetted for cultural relevance. What does a thumbs-up or a green tick mean? Language should be relatively neutral - addressing users in a particular manner may be acceptable in one region, but considered rude in another.</p> <p><strong>Resources</strong></p> <p>C++ and Java programmers may find the ICU website useful: <a href="http://www.icu-project.org/" rel="noreferrer">http://www.icu-project.org/</a></p>
<p>One website I use has a translation method the owner calls "wiki + machine translation". This is a community based site so is obviously different to the needs of companies. </p> <p><a href="http://blog.bookmooch.com/2007/09/23/how-bookmooch-does-its-translations/" rel="nofollow noreferrer">http://blog.bookmooch.com/2007/09/23/how-bookmooch-does-its-translations/</a></p>
2,333
<p>I have an application that sometimes causes a BSOD on a Win XP machine. Trying to find out more, I loaded up the resulting *.dmp file (from C:\Windows\Minidump), but get this message when in much of the readout when doing so:</p> <pre><code>********************************************************************* * Symbols can not be loaded because symbol path is not initialized. * * * * The Symbol Path can be set by: * * using the _NT_SYMBOL_PATH environment variable. * * using the -y &lt;symbol_path&gt; argument when starting the debugger. * * using .sympath and .sympath+ * ********************************************************************* </code></pre> <p>What does this mean, and how do I "fix" it?</p>
<p>Quick answer is to </p> <p>c:\> set _NT_SYMBOL_PATH=SRV*C:\WINDOWS\Symbols*http://msdl.microsoft.com/download/symbols</p> <p>before starting windbg.</p>
<p>As @Vaibhav noted, you actually need to download the symbols and configure windbg to use them.</p> <p>Also note the following: !sym noisy -- Activates noisy symbol loading lm v -- Use with "m" parameter to look at information for a loaded module. lme D sm - List all modules w/o symbols.</p>
3,313
<p>I wonder if anyone uses commercial/free java obfuscators on his own commercial product. I know only about one project that actually had an obfuscating step in the ant build step for releases.</p> <p>Do you obfuscate? And if so, why do you obfuscate?</p> <p>Is it really a way to protect the code or is it just a better feeling for the developers/managers?</p> <p><strong>edit:</strong> Ok, I to be exact about my point: Do you obfuscate to protect your IP (your algorithms, the work you've put into your product)? I won't obfuscate for security reasons, that doesn't feel right. So I'm only talking about protecting your applications code against competitors.</p> <p><a href="https://stackoverflow.com/users/988/staffan">@staffan</a> has a good point:</p> <blockquote> <p>The reason to stay away from chaining code flow is that some of those changes makes it impossible for the JVM to efficiently optimize the code. In effect it will actually degrade the performance of your application.</p> </blockquote>
<p>If you do obfuscate, stay away from obfuscators that modify the code by changing code flow and/or adding exception blocks and such to make it hard to disassemble it. To make the code unreadable it is usually enough to just change all names of methods, fields and classes.</p> <p>The reason to stay away from changing code flow is that some of those changes makes it impossible for the JVM to efficiently optimize the code. In effect it will actually degrade the performance of your application. </p>
<p>I guess it really comes down to <em>what</em> your Java code is for, how it's distributed and who your clients are. We don't obfuscate anything, as we've never found one that was particularly good and it tends to be more trouble than it's worth. If someone has access to our JAR files and has the knowledge to be able to sniff around inside them, then there's far more worrying things that they can do than rip off our source code.</p>
3,317
<p>Was considering the <code>System.Collections.ObjectModel ObservableCollection&lt;T&gt;</code> class. This one is strange because </p> <ul> <li>it has an Add Method which takes <strong>one</strong> item only. No AddRange or equivalent. </li> <li>the Notification event arguments has a NewItems property, which is a <strong>IList</strong> (of objects.. not T)</li> </ul> <p>My need here is to add a batch of objects to a collection and the listener also gets the batch as part of the notification. Am I missing something with ObservableCollection ? Is there another class that meets my spec?</p> <p><em>Update: Don't want to roll my own as far as feasible. I'd have to build in add/remove/change etc.. a whole lot of stuff.</em></p> <hr> <p>Related Q:<br> <a href="https://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each/670579#670579">https://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each</a></p>
<p>It seems that the <code>INotifyCollectionChanged</code> interface allows for updating when multiple items were added, so I'm not sure why <code>ObservableCollection&lt;T&gt;</code> doesn't have an <code>AddRange</code>. You could make an extension method for <code>AddRange</code>, but that would cause an event for every item that is added. If that isn't acceptable you should be able to inherit from <code>ObservableCollection&lt;T&gt;</code> as follows:</p> <pre><code>public class MyObservableCollection&lt;T&gt; : ObservableCollection&lt;T&gt; { // matching constructors ... bool isInAddRange = false; protected override void OnCollectionChanged(NotifyCollectionChangedEventArgs e) { // intercept this when it gets called inside the AddRange method. if (!isInAddRange) base.OnCollectionChanged(e); } public void AddRange(IEnumerable&lt;T&gt; items) { isInAddRange = true; foreach (T item in items) Add(item); isInAddRange = false; var e = new NotifyCollectionChangedEventArgs( NotifyCollectionChangedAction.Add, items.ToList()); base.OnCollectionChanged(e); } } </code></pre>
<p>Take a look at <a href="https://stackoverflow.com/questions/670577/observablecollection-doesnt-support-addrange-method-so-i-get-notified-for-each/670579#670579">Observable collection with AddRange, RemoveRange and Replace range methods</a> in both C# and VB.</p> <p>In VB: INotifyCollectionChanging implementation.</p>
8,123
<p>In follow up to <a href="https://stackoverflow.com/questions/56820/round-in-python-doesnt-seem-to-be-rounding-properly">this question</a>, it appears that some numbers cannot be represented by floating point at all, and instead are approximated.</p> <p>How are floating point numbers stored?</p> <p>Is there a common standard for the different sizes?</p> <p>What kind of gotchas do I need to watch out for if I use floating point?</p> <p>Are they cross-language compatible (ie, what conversions do I need to deal with to send a floating point number from a python program to a C program over TCP/IP)?</p>
<p>As mentioned, the <a href="http://en.wikipedia.org/wiki/IEEE_754-1985" rel="noreferrer">Wikipedia article on IEEE 754</a> does a good job of showing how floating point numbers are stored on most systems.</p> <p>Now, here are some common gotchas:</p> <ul> <li>The biggest is that you almost never want to compare two floating point numbers for equality (or inequality). You'll want to use greater than/less than comparisons instead.</li> <li>The more operations you do on a floating point number, the more significant rounding errors can become.</li> <li>Precision is limited by the size of the fraction, so you may not be able to correctly add numbers that are separated by several orders of magnitude. (For example, you won't be able to add 1E-30 to 1E30.)</li> </ul>
<p>What I remember is a 32 bit floating point is stored using 24 bits for a actual number, and the remain 8 bits are used as a power of 10, determining where the decimal point is.</p> <p>I'm a bit rusty on the subject tho...</p>
8,111
<p>I want to print a structure that I can embed in a resin and later dissolve. I know that some fancy 3D printing systems have raft materials etc., that can be printed and later removed easily. </p> <p>Can any one suggest a 3D printing material that can be dissolved in say water or another readily available solvent?</p>
<p>Wash-away filament used for support in PLA printing is typically PVA, which is completely water soluble and may serve your purpose. It is easily 3D printed as the primary filament and attaches well to the build plate.</p> <p>Many 3D printer filament suppliers will carry this type of support material. It is important to keep it in a sealed bag with desiccant as it will absorb moisture from the air, rendering it useless for printing.</p> <p>One such resource is <a href="https://www.matterhackers.com/store/l/175mm-pva-filament-half-kg/sk/M4MJTECR" rel="nofollow noreferrer">MatterHackers</a> which prices a half-kilogram at US$45. The link provides suitably appropriate information:</p> <blockquote> <p>PVA (Polyvinyl Alcohol) is a water-soluble material that is often used as a support material, but can also be used to print independently. PVA supports are useful for complex designs where removing support material manually is difficult or impossible, but leaving the part in a water bath overnight will completely dissolve this material.</p> </blockquote> <p><a href="https://i.stack.imgur.com/2ytSy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2ytSy.png" alt="PVA filament"></a></p>
<p>ABS dissolves in acetone. Indeed actone can be used to clean up 3D prints, see <a href="https://3dprinting.stackexchange.com/questions/4235/whats-smoother-acetone-treated-pla-or-abs/">What&#39;s smoother? Acetone treated PLA or ABS</a>. PLA maybe not somuch as ABS, see the same post.</p> <p>PLA dissolves in any chlorinated or fluorinated solvent, such as THF or Chloroform - both of which are significantly more hazardous than acetone.</p> <p>Hence, as always <strong>take care</strong> when using solvents, see <a href="https://3dprinting.stackexchange.com/questions/81/safety-precautions-when-using-acetone/278#278">Safety precautions when using acetone</a></p> <p>Also, as filaments are often not pure ABS or PLA, due to additives and dyes, etc., then the solvent may not dissolve the 3D printed part <em>completely</em>, and you may be left with a deformed, rubbery residue.</p>
910
<p>I am looking for simple straightforward solution for accessing EXIF information of jpeg images in .Net. Does anybody has experience with this?</p>
<p>If you're willing to use an open-source library, may I humbly suggest one of my own creation?</p> <p>The <em>metadata-extractor</em> project has been alive and well since 2002 for Java, and is now available for .NET.</p> <ul> <li>Open source (Apache 2.0)</li> <li>Heavily tested and widely used</li> <li>Supports many image types (JPEG, TIFF, PNG, WebP, GIF, BMP, ICO, PCX...)</li> <li>Supports many metadata types (Exif, IPTC, XMP, JFIF, ...)</li> <li>Supports many manufacturer-specific fields (Canon, Nikon, ...)</li> <li>Very fast (fully processes ~400 images totalling 1.33GB in ~3 seconds) with low memory consumption</li> <li>Builds for .NET 3.5, .NET 4.0+ and PCL</li> </ul> <p>It's available via <a href="https://www.nuget.org/packages/MetadataExtractor/" rel="noreferrer">NuGet</a> or <a href="https://github.com/drewnoakes/metadata-extractor-dotnet" rel="noreferrer">GitHub</a>.</p> <p>Sample usage:</p> <pre><code>IEnumerable&lt;Directory&gt; directories = ImageMetadataReader.ReadMetadata(path); foreach (var directory in directories) foreach (var tag in directory.Tags) Console.WriteLine($"{directory.Name} - {tag.TagName} = {tag.Description}"); </code></pre>
<p>Several years ago, I started a little JPEG EXIF app with Omar Shahine to work on JPEG EXIF files, called JpegHammer.</p> <p>He extracted from that project a library and called it PhotoLibrary, it was an easy .NET wrapper for the EXIF 2.2 tags. Unfortunately, the GotDotNet site is gone, CodePlex doesn't have it, Omar's web site links don't work, and I don't have a copy anymore.</p> <p>But, if you can dig around Google, maybe you'll find it and it'll do the trick for you.</p>
6,343
<p>I want my website to join some webcam recordings in FLV files (like this one). This needs to be done on Linux without user input. How do I do this? For simplicity's sake, I'll use the same flv as both inputs in hope of getting a flv that plays the same thing twice in a row.</p> <p>That should be easy enough, right? There's even a full code example in the <a href="http://ffmpeg.mplayerhq.hu/faq.html#SEC31" rel="noreferrer">ffmpeg FAQ</a>.</p> <p>Well, pipes seem to be giving me problems (both on my mac running Leopard and on Ubuntu 8.04) so let's keep it simple and use normal files. Also, if I don't specify a rate of 15 fps, the visual part plays <a href="http://www.marc-andre.ca/posts/blog/webcam/output-norate.flv" rel="noreferrer">extremely fast</a>. The example script thus becomes:</p> <pre><code>ffmpeg -i input.flv -vn -f u16le -acodec pcm_s16le -ac 2 -ar 44100 \ - &gt; temp.a &lt; /dev/null ffmpeg -i input.flv -an -f yuv4mpegpipe - &gt; temp.v &lt; /dev/null cat temp.v temp.v &gt; all.v cat temp.a temp.a &gt; all.a ffmpeg -f u16le -acodec pcm_s16le -ac 2 -ar 44100 -i all.a \ -f yuv4mpegpipe -i all.v -sameq -y output.flv </code></pre> <p>Well, using this will work for the audio, but I only get the video the first time around. This seems to be the case for any flv I throw as input.flv, including the movie teasers that come with red5.</p> <p>a) Why doesn't the example script work as advertised, in particular why do I not get all the video I'm expecting?</p> <p>b) Why do I have to specify a framerate while Wimpy player can play the flv at the right speed?</p> <p>The only way I found to join two flvs was to use mencoder. Problem is, mencoder doesn't seem to join flvs:</p> <pre><code>mencoder input.flv input.flv -o output.flv -of lavf -oac copy \ -ovc lavc -lavcopts vcodec=flv </code></pre> <p>I get a Floating point exception...</p> <pre><code>MEncoder 1.0rc2-4.0.1 (C) 2000-2007 MPlayer Team CPU: Intel(R) Xeon(R) CPU 5150 @ 2.66GHz (Family: 6, Model: 15, Stepping: 6) CPUflags: Type: 6 MMX: 1 MMX2: 1 3DNow: 0 3DNow2: 0 SSE: 1 SSE2: 1 Compiled for x86 CPU with extensions: MMX MMX2 SSE SSE2 success: format: 0 data: 0x0 - 0x45b2f libavformat file format detected. [flv @ 0x697160]Unsupported audio codec (6) [flv @ 0x697160]Could not find codec parameters (Audio: 0x0006, 22050 Hz, mono) [lavf] Video stream found, -vid 0 [lavf] Audio stream found, -aid 1 VIDEO: [FLV1] 240x180 0bpp 1000.000 fps 0.0 kbps ( 0.0 kbyte/s) [V] filefmt:44 fourcc:0x31564C46 size:240x180 fps:1000.00 ftime:=0.0010 ** MUXER_LAVF ***************************************************************** REMEMBER: MEncoder's libavformat muxing is presently broken and can generate INCORRECT files in the presence of B frames. Moreover, due to bugs MPlayer will play these INCORRECT files as if nothing were wrong! ******************************************************************************* OK, exit Opening video filter: [expand osd=1] Expand: -1 x -1, -1 ; -1, osd: 1, aspect: 0.000000, round: 1 ========================================================================== Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family Selected video codec: [ffflv] vfm: ffmpeg (FFmpeg Flash video) ========================================================================== audiocodec: framecopy (format=6 chans=1 rate=22050 bits=16 B/s=0 sample-0) VDec: vo config request - 240 x 180 (preferred colorspace: Planar YV12) VDec: using Planar YV12 as output csp (no 0) Movie-Aspect is undefined - no prescaling applied. videocodec: libavcodec (240x180 fourcc=31564c46 [FLV1]) VIDEO CODEC ID: 22 AUDIO CODEC ID: 10007, TAG: 0 Writing header... [NULL @ 0x67d110]codec not compatible with flv Floating point exception </code></pre> <p>c) Is there a way for mencoder to decode and encode flvs correctly?</p> <p>So the only way I've found so far to join flvs, is to use ffmpeg to go back and forth between flv and avi, and use mencoder to join the avis:</p> <pre><code>ffmpeg -i input.flv -vcodec rawvideo -acodec pcm_s16le -r 15 file.avi mencoder -o output.avi -oac copy -ovc copy -noskip file.avi file.avi ffmpeg -i output.avi output.flv </code></pre> <p>d) There must be a better way to achieve this... Which one?</p> <p>e) Because of the problem of the framerate, though, only flvs with constant framerate (like the one I recorded through <a href="http://ffmpeg.mplayerhq.hu/faq.html#SEC31" rel="noreferrer">facebook</a>) will be converted correctly to avis, but this won't work for the flvs I seem to be recording (like <a href="http://www.marc-andre.ca/posts/blog/webcam/test-wowza.flv" rel="noreferrer">this one</a> or <a href="http://www.marc-andre.ca/posts/blog/webcam/test-red5-publisher.flv" rel="noreferrer">this one</a>). Is there a way to do this for these flvs too?</p> <p>Any help would be very appreciated.</p>
<p>I thought it would be a nice learning exercise to rewrite it in Ruby.</p> <p>It was.</p> <p>Six months later and three gems later, <a href="http://github.com/marcandre/flvedit" rel="nofollow noreferrer">here's the released product</a>.</p> <p>I'll still be working a bit on it, but it works.</p>
<p>dont know if this will actually work but try using this command : </p> <pre><code>cat yourVideos/*.flv &gt;&gt; big.flv </code></pre> <p>this will probably damage meta information so after executing that command use "flvtool" (ruby script you can find it with google) to fix it.</p>
9,324
<p>What are the differences between delegates and an events? Don't both hold references to functions that can be executed?</p>
<p>An <strong>Event</strong> declaration adds a layer of abstraction and protection on the <strong>delegate</strong> instance. This protection prevents clients of the delegate from resetting the delegate and its invocation list and only allows adding or removing targets from the invocation list.</p>
<p>An event in .net is a designated combination of an Add method and a Remove method, both of which expect some particular type of delegate. Both C# and vb.net can auto-generate code for the add and remove methods which will define a delegate to hold the event subscriptions, and add/remove the passed in delegagte to/from that subscription delegate. VB.net will also auto-generate code (with the RaiseEvent statement) to invoke the subscription list if and only if it is non-empty; for some reason, C# doesn't generate the latter.</p> <p>Note that while it is common to manage event subscriptions using a multicast delegate, that is not the only means of doing so. From a public perspective, a would-be event subscriber needs to know how to let an object know it wants to receive events, but it does not need to know what mechanism the publisher will use to raise the events. Note also that while whoever defined the event data structure in .net apparently thought there should be a public means of raising them, neither C# nor vb.net makes use of that feature.</p>
4,884
<p>So yesterday I got my power supply in the mail and I thought, let's check it out!</p> <p>I put all the wires in correctly (as shown in this YouTube video, <a href="https://www.youtube.com/watch?v=X8GhVKG2Nno" rel="nofollow noreferrer">Anet A8 power supply unit fuse blown</a>, I just searched really quickly, this person has the same problem as me) and &quot;BANG&quot;, it blew.</p> <p><a href="https://i.stack.imgur.com/kBCjk.png" rel="nofollow noreferrer" title="Image from YouTube video"><img src="https://i.stack.imgur.com/kBCjk.png" alt="Image from YouTube video" title="Image from YouTube video" /></a></p> <p>Luckily the only thing broken on it is the fuse, for which I can get a new one, but my main question is .. why? why did it blow out? Did I wire it up wrong? The 12 V output goes to a RAMPS 1.4 board which is working correctly.</p> <p>It worked the first time I plugged it in; the little green light went on. The second time a nice &quot;big bang&quot;. When I tested it the first time, I didn't add the 12 V wires to the RAMPS board yet. When I did, the fuse of the PSU blew out.</p> <p>The board is a RepRap RAMPS 1.4, which works fine when connected via USB to laptop.</p> <p>Upon closer inspection I found a burned out resistor in the circuit of the power supply, maybe this caused the bang?</p> <h3>BIG update!</h3> <p>I opened it up and flipped the board, and noticed that there was a big ol' blob of tin connected to one of the pins I connected my wires to. I am very sure that this blob shouldn't connect to that pin at all, hence shorting my board.</p> <p>Is this the cause?</p> <p><a href="https://i.stack.imgur.com/lGGSF.jpg" rel="nofollow noreferrer" title="Close up of PCB"><img src="https://i.stack.imgur.com/lGGSF.jpg" alt="Close up of PCB" title="Close up of PCB" /></a></p> <p><a href="https://i.stack.imgur.com/lKdWI.jpg" rel="nofollow noreferrer" title="Close up of PCB - Highlighted potential short circuit"><img src="https://i.stack.imgur.com/lKdWI.jpg" alt="Close up of PCB - Highlighted potential short circuit" title="Close up of PCB - Highlighted potential short circuit" /></a></p> <p>Here is a link to the webpage I bought it from: <a href="https://m.banggood.com/nl/12V-20A-240W-Anet-Power-Supply-Dual-input-Centralized-Power-Monitoring-For-3D-Printer-p-1108988.html" rel="nofollow noreferrer">Anet® 12 V 20 A 240 W Power Supply Dual-input Centralized Power Monitoring For 3D Printer</a></p> <p>Here is how I wired it up at the PSU side:</p> <p><a href="https://i.stack.imgur.com/yHZxm.png" rel="nofollow noreferrer" title="Power supply connections"><img src="https://i.stack.imgur.com/yHZxm.png" alt="Power supply connections" title="Power supply connections" /></a></p> <p>At the RAMPS side:</p> <p><a href="https://i.stack.imgur.com/Od4en.jpg" rel="nofollow noreferrer" title="RAMPS board connections"><img src="https://i.stack.imgur.com/Od4en.jpg" alt="RAMPS board connections" title="RAMPS board connections" /></a></p> <p>This shows the internals of the PSU, it clearly shows burn marks:</p> <p><a href="https://i.stack.imgur.com/EuSfm.jpg" rel="nofollow noreferrer" title="Overview of the failed electronic component in the PSU"><img src="https://i.stack.imgur.com/EuSfm.jpg" alt="Overview of the failed electronic component in the PSU" title="Overview of the failed electronic component in the PSU" /></a></p>
<p>You need to closely look at how to connect to the output connectors. In this case it appears that you have wired it correctly according to the stamped in markings above the connectors. You have chosen not to connect the earth, this is strongly advised.</p> <p>Did you check if the power switch matches the voltage of your country? If you are in Europe the switch should be set to 230&nbsp;V, not 115&nbsp;V (which is used in America).</p> <p>E.g. for the following power supply you see such a switch on the side: <a href="https://i.stack.imgur.com/cIUcA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cIUcA.png" alt="PSU voltage setting"></a></p> <p>If a PSU is connected without load and works, and short circuits when externals are connected there are a few options:</p> <ul> <li>there is a short in the connected printer board,</li> <li>the load that the board takes is too large for the PSU,</li> <li>the PSU cannot deliver the load,</li> <li>the PSU was faulty to begin with.</li> </ul>
<h3>Unless you know what you're doing, do not remove the covers from a PSU. The components can store a lethal charge long after power is removed, even if the fuse is blown.</h3> <p>My guess is something loose (now vapourised) in the PSU. Electronics have a tendancy of failing either quite soon after manufacture, or lasting reasonably well. This is described with the <a href="https://en.wikipedia.org/wiki/Bathtub_curve" rel="nofollow noreferrer">Bathtub Curve</a>.</p> <p>Looking at the failure, there was a significant short circuit somewhere - quite likely within the PSU itself. This doesn't mean you can be sure that the RAMPS board survived, but it has a reasonable chance of not being harmed.</p> <p>There is no significant chance of the PSU failing like that simply due to an excessive load in its output - unless it was overloaded for a significant period of time. Generally these PSUs will have some degree of overload protection even if they are not explicitly designed to survive an overload.</p>
1,214
<p>I want to disable the selection of certain rows in a datagridview.</p> <p>It must be possible to remove the select property for one or more datagridview rows in a datagridview shown in a winform. The goal is that the user can't select certain rows. (depending on a condition)</p> <p>Thankx,</p>
<p>If SelectionMode is FullRowSelect, then you'll need to override SetSelectedRowCore for that DataGridView, and not call the base SetSelectedRowCore for rows you don't want selected.</p> <p>If SelectionMode is not FullRowSelect, you'll want to additionally override SetSelectedCellCore (and not call the base SetSelectedCellCore for rows you don't want selected), as SetSelectedRowCore will only kick in if you click the row header and not an individual cell.</p> <p>Here's an example:</p> <pre><code>public class MyDataGridView : DataGridView { protected override void SetSelectedRowCore(int rowIndex, bool selected) { if (selected &amp;&amp; WantRowSelection(rowIndex)) { base.SetSelectedRowCore(rowIndex, selected); } } protected virtual void SetSelectedCellCore(int columnIndex, int rowIndex, bool selected) { if (selected &amp;&amp; WantRowSelection(rowIndex)) { base.SetSelectedRowCore(rowIndex, selected); } } bool WantRowSelection(int rowIndex) { //return true if you want the row to be selectable, false otherwise } } </code></pre> <p>If you're using WinForms, crack open your designer.cs for the relevant form, and change the declaration of your DataGridView instance to use this new class instead of DataGridView, and also replace the this.blahblahblah = new System.Windows.Forms.DataGridView() to point to the new class.</p>
<pre><code>Private Sub dgvSomeDataGridView_SelectionChanged(sender As Object, e As System.EventArgs) Handles dgvSomeDataGridView.SelectionChanged dgvSomeDataGridView.ClearSelection() End Sub </code></pre>
9,692
<p>I'd like to create a spring bean that holds the value of a double. Something like:</p> <pre><code>&lt;bean id="doubleValue" value="3.7"/&gt; </code></pre>
<p>Declare it like this:</p> <pre><code>&lt;bean id="doubleValue" class="java.lang.Double"&gt; &lt;constructor-arg index="0" value="3.7"/&gt; &lt;/bean&gt; </code></pre> <p>And use like this:</p> <pre><code>&lt;bean id="someOtherBean" ...&gt; &lt;property name="value" ref="doubleValue"/&gt; &lt;/bean&gt; </code></pre>
<p>Why don't you just use a <strong>Double</strong>? any reason?</p>
8,461
<p>I need to have a summary field in each page of the report and in page 2 and forward the same summary has to appear at the top of the page. Anyone know how to do this? Ex:</p> <pre><code>&gt; &gt; Page 1 &gt; &gt; Name Value &gt; a 1 &gt; b 3 &gt; Total 4 &gt; &gt; Page 2 &gt; Name Value &gt; Total Before 4 &gt; c 5 &gt; d 1 &gt; Total 10 </code></pre>
<p>Create a new Running Total Field called, for example "RTotal". In "Field to summarize" select "Value", in "Type of summary" select "sum", under "Evaluate" select "For each record". You can then drag this field into your report to use as the "Total" at the bottom of each page.</p> <p>You cannot use this running total field in the page header too, however, because Crystal will add the value in the first row on the page to it first (so in your example it would show 9 rather than 4 at the top of page 2). To work around this, create a formula field which subtracts the current value of the Value field from the running total (e.g. {#RTotal}-{TableName.Value}), and put this formula field in your page header.</p>
<p>I do not understand your question all the way.</p> <p>If you need an overall summary that is repeated, you would need a sub-report that have shown in the report multiple times.</p>
4,550
<p>I've come to love <a href="http://en.wikipedia.org/wiki/Amazon_Elastic_Compute_Cloud" rel="nofollow noreferrer">Amazon's EC2 service</a> and I'm looking for something similar that supports the ability to save a running Windows server image and start new instances from it.</p> <p>I contacted <a href="http://www.gogrid.com/" rel="nofollow noreferrer">GoGrid</a> (the feature is planned in future) and <a href="http://www.mosso.com/" rel="nofollow noreferrer">Mosso</a> (no joy)</p> <p>Anyone know of any hosting/cloud providers that can dothis?</p>
<p>I have just received a message from Amazon to the effect that that they will be <a href="http://aws.amazon.com/windows/" rel="nofollow noreferrer">supporting Windows Server on EC2</a> this fall.</p> <p>Wahaay!!</p>
<p>Seems like dealing with licensing issues would be nightmarish for the host.</p>
4,248
<p>The Y-axis belt just broke on my Ender 3 v2. I believe that it was over tensioned from the factory. When I initially assembled the printer, I noticed that the Y-axis tensioner was tightened almost all the way. The belt itself felt very stiff. The X-axis belt, which I installed upon assembly, didn't require a lot of tightening. I have ordered replacement belt material and clips to make new belts.</p> <p>What is the proper tension for both the X- and Y-axis belts?</p>
<p>Generally, a timing belt is a complicated device and many things depend on its internal construction and materials (it may be damaged when bound in wrong direction, or when cut, and when overtighten of course, etc.). There is also physics and math applicable, based on <a href="https://en.wikipedia.org/wiki/Mersenne%27s_laws" rel="nofollow noreferrer">Mersenne's laws</a>.</p> <p>Some vendors provide calculators (online or as phone apps), which can calculate tension (force in Newtons or lbs) or the frequency (Hz). Therefore often the advice is to tension the belt until some (bass) sound is present - and professionals would tune belts with a sound tuner. There are also hints that belts should be possible to connect with fingers with slight or significant pressure (so not consistent). There is also visual guideline: when you slowly move the carriage with hand, the belt should remain straight. (Slowly, because belt is elastic and may behave different when moving carriage stronger and faster against friction of pulley.)</p> <p>I would suggest to read <a href="https://www.3dprintingspot.com/post/3d-printer-belt-tension-everything-that-you-need-to-know" rel="nofollow noreferrer">this article on 3dprintingspot.com</a> for many practical suggestions.</p>
<p>Mine came from the factory tight enough that it doesn't sag at all, but not so tight that it feels hard or stiff or difficult to deflect a bit with gentle pressure. With the bed pushed all the way to the back, I can push the y-axis belt to the side about 1/8&quot; with gentle pressure, and it feels like that's about as far as it's going to go even if I were to push harder. Seems to work really well without a lot of unnecessary force.</p>
1,822
<p>I was reading a book on programming skills wherein the author asks the interviewee, "How do you crash a JVM?" I thought that you could do so by writing an infinite for-loop that would eventually use up all the memory.</p> <p>Anybody has any idea?</p>
<p><a href="http://en.wikipedia.org/wiki/Java_Native_Interface" rel="noreferrer">JNI</a>. In fact, with JNI, crashing is the default mode of operation. You have to work extra hard to get it not to crash.</p>
<p>If a 'Crash' is anything that interrupts the jvm/program from normal termination, then an Un-handled exception could do this.</p> <pre><code>public static void main(String args[]){ int i = 1/0; System.out.print(i); // This part will not be executed due to above unhandled exception } </code></pre> <p>So, it depends on what type of CRASH ?!</p>
9,097
<p>I installed VS SP1 and played around with Entity Framework.</p> <p>I created a schema from an existing database and tried some basic operations.</p> <p>Most of it went well, except the database schema update.</p> <p>I changed the database in every basic way:</p> <ul> <li>added a new table</li> <li>deleted a table</li> <li>added a new column to an existing table</li> <li>deleted a column from an existing table</li> <li>changed the type of an existing column</li> </ul> <p>The first three went well, but the type change and the column deletion did not followed the database changes.</p> <p>Is there any way to make is work from the designer? Or is it not supported at the moment? I didn't find any related material yet, but still searching.</p>
<p>I would guess that possibly those don't happen because they would break the build for existing code, but that's just a guess on my part.</p> <p>Here's my logic:</p> <p>First, EF is supposed to be more than 1:1 table mapping, so it's quite possible that just because you are deleting a column from table A doesn't mean that for that entity, there shouldn't be a property Description. You might just map that property to another table.</p> <p>Second, changing a type could just break builds. that's the only rationale there.</p>
<p>You need to delete the column by yourself from the designer or the XML file.</p>
3,324
<p>How do I create an rss feed in ASP.Net? Is there anything built in to support it? If not, what third-party tools are available?</p> <p>I'm thinking webforms, not MVC, though I suppose since this isn't a traditional page the difference may be minimal.</p>
<p>For built-in, there's nothing stopping you from using XmlDocument or XDocument (3.5) to build up the required XML for RSS. It's more work than it's worth though.</p> <p>I use the <a href="http://www.codeplex.com/Argotic" rel="nofollow noreferrer">Argotic Syndication Framework</a> and serve the feeds through Generic Handlers (.ashx) with the content type set to text/xml.</p> <p>The <a href="http://www.codeplex.com/ASPNETRSSToolkit" rel="nofollow noreferrer">RSSToolkit</a> is also nice. It comes with an RSSDataSource control if you're into that sort of thing. It also includes a control that will automatically insert the meta tag required for feed autodiscovery in browsers. I found the build provider for creating feeds to be a little kludgey however.</p>
<p>Create an HTTP Handler to create a RSS feed</p>
8,149
<p>Ideally, I'm looking for a templated logical Set class. It would have all of the standard set operations such as Union, Intersection, Etc., and collapse duplicated items.</p> <p>I ended up creating my own set class based on the C# Dictionary&lt;>- just using the Keys.</p>
<p><a href="http://msdn.microsoft.com/en-us/library/bb359438.aspx" rel="noreferrer"><code>HashSet&lt;T&gt;</code></a> is about the closest you'll get, I think.</p>
<p>Here's a simple implementation:</p> <pre><code>public sealed class MathSet&lt;T&gt; : HashSet&lt;T&gt;, IEquatable&lt;MathSet&lt;T&gt;&gt; { public override int GetHashCode() =&gt; this.Select(elt =&gt; elt.GetHashCode()).Sum().GetHashCode(); public bool Equals(MathSet&lt;T&gt; obj) =&gt; SetEquals(obj); public override bool Equals(object obj) =&gt; Equals(obj as MathSet&lt;T&gt;); public static bool operator ==(MathSet&lt;T&gt; a, MathSet&lt;T&gt; b) =&gt; ReferenceEquals(a, null) ? ReferenceEquals(b, null) : a.Equals(b); public static bool operator !=(MathSet&lt;T&gt; a, MathSet&lt;T&gt; b) =&gt; !(a == b); } </code></pre> <p>Example usage:</p> <pre><code>var a = new MathSet&lt;int&gt; { 1, 2, 3 }; var b = new MathSet&lt;int&gt; { 3, 2, 1 }; var c = a.Equals(b); // true var d = new MathSet&lt;MathSet&lt;int&gt;&gt; { a, b }; // contains one element var e = a == b; // true </code></pre> <p>See <a href="https://stackoverflow.com/questions/47688779/set-class-with-mathematical-set-equality-by-default">this question</a> for why this approach was considered over <code>HashSet</code>.</p>
3,164
<p>I'm pretty green still when it comes to web programming, I've spent most of my time on client applications. So I'm curious about the common exploits I should fear/test for in my site.</p>
<p><a href="http://www.owasp.org/index.php/Main_Page" rel="noreferrer">OWASP</a> keeps a list of the <a href="http://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project" rel="noreferrer">Top 10</a> web attacks to watch our for, in addition to a ton of other useful security information for web development.</p>
<p>The most common are probably database injection attacks and cross-site scripting attacks; mainly because those are the easiest to accomplish (that's likely because those are the ones programmers are laziest about).</p>
4,310
<p>I'm aware of things like <code>onchange</code>, <code>onmousedown</code> and <code>onmouseup</code> but is there a good reference somewhere that lists all of them complete with possibly a list of the elements that they cover?</p>
<p>W3Schools seems to have a good Javascript events reference: <a href="http://www.w3schools.com/jsref/dom_obj_event.asp" rel="noreferrer">HTML DOM Events</a></p>
<p>Here is a pretty good JavaScript event reference with the elements they are for:<br> <a href="http://www.globalguideline.com/JavaScript_Guide/Java_Script_Events.php" rel="nofollow noreferrer">JavaScript Tutorial >> JavaScript Events</a></p>
2,840
<p>This might be on the "discussy" side, but I would really like to hear your view on this.</p> <p>Previously I have often written data access classes that handled both reading and writing, which often led to poor naming, like FooIoHandler etc. The rule of thumb that classes that are hard to name probably are poorly designed suggests that this is not a good solution.</p> <p>So, I have recently started splitting the data access into FooWriter and FooReader, which leads to nicer names and gives some additional flexibility, but at the same time I kind of like keeping it together, if the classes are not to big.</p> <p>Is a reader/writer separation a better design, or should I combine them? If I should combine them, what the heck should I name the class?</p> <p>Thanks /Erik</p>
<p>ORM might be your best solution.<br> Or use a repository type pattern, with a "thingContext" object that is responsible for state persistence.</p> <p>Personally, I use the activeRecord pattern, where save logic is baked into a base class, but I'm leaving it in favor of an nHibernate style repository pattern. The allowance for DDD and testing things without a db is very nice to have in a framework type situation, where my business logic is now gaining traction for a new UI.</p>
<p>When given the choice I generally subclass the reader to create the writer. </p>
4,923
<p>How do I setup Public-Key Authentication for SSH?</p>
<p>If you have SSH installed, you should be able to run..</p> <pre><code>ssh-keygen </code></pre> <p>Then go through the steps, you'll have two files, <code>id_rsa</code> and <code>id_rsa.pub</code> (the first is your private key, the second is your public key - the one you copy to remote machines)</p> <p>Then, connect to the remote machine you want to login to, to the file <code>~/.ssh/authorized_keys</code> add the contents of your that <code>id_rsa.pub</code> file.</p> <p>Oh, and <code>chmod 600</code> all the <code>id_rsa*</code> files (both locally and remote), so no other users can read them:</p> <pre><code>chmod 600 ~/.ssh/id_rsa* </code></pre> <p>Similarly, ensure the remote <code>~/.ssh/authorized_keys</code> file is <code>chmod 600</code> also:</p> <pre><code>chmod 600 ~/.ssh/authorized_keys </code></pre> <p>Then, when you do <code>ssh remote.machine</code>, it should ask you for the key's password, not the remote machine.</p> <hr> <p>To make it nicer to use, you can use <code>ssh-agent</code> to hold the decrypted keys in memory - this means you don't have to type your keypair's password every single time. To launch the agent, you run (including the back-tick quotes, which eval the output of the <code>ssh-agent</code> command)</p> <pre><code>`ssh-agent` </code></pre> <p>On some distros, ssh-agent is started automatically. If you run <code>echo $SSH_AUTH_SOCK</code> and it shows a path (probably in /tmp/) it's already setup, so you can skip the previous command.</p> <p>Then to add your key, you do</p> <pre><code>ssh-add ~/.ssh/id_rsa </code></pre> <p>and enter your passphrase. It's stored until you remove it (using the <code>ssh-add -D</code> command, which removes all keys from the agent)</p>
<p>For windows <a href="http://the.earth.li/~sgtatham/putty/0.53b/htmldoc/Chapter8.html" rel="noreferrer">this</a> is a good introduction and guide</p> <p>Here are some good ssh-agents for systems other than linux.</p> <ul> <li>Windows - <a href="http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html" rel="noreferrer">pageant</a></li> <li>OS X - <a href="http://www.askbjoernhansen.com/2005/01/07/sshkeychain_ssh.html" rel="noreferrer">SSHKeychain</a></li> </ul>
2,889
<p>Does anyone know if it is possible to display a prompt to a user/administrator when activating or installing a sharepoint feature? </p> <p>I am writing a custom webpart and it is connecting to a separate database, I would like to allow the administrator to select or type in a connection string when installing the .wsp file or activating the feature.</p> <p>I am looking inside the FeatureActivated event and thinking of using the SPWebConfigModification class to actually write the connection string to the web.config files in the farm. </p> <p>I do not want to hand edit the web.configs or hard code the string into the DLL.</p> <p>If you have other methods for handling connection strings inside sharepoint I would be interested in them as well.</p>
<p>Unfortunately there is no way to swap to a screen where you can get user via the feature activation process. Couple of comments for you:</p> <ol> <li>I'm assuming the connection string is going to be different for every installation, so there is no way you can include it directly in the Solution. </li> <li>I'm assuming that you couldn't programmatically construct this during installation.</li> </ol> <p>Therefore, you need some way to get user input. Here are a couple of options:</p> <ol> <li>It could be a web part property, though this would mean setting it each and every time the web part was added, and you would need to then maitain those settings individually.</li> <li>You could build out your own _layouts settings screen (good post: <a href="http://community.zevenseas.com/Blogs/Robin/archive/2008/03/17/lcm-creating-custom-application-page-and-using-the-propertybag-more-detailed.aspx" rel="nofollow noreferrer">http://community.zevenseas.com/Blogs/Robin/archive/2008/03/17/lcm-creating-custom-application-page-and-using-the-propertybag-more-detailed.aspx</a>), and from there users can maintain the property, storing it in either the Web Property bag, or inside the Web.Config. I try to avoid using the Web.Config where I can, but if you do wish to go this route then MAKE SURE you use the SPWebConfigModification class (Read this great blog: <a href="http://www.crsw.com/mark/Lists/Posts/Post.aspx?ID=32" rel="nofollow noreferrer">http://www.crsw.com/mark/Lists/Posts/Post.aspx?ID=32</a>)</li> <li>Finally, a technique I often use is storing configuration information in a SharePoint List. Chris O'Brien has a great framework for that here: <a href="http://www.codeplex.com/SPConfigStore" rel="nofollow noreferrer">http://www.codeplex.com/SPConfigStore</a></li> </ol> <p>Hope that helps, Daniel</p>
<p>Sounds good. I will look at these possible solutions.</p> <p>I do not think #1 will work since I am deploying multiple webparts inside a single solution which all use the same connectionString.</p> <p>#3 sounds like a very clean solution. I see the config items are cached so it looks like if I need to store a connection string, I will not be hit with a SP lookup each time I need that string.</p> <p><a href="http://www.codeplex.com/CKS/SourceControl/FileView.aspx?itemId=222757&amp;changeSetId=11423" rel="nofollow noreferrer">While searching for a solution I did stumble across another method.</a> </p> <p>If you dig around their code, I looks like they have created an installer that accepts application specific values, adds the values into a FeatureTemplate.xml file and passes them to the SPFeatureReceiverProperties object in the Reciever.</p> <p>I was about to start tackling this method, but I think #3 would be better. </p> <p>Thank you, Keith</p>
3,033
<p>I’m looking at rewriting a portion of our application in C# (currently legacy VB6 code). The module I am starting with is responsible for importing data from a variety of systems into our database. About 5-6 times a year, a new client asks us to write a new import for the system that they use. Presently, this requires us to release a new version of our software for each new import option we add to the application. </p> <p>One of the goals of the rewrite is to make the application support plug-ins. Every new import can become a separate assembly which the host application will recognize and allow the end user to interact with. This will hopefully simplify life to some degree as we can simply drop a new assembly into the directory and have it be recognized and used by the main (host) application.</p> <p>One of the items I am struggling with relates to the differences between the import options we currently support. In some cases we actually let the user point to a directory and read all of the files within the directory into our system. In other cases we allow them to point to a single file and import its contents. Additionally, some imports have a date range restriction that the user applies while others do not.</p> <p>My question is, how can I design the application in a manner that allows for some flexibility among the imports we build and support while at the same time implementing a common interface that will allow the host application to easily recognize the plug-ins and the options that each one exposes to the user?</p>
<p>I would recommend you take a look at the Managed Add-In Framework that shipped with .NET 3.5. The <a href="http://blogs.msdn.com/clraddins/" rel="nofollow noreferrer">Add-In team</a> has posted some samples and tools at <a href="http://www.codeplex.com/clraddins" rel="nofollow noreferrer">CodePlex site</a> as well..</p>
<p>.Net 3.5 has the system.Addin namespace.</p> <p>This thread also has some good information for older versions of the framework:<br> h<a href="http://forums.devshed.com/net-development-87/system-plugin-532149.html" rel="nofollow noreferrer">ttp://forums.devshed.com/net-development-87/system-plugin-532149.html</a></p>
6,838
<p>I have a rather classic UI situation - two ListBoxes named <code>SelectedItems</code> and <code>AvailableItems</code> - the idea being that the items you have already selected live in <code>SelectedItems</code>, while the items that are available for adding to <code>SelectedItems</code> (i.e. every item that isn't already in there) live in <code>AvailableItems</code>.</p> <p>Also, I have the <code>&lt;</code> and <code>&gt;</code> buttons to move the current selection from one list to the other (in addition to double clicking, which works fine).</p> <p>Is it possible in WPF to set up a style/trigger to enable or disable the move buttons depending on anything being selected in either ListBox? <code>SelectedItems</code> is on the left side, so the <code>&lt;</code> button will move the selected <code>AvailableItems</code> to that list. However, if no items are selected (<code>AvailableItems.SelectedIndex == -1</code>), I want this button to be disabled (<code>IsEnabled == false</code>) - and the other way around for the other list/button.</p> <p>Is this possible to do directly in XAML, or do I need to create complex logic in the codebehind to handle it?</p>
<p>Here's your solution.</p> <pre><code>&lt;Button Name="btn1" &gt;click me &lt;Button.Style&gt; &lt;Style&gt; &lt;Style.Triggers&gt; &lt;DataTrigger Binding ="{Binding ElementName=list1, Path=SelectedIndex}" Value="-1"&gt; &lt;Setter Property="Button.IsEnabled" Value="false"/&gt; &lt;/DataTrigger&gt; &lt;/Style.Triggers&gt; &lt;/Style&gt; &lt;/Button.Style&gt; &lt;/Button&gt; </code></pre>
<p>Less code solution:</p> <pre><code>&lt;Button Name="button1" IsEnabled="{Binding ElementName=listBox1, Path=SelectedItems.Count}" /&gt; </code></pre> <p>If count is 0 that seems to map to false, > 0 to true.</p>
3,849
<p>Can anyone recommend any good <strong>add-ons</strong> or <strong>plugins</strong> for <code>Microsoft Visual Studio</code>?<br> Freebies are preferred, but if it is worth the cost then that's fine.</p>
<p><a href="http://weblogs.asp.net/alex_papadimoulis/archive/2004/05/25/Smart-Paster-1.1-Add-In---StringBuilder-and-Better-C_2300_-Handling.aspx" rel="noreferrer">SmartPaster</a> - (FREE) Copy/Paste code generator for strings</p> <p><a href="http://ankhsvn.open.collab.net/" rel="noreferrer">AnkhSvn</a> - (FREE) SVN Source Control Integration for VS.NET</p> <p><a href="http://www.visualsvn.com/server/" rel="noreferrer">VisualSVN Server</a> - (FREE) Source Control</p> <p><a href="http://www.jetbrains.com/resharper/index.html" rel="noreferrer">ReSharper</a> - IDE enhancement that helps with refactoring and productivity</p> <p><a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/Coding_Assistance/" rel="noreferrer">CodeRush</a> - Code gen macros on steroids</p> <p><a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/Refactoring/" rel="noreferrer">Refactor</a> - Code refactoring aid</p> <p><a href="http://www.codemaid.net/" rel="noreferrer">CodeMaid</a> (FREE) - Code cleanup, organization and complexity analysis</p> <p><a href="http://www.codesmithtools.com/" rel="noreferrer">CodeSmith</a> - Code Generator</p> <p><a href="http://www.roland-weigelt.de/ghostdoc/" rel="noreferrer">GhostDoc</a> - (FREE) Simple code commenting tool</p> <p><a href="http://www.devexpress.com/Downloads/Visual_Studio_Add-in/DXCore/" rel="noreferrer">DXCore</a> (FREE) and its many awesome plugins: <a href="http://code.google.com/p/dxcorecommunityplugins/" rel="noreferrer">DxCore Community Plugins</a>, <a href="http://code.google.com/p/cr-documentor/" rel="noreferrer">CR_Documentor</a>, <a href="http://joel.fjorden.se/static.php?page=CodeStyleEnforcer" rel="noreferrer">CodeStyleEnforcer</a>, <a href="http://www.rorybecker.me.uk/DevExpress/Plugins/Community/RedGreen/" rel="noreferrer">RedGreen</a></p> <p><a href="http://www.testdriven.net/" rel="noreferrer">TestDriven.Net</a> - (FREE/PAY) Unit Testing Aid</p> <p><a href="http://www.red-gate.com/products/reflector/" rel="noreferrer">Reflector</a> - (PAY) Feature rich .Net Disassembler <a href="http://www.codeplex.com/reflectoraddins" rel="noreferrer">Reflector AddIn's</a></p> <p><a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=0AA30AE8-C73B-4BDD-BB1B-FE697256C459&amp;displaylang=en" rel="noreferrer">Web Deployment Projects</a> - Provides additional functionality to build and deploy Web sites and Web applications (<a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=0AA30AE8-C73B-4BDD-BB1B-FE697256C459&amp;displaylang=en" rel="noreferrer">source</a>).</p> <p>StudioTools - (FREE) Navigation assistant, code metrics tool, incremental search, file explorer in visual studio and tear off editor windows. Moved from <a href="https://web.archive.org/web/20100218144023/http://www.exactmagic.com/products/studiotools/index.html" rel="noreferrer">old site (archive.org)</a> to <a href="http://submain.com/products/studiotools.aspx" rel="noreferrer">new site</a> and discontinued.</p>
<ul> <li>Resharper (Agree it sucks you have to pay extra to get this, but well work the money)</li> <li><p>GhostDoc (Takes away any excuse for not having comments in your code)</p></li> <li><p>PowerCommands for VS 2008 (Forgot I even had this installed because it just adds a the little things that should have been there all along)</p></li> </ul>
2,487
<p>Often time I need to add a control to a dialog after the dialog has been generated via dialog template and CreateDialogIndirect. In these cases the tab order is set by the dialog template and there is no obvious way to change the tab order by including a newly created control.</p>
<p>I recently discovered that you can use SetWindowPos to accomplish this. Determine which control after which you want to insert the new control in the tab order then use SetWindowPos like this:</p> <pre><code>SetWindowPos(hNewControl, hOldControl, 0, 0, 0, 0, SWP_NOMOVE|SWP_NOSIZE); </code></pre> <p>This changes the z-order of controls which, in turn, establishes the tab order.</p>
<p>I know this is an old question but here is how to do it at compile time (which is preferable in the vast majority of cases): <a href="http://msdn.microsoft.com/en-us/library/7039hzb0(v=vs.80).aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/7039hzb0(v=vs.80).aspx</a></p> <p>My favourite method:</p> <ol> <li>From the View menu, choose Tab Order.</li> <li>Choose Assign Interactively.</li> <li>Double-click the tab order box beside the control you want to be the first control in the tab order.</li> <li>Click the tab order box for each of the other controls.</li> <li>Click anywhere on the form to save your changes and exit Tab Order mode, or press ESC to exit Tab Order mode without saving your changes.</li> </ol>
7,295
<p>Given a URL, what would be the most efficient code to download the contents of that web page? I am only considering the HTML, not associated images, JS and CSS.</p>
<pre><code>public static void DownloadFile(string remoteFilename, string localFilename) { WebClient client = new WebClient(); client.DownloadFile(remoteFilename, localFilename); } </code></pre>
<p>I think this is the fastest (download speed time with low latency) solution for download.</p> <pre><code>// WebClient vs HttpClient vs HttpWebRequest vs RestSharp // در نهایت به نظرم روش زیر سریعترین روشه HttpWebRequest Request = (HttpWebRequest)WebRequest.Create(url); Request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; Request.Proxy = null; Request.Method = "GET"; using (WebResponse Response = Request.GetResponse()) { using (StreamReader Reader = new StreamReader(Response.GetResponseStream())) { return Reader.ReadToEnd(); } } </code></pre>
4,584
<p><a href="http://twitter.com/codinghorror/statuses/901272685" rel="nofollow noreferrer">Source</a></p> <blockquote> <p>RegexOptions.IgnoreCase is more expensive than I would have thought (eg, should be barely measurable)</p> </blockquote> <p>Assuming that this applies to PHP, Python, Perl, Ruby etc as well as C# (which is what I assume Jeff was using), how much of a slowdown is it and will I incur a similar penalty with <code>/[a-zA-z]/</code> as I will with <code>/[a-z]/i</code> ?</p>
<p>Yes, [A-Za-z] will be much faster than setting the <code>RegexOptions.IgnoreCase</code>, largely because of Unicode strings. But it's also much more limiting -- [A-Za-z] does <em>not</em> match accented international characters, it's literally the A-Za-z ASCII set and nothing more.</p> <p>I don't know if you saw Tim Bray's answer to my message, but it's a good one:</p> <blockquote> <p>One of the trickiest issues in internationalized search is upper and lower case. This notion of case is limited to languages written in the Latin, Greek, and Cyrillic character sets. English-speakers naturally expect search to be case-insensitive if only because they’re lazy: if Nadia Jones wants to look herself up on Google she’ll probably just type in nadia jones and expect the system to take care of it.</p> <p>So it’s fairly common for search systems to “normalize” words by converting them all to lower- or upper-case, both for indexing and queries.</p> <p>The trouble is that the mapping between cases is not always as straightforward as it is in English. For example, the German lower-case character “ß” becomes “SS” when upper-cased, and good old capital “I” when down-cased in Turkish becomes the dotless “ı” (yes, they have “i”, its upper-case version is “İ”). I have read (but not verified first-hand) that the rules for upcasing accented characters such “é” are different in France and Québec. One of the results of all this is that software such as java.String.toLowerCase() tends to run astonishingly slow as it tries to work around all these corner-cases.</p> </blockquote> <p><a href="http://www.tbray.org/ongoing/When/200x/2003/10/11/SearchI18n" rel="noreferrer">http://www.tbray.org/ongoing/When/200x/2003/10/11/SearchI18n</a></p>
<p>If you're concerned about this, it may be worthwhile to set the case to all upper or all lower before you check.<br> For instance, in Perl:</p> <pre><code>$x = "abbCCDGBAdgfabv"; (lc $x) =~ /bad/; </code></pre> <p>May in some cases be better than</p> <pre><code>$x = "abbCCDGBAdgfabv"; $x =~ /bad/i; </code></pre>
5,195
<p>I'm looking for a multiline regex that will match occurrences after a blank line. For example, given a sample email below, I'd like to match "From: Alex". <code>^From:\s*(.*)$</code> works to match any From line, but I want it to be restricted to lines in the body (anything after the first blank line).</p> <pre> Received: from a server Date: today To: Ted From: James Subject: [fwd: hi] fyi ----- Forwarded Message ----- To: James From: Alex Subject: hi Party! </pre>
<p>I'm not sure of the syntax of C# regular expressions but you should have a way to anchor to the beginning of the string (not the beginning of the line such as ^). I'll call that "\A" in my example:</p> <pre><code>\A.*?\r?\n\r?\n.*?^From:\s*([^\r\n]+)$ </code></pre> <p>Make sure you turn the multiline matching option on, however that works, to make "." match \n</p>
<p>Writing complicated regular expressions for such jobs is a bad idea IMO. It's better to combine several simple queries. For example, first search for "\r\n\r\n" to find the start of the body, then run the simple regex over the body.</p>
9,336
<p>About 6 months ago I rolled out a site where every request needed to be over https. The only way at the time I could find to ensure that every request to a page was over https was to check it in the page load event. If the request was not over http I would response.redirect("<a href="https://example.com" rel="noreferrer">https://example.com</a>")</p> <p>Is there a better way -- ideally some setting in the web.config?</p>
<p>Please use <a href="https://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security" rel="noreferrer">HSTS</a> (HTTP Strict Transport Security)</p> <p>from <a href="http://www.hanselman.com/blog/HowToEnableHTTPStrictTransportSecurityHSTSInIIS7.aspx" rel="noreferrer">http://www.hanselman.com/blog/HowToEnableHTTPStrictTransportSecurityHSTSInIIS7.aspx</a></p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt; &lt;configuration&gt; &lt;system.webServer&gt; &lt;rewrite&gt; &lt;rules&gt; &lt;rule name="HTTP to HTTPS redirect" stopProcessing="true"&gt; &lt;match url="(.*)" /&gt; &lt;conditions&gt; &lt;add input="{HTTPS}" pattern="off" ignoreCase="true" /&gt; &lt;/conditions&gt; &lt;action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" /&gt; &lt;/rule&gt; &lt;/rules&gt; &lt;outboundRules&gt; &lt;rule name="Add Strict-Transport-Security when HTTPS" enabled="true"&gt; &lt;match serverVariable="RESPONSE_Strict_Transport_Security" pattern=".*" /&gt; &lt;conditions&gt; &lt;add input="{HTTPS}" pattern="on" ignoreCase="true" /&gt; &lt;/conditions&gt; &lt;action type="Rewrite" value="max-age=31536000" /&gt; &lt;/rule&gt; &lt;/outboundRules&gt; &lt;/rewrite&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre> <p><strong>Original Answer</strong> (replaced with the above on 4 December 2015)</p> <p>basically</p> <pre><code>protected void Application_BeginRequest(Object sender, EventArgs e) { if (HttpContext.Current.Request.IsSecureConnection.Equals(false) &amp;&amp; HttpContext.Current.Request.IsLocal.Equals(false)) { Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"] + HttpContext.Current.Request.RawUrl); } } </code></pre> <p>that would go in the global.asax.cs (or global.asax.vb)</p> <p>i dont know of a way to specify it in the web.config</p>
<p>-> Simply ADD [RequireHttps] on top of the public class HomeController : Controller.</p> <p>-> And add GlobalFilters.Filters.Add(new RequireHttpsAttribute()); in 'protected void Application_Start()' method in Global.asax.cs file.</p> <p>Which forces your entire application to HTTPS.</p>
6,928
<p>I am using LightBurn to laser engrave on wood. I am just trying to print some letters. </p> <p>In the softwares preview the output looks correct. The black part is where the laser should burn and the red part are traversal/scan lines <a href="https://i.stack.imgur.com/nLs8P.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nLs8P.png" alt="enter image description here"></a></p> <p>When i actually print it the negative space is burnt by the laser (basically where the traversal/scan lines are shown in the preview above)</p> <p><a href="https://i.stack.imgur.com/DjRPw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DjRPw.png" alt=""></a></p> <hr> <p>What I was able to figure out is that:</p> <ul> <li><code>M42 P4 S255</code> properly turns on the laser when I send this command on its own,</li> <li><code>M42 P4 S0</code> properly turns off the laser.</li> </ul> <p>But the issue is when I send the following G-code, the following happens:</p> <pre><code>M42 P4 S255 &lt;--- Laser turns on for a flash of a second G1 X15 &lt;--- By the time the movement starts the laser is already off. M42 P4 S0 </code></pre> <p>When i stopped using PWM (via the D11) and instead connected directly to D9 (which is for the fan) this issue stops occurring. So this issue is only occurring when I use PWM. Any Guidance on what to check</p> <p><strong>Update:</strong> I read the following on another forum. This might be the root cause here.</p> <blockquote> <p>M42 is an immediate command and would turn on the laser before it reached its intended start point, M106 and M107 are buffered so the on/off can happen in its intended locations.</p> </blockquote>
<p><code>M42</code> command is an immediate command. This means that it will run before the move GCode commands finish. This is exactly what I was facing. </p> <p>This video has the walk-through of solving the issue: <div class="youtube-embed"><div> <iframe width="640px" height="395px" src="https://www.youtube.com/embed/LEjgp77TIy4?start=625"></iframe> </div></div></p> <p>Here is the relevant PDF it talks about: <a href="https://www.v1engineering.com/wp-content/uploads/2016/01/MPCNC-laser-add-on-walk-through-Rev2.0.pdf" rel="nofollow noreferrer">The 2.8 watt, $100 Laser Upgrade for MPCNC</a>.</p> <p>Here is the relevant section on page 7 of the PDF:</p> <blockquote> <ol> <li><p>The laser driver requires a 5 volt TTL input control signal. The Marlin fan control Mcodes (M106 and M107) will be used to control the laser .Unfortunately, the Ramps fan output (D9) is a 12 volt signal so we can’t use it. We'll need a quick firmware edit to remap the fan output from pin D9 (12v) to pin 44(5v).</p></li> <li><p>Make a backup copy of your Marlin firmware folder first. Open the pins_RAMPS_13.h file in your Marlin firmware folder with a text editor (Wordpad). Search for the line where the fan pin is assigned and change it from pin 9 to pin 44.</p></li> <li><p>Save the changes and flash the revised firmware back onto your Mega board. </p></li> </ol> </blockquote>
<p>This is too long for a good comment but may fall short of being a true answer. If the mods prefer, I can recast it as a set of comments.</p> <p>There are several differences between using a GPIO pin as a binary data pin and using one as a PWM pin, and the behavior depends on several factors:</p> <ol> <li>Is the PWM pin a native PWN pin with hardware support, or is the PWM function being implemented with software?</li> <li>Has the PWM pin been initialized as a PWM pin?</li> <li>What processor type is used?</li> <li>What is the PWM frequency?</li> <li>Is the pin a TTL compatible output [0.4 V low, 2.7 V high]? CMOS? What Vcc?</li> <li>For that matter, what is the CPU?</li> </ol> <p>As @0scar points out, the fan control pin is typically not connected directly to the fan, but instead uses a FET to provide isolation and switch more current than the output pin can provide. Depending on the circuit, it may be inverting or non-inverting. M42 Pxx S255 may be full on or full off. When the fan is controlled through the fan G-code, the firmware can take possible inversion into account.</p> <p>You haven't said what the input circuit to the laser involves. </p> <ol> <li>It is active high or active low? </li> <li>Does it require a pulse train to keep the output on, or is it static? I don't know how yours works, but I could imagine designing a laser module to require a continuous stream of pulses to keep the beam active so that a failure in the drive circuit could not create a safety hazard.</li> <li>Is it a TTL compatible input [0.7 low, 2.4 high]? CMOS? What Vcc?</li> <li>Is it something else?</li> </ol> <p>Laser etching is generally on-topic for this group given the close association with 3D printing tech, but people are less familiar with the "standard systems". For some of us to be helpful (especially for me to be helpful) we need more of the circuitry and firmware context.</p>
1,321
<p>How do you test the usability of the user interfaces of your applications - be they web or desktop? Do you just throw it all together and then tweak it based on user experience once the application is live? Or do you pass it to a specific usability team for testing prior to release?</p> <p>We are a small software house, but I am interested in the best practices of how to measure usability.</p> <p>Any help appreciated.</p>
<p>I like <a href="http://friendfeed.com/paul" rel="noreferrer">Paul Buchheit's</a> answer on this from startup school. The short version of what he said listen to your users. Listen does not mean obey your users. Take in the data filter out all the bad advice and iteratively clean up the site. Lather, rinse, repeat. </p> <p>If you are a small shop you probably don't have a team of QA or Usability people or whatever to go through the site. Your users are going to be the ones that actually use the site though. Their feedback can be invaluable.</p> <p>If something is too hard for one of your users to use or too complex to understand why they should use it, then it might be the same way for 1000 other users. Find a simpler way of accomplishing the same thing. </p> <p>Once you have gathered all of this feedback and have a list of things to do, do the simplest ones first. That way you have forward moving usability progress. </p>
<p>I'm a strong believer in what I call 3-martini usability testing. When designing a system, imagine that the person who will be using it has just had 3 martinis. </p> <p>Before handing over the system to colleagues (other programmers, quality assurance, tech support) or usability testers, an informal test with a couple of friends and a bottle of vodka (outside of work, of course) can often prove instructive.</p>
3,880
<p>Given that my client code knows everything it needs to about the remoting object, what's the simplest way to connect to it?</p> <p>This is what I'm doing at the moment:</p> <pre><code>ChannelServices.RegisterChannel(new HttpChannel(), false); RemotingConfiguration.RegisterWellKnownServiceType( typeof(IRemoteServer), "RemoteServer.rem", WellKnownObjectMode.Singleton); MyServerObject = (IRemoteServer)Activator.GetObject( typeof(IRemoteServer), String.Format("tcp://{0}:{1}/RemoteServer.rem", server, port)); </code></pre>
<p>The first two lines are in the server-side code, for marshaling out the server object, yes?</p> <p>In that case, yes, the third line is the simplest you can get at client-side.</p> <p>In addition, you can serve out additional server-side objects from the <strong>MyServerObject</strong> instance, if you include public accessors for them in <strong>IRemoteServer</strong> interface, so, accessing those objects become the simple matter of method calls or property accesses on your main server object, so you don't have to use activator for every single thing:</p> <pre><code>//obtain another marshalbyref object of the type ISessionManager: ISessionManager = MyServerObject.GetSessionManager(); </code></pre>
<p>WCF. </p> <p>I have used IPC before there was a WCF, and believe me, IPC is a bear. And it isn't documented fully/correctly.</p> <p>What’s the simplest way to connect to a .NET remote server object? WCF.</p>
4,556
<p>Is it necessary to set large objects to <code>null</code> when implementing a <code>Dispose()</code> method?</p>
<p>Not usually.</p> <p>The garbage collector looks for rooted objects, and circular dependencies don't prevent collection if neither object is rooted.</p> <p>There is a caveat: if object A has a reference to object B, and object B is being disposed, you may want to clean up that relationship or else you could end up with a leak. The most common place this surfaces is in event handlers (the reference from A->B is one that B controls, because it subscribed to an event on A). In this case, if A is still rooted, B cannot be collected even though it's been disposed.</p>
<p>Think about the purpose of Disposable methods for a bit: it's usually because you're holding some resource that won't be released during garbage collection. This is usually something like a database connection or a file handle. Thus, once the Dispose method has been called, all those resources have been released.</p> <p>I'd argue that having nulls floating around is more harmful that having "zombie" objects floating around.</p>
7,257
<p>Hey so what I want to do is snag the content for the first paragraph. The string <code>$blog_post</code> contains a lot of paragraphs in the following format:</p> <pre><code>&lt;p&gt;Paragraph 1&lt;/p&gt;&lt;p&gt;Paragraph 2&lt;/p&gt;&lt;p&gt;Paragraph 3&lt;/p&gt; </code></pre> <p>The problem I'm running into is that I am writing a regex to grab everything between the first <code>&lt;p&gt;</code> tag and the first closing <code>&lt;/p&gt;</code> tag. However, it is grabbing the first <code>&lt;p&gt;</code> tag and the <strong>last</strong> closing <code>&lt;/p&gt;</code> tag which results in me grabbing everything.</p> <p>Here is my current code:</p> <pre><code>if (preg_match("/[\\s]*&lt;p&gt;[\\s]*(?&lt;firstparagraph&gt;[\\s\\S]+)[\\s]*&lt;\\/p&gt;[\\s\\S]*/",$blog_post,$blog_paragraph)) echo "&lt;p&gt;" . $blog_paragraph["firstparagraph"] . "&lt;/p&gt;"; else echo $blog_post; </code></pre>
<p>Well, sysrqb will let you match anything in the first paragraph assuming there's no other html in the paragraph. You might want something more like this</p> <pre><code>&lt;p&gt;.*?&lt;/p&gt; </code></pre> <p>Placing the <code>?</code> after your <code>*</code> makes it non-greedy, meaning it will only match as little text as necessary before matching the <code>&lt;/p&gt;</code>.</p>
<p>Using Regular Expressions for html parsing is never the right solution. You should be using XPATH for this particular case:</p> <pre><code>$string = &lt;&lt;&lt;XML &lt;a&gt; &lt;b&gt; &lt;c&gt;texto&lt;/c&gt; &lt;c&gt;cosas&lt;/c&gt; &lt;/b&gt; &lt;d&gt; &lt;c&gt;código&lt;/c&gt; &lt;/d&gt; &lt;/a&gt; XML; $xml = new SimpleXMLElement($string); /* Busca &lt;a&gt;&lt;b&gt;&lt;c&gt; */ $resultado = $xml-&gt;xpath('//p[1]'); </code></pre>
5,964
<p>What are all the possible ways in which we can get memory leaks in .NET?</p> <p>I know of two:</p> <ol> <li>Not properly un-registering <a href="http://diditwith.net/PermaLink,guid,fcf59145-3973-468a-ae66-aaa8df9161c7.aspx" rel="nofollow noreferrer">Event Handlers/Delegates</a>.</li> <li>Not disposing dynamic child controls in Windows Forms:</li> </ol> <p>Example:</p> <pre><code>// Causes Leaks Label label = new Label(); this.Controls.Add(label); this.Controls.Remove(label); // Correct Code Label label = new Label(); this.Controls.Add(label); this.Controls.Remove(label); label.Dispose(); </code></pre> <p><strong>Update</strong>: The idea is to list common pitfalls which are not too obvious (such as the above). Usually the notion is that memory leaks are not a big problem because of the garbage collector. Not like it used to be in C++.</p> <hr> <p>Great discussion guys, but let me clarify... by definition, if there is no reference left to an object in .NET, it will be Garbage Collected at some time. So that is not a way to induce memory leaks.</p> <p>In the managed environment, I would consider it a memory leak if you had an unintended reference to any object that you aren't aware of (hence the two examples in my question).</p> <p><strong>So, what are the various possible ways in which such a memory leak can happen?</strong></p>
<p>There's no way to provide a comprehensive list... this is very much like asking "How can you get wet?"</p> <p>That said, make sure you're calling Dispose() on everything that implements IDisposable, and make sure you implement IDisposable on any types that consume unmanaged resources of any kind.</p> <p>Every now and then, run something like FxCop on your codebase to help you enforce that rule - you'd be surprised how deep some disposable objects get buried within an application framework.</p>
<p>A lot of the things that can cause memory leaks in unmanaged languages can still cause memory leaks in managed languages. For example, <a href="http://blogs.msdn.com/oldnewthing/archive/2006/05/02/588350.aspx" rel="nofollow noreferrer">bad caching policies</a> can result in memory leaks.</p> <p>But as Greg and Danny have said, there is no comprehensive list. Anything that can result in holding memory after its useful lifetime can cause a leak.</p>
4,075
<p>I am making a "fun button", with a dome-shaped top. The vertical sides, top center, and raised lettering seem fine, but the more sloped outer parts of the dome are very thin, with some gaps and the infill pattern is quite visible. It's almost like the slicer isn't recognizing the sloped part as an exterior shell. </p> <p>What is causing this, and how can I fix it?</p> <p><a href="https://i.stack.imgur.com/cU2IR.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cU2IR.jpg" alt="My Fun Button"></a></p> <p>The model was made in Fusion 360, sliced in Repetier with Slic3r, and printed on a Monoprice Maker Select Mini.</p> <p>Edit: More information after checking values used and taking more photos.</p> <p>This was my second attempt, after increasing the shell count already.</p> <p>On my first print, I clearly had a low value for horizontal shells, top and bottom were both at the default of 3. I upped these both to 8. (Layer height is 0.13125.) The bottom of the button is now good. The "good" center area extends a little further out, so I think it's probably thicker up at the top of the dome. But the sloped sides are pretty much the same - this is why I'm thinking it's not being considered as a "horizontal shell".</p> <p>Comparison:</p> <p><a href="https://i.stack.imgur.com/6C7aX.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6C7aX.jpg" alt="bottom of buttons"></a></p> <p><a href="https://i.stack.imgur.com/SgwOd.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SgwOd.jpg" alt="top of buttons"></a></p> <p>There are some design iterations, but the top surface is the same shape.</p> <p><strong>Update:</strong></p> <p>I did a print using Cura, with 0.8 mm shells, and it looks great!</p> <p><a href="https://i.stack.imgur.com/D4iC5.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/D4iC5.jpg" alt="Printed with Cura"></a></p> <p>I cut the two bad prints with a hacksaw to see a cross-section. The bottom is clearly thicker. The top on the outer infill void is pretty much the same. The top on the other void is thicker most of the way across, but suddenly changes to thin.</p> <p><a href="https://i.stack.imgur.com/A27aV.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/A27aV.jpg" alt="Cross section"></a></p>
<p>Slice with more solid top layers. I always use five with low-density infill.</p>
<p>You can either increase the shells, or you can increase the infill density. In addition different fill patterns will help. I would do 4 minimum for such a print.</p>
497
<p>I have a ASP.NET application that we've written our own logging module for.</p> <p>My question is, where is the standard place to write a log file to? I.e. the website will be running as the anonymous user identity (e.g. IUSR on IIS7) and I need a place where I know it'll have permission to write to.</p> <p>Cheers,</p>
<p>App_Data folder on the root of the project. It isn't served to web requests; so other people can't snoop for it.</p>
<p>I'm not in a position to modify the permissions on folders (especially outside of the virtual directory home folder), and don't already have an App_Data folder, so am a bit hesitant to go with that. </p> <p>So for the moment I'm going with the CommonApplicationData Folder. </p> <ul> <li>On Vista/Server 2008 this is C:\ProgramData\</li> <li>On XP/Server 2003 this is C:\Documents and Settings\All Users\Application Data\</li> </ul>
2,825
<p>I have tried to print <a href="https://www.thingiverse.com/thing:2014307" rel="nofollow noreferrer">Baby Groot</a> , but every time I print the head, there are always layer shifts like the photos below. I have printed three heads and the layer shifts happened all in the same place.</p> <p><a href="https://i.stack.imgur.com/6WAAn.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6WAAn.jpg" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/denTU.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/denTU.jpg" alt="enter image description here" /></a></p> <p>I tried to print something else that is the (more or less) same height and the layer shifting also happened.</p> <p><a href="https://i.stack.imgur.com/W3E96.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/W3E96.jpg" alt="enter image description here" /></a></p> <p>I was thinking maybe because z-rod bent. But apparently the layer shift happened in different height.</p> <p><a href="https://i.stack.imgur.com/yBkjJ.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yBkjJ.jpg" alt="enter image description here" /></a></p> <p>What is my problem and how to solve this ? I am using Ender 3 with BLTouch.</p>
<p>Layer shifting has two basic causes: the partially printed part moves or flexes, or the bed or Y carriage (almost always -- they seem rather uncommon on the X axis) skips one or more steps in one direction or the other.</p> <p>Permanent layer shifts -- that is, where the entire print above the shift is and remains shifted -- are more likely to be the latter; temporary shifts (where the shift creates a bulge or groove, and then layers above that section are back in line with those below) are more likely due to part movement.</p> <p>In your case, you appear to have temporary shifts. Those on the Groot head seem (in the photos) to line up with heights at which some of the peaks on the head end; they might be a result of changes in the nozzle interaction with a print that's becoming tall enough to flex as the path changes due to those sections finishing. The ones on the pink block look more like temporary overextrusion, but since we can't see the opposite side of whatever that is, I can't say for certain that they aren't the same thing.</p> <p>One thing you might try is reslicing both of those objects with Z-hop enabled. That will reduce nozzle dragging over earlier parts of the current layer, which can flex the part (or temporarily block the nozzle, causing pressure buildup that will lead to momentary overextrusion).</p> <p>To save time, you might look for whether you have any objects that exhibit this without as many hours of printing time (and tens of grams of filament) already spent -- perhaps you can sink Groot into the virtual bed in your slicer, so as to print him only from the eyes up (or even higher) -- though that might reduce flex enough that finishing the peaks on his head won't result in a significant change.</p>
<p>Zeiss Ikon's answer is good - but just in case that doesn't solve it, have you printed larger / longer prints before? There's a well known problem with the Ender 3's 4.2.2 motherboard that causes layer shifts as it overheats on longer prints. You can try elevating the printer and putting a fan underneath to see if that changes anything. (I had that problem and it drove me nuts until I got a 4.2.7 motherboard)</p> <ul> <li><a href="https://www.reddit.com/r/ender3v2/comments/lmf1v2/an_faq_on_layer_shifts_and_mainboards/" rel="nofollow noreferrer">https://www.reddit.com/r/ender3v2/comments/lmf1v2/an_faq_on_layer_shifts_and_mainboards/</a></li> <li><a href="https://www.reddit.com/r/ender3v2/comments/kn8u72/layer_shift_investigation_data_and_video/" rel="nofollow noreferrer">https://www.reddit.com/r/ender3v2/comments/kn8u72/layer_shift_investigation_data_and_video/</a></li> <li><a href="https://www.reddit.com/r/ender3v2/comments/kxeikz/as_promised_thermal_camera_captures_of_a_layer/" rel="nofollow noreferrer">https://www.reddit.com/r/ender3v2/comments/kxeikz/as_promised_thermal_camera_captures_of_a_layer/</a></li> </ul> <p>However, I do see some other layer issues on the head further down the print. I would probably loosen and readjust all the gantries again, check all the belt tensions, do another bed level (you changed out the stock springs with the yellow ones right?). After hours of use, not uncommon for there to be a hiccup, maybe a piece of plastic / dust stuck in a track.</p> <p>If you've double checked and adjusted all the gantry's and none are loose or too tight, look at your table the printer sits on. If possible, put the printer on something really heavy (slab of concrete, thick wood) with a little padding underneath that heavy surface. Put a half glass of water on the top most surface (not on the printer) to see if the table is vibrating while printing (water should be still the entire time). It could be the table is moving a little as the printer is printing - with fractions of mm's it doesn't take too much.</p>
1,987
<p>In the web-application I'm developing I currently use a naive solution when connecting to the database:</p> <pre><code>Connection c = DriverManager.getConnection("url", "username", "password"); </code></pre> <p>This is pretty unsafe. If an attacker gains access to the sourcecode he also gains access to the database itself. How can my web-application connect to the database without storing the database-password in plaintext in the sourcecode?</p>
<p>You can store the connection string in Web.config or App.config file and encrypt the section that holds it. Here's a very good article I used in a previous project to encrypt the connection string:</p> <p><a href="http://www.ondotnet.com/pub/a/dotnet/2005/02/15/encryptingconnstring.html" rel="noreferrer">http://www.ondotnet.com/pub/a/dotnet/2005/02/15/encryptingconnstring.html</a></p>
<p>I can recommend these techniques for .NET programmers: </p> <ul> <li>Encrypt password\connection string in config file</li> <li>Setup trusted connection between client and server (i.e. use windows auth, etc)</li> </ul> <p>Here is useful articles from CodeProject: </p> <ul> <li><a href="http://www.codeproject.com/KB/cs/Configuration_File.aspx" rel="nofollow noreferrer">Encrypt and Decrypt of ConnectionString in app.config and/or web.config</a></li> </ul>
6,445
<p>I am writing my first serious wxWidgets program. I'd like to use the wxConfig facility to make the program's user options persistent. However I <em>don't</em> want wxConfigBase to automatically use the Windows registry. Even though I'm initially targeting Windows, I'd prefer to use a configuration (eg .ini) file. Does anyone know a clean and simple way of doing this ? Thanks.</p>
<p>Don't do it!</p> <p>Trying to create identifiers that are not valid in your language is not a good idea. If you really want to set variables like that, use attribute macros:</p> <pre><code>attr_writer :bar attr_reader :baz attr_accessor :foo </code></pre> <p>Okay, now that you have been warned, here's how to do it. Just return another instance of the same class every time you get a regular accessor, and collect the needed information as you go.</p> <pre><code>class SillySetter def initialize path=nil @path = path end def method_missing name,value=nil new_path = @path ? "#{@path}.#{name}" : name if name.to_s[-1] == ?= puts "setting #{new_path} #{value}" else return self.class.new(path=new_path) end end end s = SillySetter.new s.foo = 5 # -&gt; setting foo= 5 s.foo.bar.baz = 4 # -&gt; setting foo.bar.baz= 4 </code></pre> <p>I didn't want to encourage ruby sillyness, but I just couldn't help myself!</p>
<p>If there's no hope of changing the canonical names, you could alias the getters and setters manually:</p> <pre><code>def variable_name send 'variable.name' end def variable_name=(value) send 'variable.name=', value end </code></pre>
7,174
<p>I am using Struts + Velocity in a Java application, but after I submit a form, the confirmation page (Velocity template) shows the variable names instead an empty label, like the Age in following example:</p> <blockquote> <p><strong>Name</strong>: Fernando</p> <p><strong>Age</strong>: {person.age}</p> <p><strong>Sex</strong>: Male</p> </blockquote> <p>I would like to know how to hide it!</p>
<p>You can mark variables as "<a href="https://velocity.apache.org/engine/1.5/user-guide.html#quietreferencenotation" rel="noreferrer">silent</a>" like this:</p> <pre><code>$!variable </code></pre> <p>If $variable is null, nothing will be rendered. If it is not null, its value will render as it normally would.</p>
<p>You will also need to be sure and use the proper syntax. Your example is missing the dollar before the variable. It should be $!{person.age}, not just {person.age}.</p>
4,367
<p>I have a function that gives me the following warning:</p> <blockquote> <p>[DCC Warning] filename.pas(6939): W1035 Return value of function 'function' might be undefined</p> </blockquote> <p>The function, however, is clean, small, and does have a known, expected, return value. The first statement in the function is:</p> <pre><code>Result := ''; </code></pre> <p>and there is no local variable or parameter called <code>Result</code> either.</p> <p>Is there any kind of pragma-like directive I can surround this method with to remove this warning? This is Delphi 2007.</p> <p>Unfortunately, the help system on this Delphi installation is not working, therefore i can't pop up the help for that warning right now.</p> <p>Anyone know off the top of their head what i can do?</p>
<p>Are you sure you have done everything to solve the warning? Maybe you could post the code for us to look at?</p> <p>You can turn off the warning locally this way:</p> <pre><code>{$WARN NO_RETVAL OFF} function func(...): string; begin ... end; {$WARN NO_RETVAL ON} </code></pre>
<p>There seems to be some sort of bug in Delphi. Read this post, the last comment links to other bug-reports that may be the one that you have got:</p> <p><a href="http://qc.codegear.com/wc/qcmain.aspx?d=8144" rel="nofollow noreferrer">http://qc.codegear.com/wc/qcmain.aspx?d=8144</a></p>
8,664
<p>Are there any handy general items you put in your .procmailrc file?</p>
<p>Many mailers prefix a mail's subject with "Re: " when replying, if that prefix isn't already there. German Outlook instead prefixes with "AW: " (for "AntWort") if that prefix isn't already there. Unfortunately, these two behaviours clash, resulting in mail subjects like "Re: AW: Re: AW: Re: AW: Re: AW: Lunch". So I now have:</p> <pre><code>:0f * ^Subject: (Antwort|AW): |sed -r -e '1,/^$/s/^(Subject: )(((Antwort: )|(Re: )|(AW: ))+)(.*)/\1Re: \7\nX-Orig-Subject: \2\7/' </code></pre> <p>Which curtails these (and an "Antwort: " prefix that I've evidently also been bothered by at some point) down to a single "Re: ".</p>
<p>To stop weird russian and chinese spams, I use this procmail configuration. </p> <pre><code>UNREADABLE='[^?"]*big5|iso-2022-jp|ISO-2022-KR|euc-kr|gb2312|ks_c_5601-1987' :0: * ^Content-Type:.*multipart * B ?? $ ^Content-Type:.*^?.*charset="?($UNREADABLE) spam-unreadable </code></pre>
2,993
<p>I am new to 3D printing and just purchased an Ender 3 V2 about two weeks ago. Since I've got it, I've been having trouble leveling the bed. I've tried watching videos, but they don't say how much friction on the paper is good or bad. I have even tried foil, playing cards, and a business card but still can't tell if it's good enough or not. Then when I would try printing calibration squares and adjust as it prints, but when it prints all looks good when printing the outside ring, but when it gets to the square parts there are bumps on the print from the nozzle being too close. Also when I seem to have corner perfect, when it gets to the center it's too close to the nozzle and doesn't even print. I'm using the stock glass bed so I'm not sure if that could be the issue. This is getting frustrating as I really want to start printing. And I want to save money for other parts and try avoiding purchasing a BL Touch if I don't need to. Am I doing something wrong? How can I get this resolved?</p> <p>Forgot to mention, I upgraded the springs to these yellow ones on Amazon.</p>
<p>Step 1: stop using paper and get some feeler gauges. The gauge should be able to just barely pass under the HEATED nozzle.</p> <p>Step 2: What are you using for bed adhesion? I use Elmer's white glue. After you think you've trammed (aka levelled) the bed, apply a generous layer of the glue in a coat on the bed. Let it dry.</p> <p>Step 3: Verify bed level with a large square print that will cause the head to move to the outermost parts of the bed. Stop the print after a few outlines. Try to remove the print. If some areas are easier to remove than others, apply another coat of Elmer's glue to those areas.</p> <p>Note: Do not hold down all four (4) corners of the glass bed. The aluminium plate is not going to be flatter than the glass. Only attach the glass to the bed on one side of the bed. I use the side that is furthest from the nozzle.</p>
<p>Don't worry too much about it. If you print with a first layer height of 0.3mm, bed levelling only needs to be approximate. If that doesn't work, and you cannot get good bed adhesion, try printing onto blue painter's tape (ScotchBlue). This makes a very forgiving build surface. You will need to clean it well with isopropyl alcohol (or acetone), since it is coated with a wax-based release agent that may prevent the filament from sticking. Once you have got used to printing, you can then refine your bed-levelling techniques.</p>
1,801
<p>My boss found a bug in a query I created, and I don't understand the reasoning behind the bug, although the query results prove he's correct. Here's the query (simplified version) before the fix:</p> <pre><code>select PTNO,PTNM,CATCD from PARTS left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD); </code></pre> <p>and here it is after the fix:</p> <pre><code>select PTNO,PTNM,PARTS.CATCD from PARTS left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD); </code></pre> <p>The bug was, that null values were being shown for column CATCD, i.e. the query results included results from table CATEGORIES instead of PARTS. Here's what I don't understand: if there was ambiguity in the original query, why didn't Oracle throw an error? As far as I understood, in the case of left joins, the "main" table in the query (PARTS) has precedence in ambiguity. Am I wrong, or just not thinking about this problem correctly?</p> <p>Update:</p> <p>Here's a revised example, where the ambiguity error is not thrown:</p> <pre><code>CREATE TABLE PARTS (PTNO NUMBER, CATCD NUMBER, SECCD NUMBER); CREATE TABLE CATEGORIES(CATCD NUMBER); CREATE TABLE SECTIONS(SECCD NUMBER, CATCD NUMBER); select PTNO,CATCD from PARTS left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD) left join SECTIONS on (SECTIONS.SECCD=PARTS.SECCD) ; </code></pre> <p>Anybody have a clue?</p>
<blockquote> <p>Here's the query (simplified version) </p> </blockquote> <p>I think by simplifying the query you removed the real cause of the bug :-)</p> <p>What oracle version are you using? Oracle 10g ( 10.2.0.1.0 ) gives: </p> <pre><code>create table parts (ptno number , ptnm number , catcd number); create table CATEGORIES (catcd number); select PTNO,PTNM,CATCD from PARTS left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD); </code></pre> <p>I get ORA-00918: column ambiguously defined</p>
<p>It is generally advised to be specific and fully qualify all column names anyway, as it saves the optimizer a little work. Certainly in SQL Server.</p> <p>From what I can gleen from the <a href="http://www.oracle.com/technology/index.html" rel="nofollow noreferrer">Oracle docs</a>, it seems it will only throw if you select the column name twice in the select list, or once in the select list and then again elsewhere like an order by clause.</p> <p>Perhaps you have uncovered an 'undocumented feature' :)</p>
8,328
<p>I'll have an ASP.net page that creates some Excel Sheets and sends them to the user. The problem is, sometimes I get Http timeouts, presumably because the Request runs longer than executionTimeout (110 seconds per default).</p> <p>I just wonder what my options are to prevent this, without wanting to generally increase the executionTimeout in <code>web.config</code>?</p> <p>In PHP, <a href="http://fr.php.net/manual/en/function.set-time-limit.php" rel="nofollow noreferrer"><code>set_time_limit</code></a> exists which can be used in a function to extend its life, but I did not see anything like that in C#/ASP.net?</p> <p>How do you handle long-running functions in ASP.net?</p>
<p>If you want to increase the execution timeout for this one request you can set</p> <pre><code>HttpContext.Current.Server.ScriptTimeout</code></pre> <p>But you still may have the problem of the client timing out which you can't reliably solve directly from the server. To get around that you could implement a "processing" page (like Rob suggests) that posts back until the response is ready. Or you might want to look into AJAX to do something similar.</p>
<p>I've not really had to face this issue too much yet myself, so please keep that in mind.</p> <p>Is there not anyway you can run the process async and specify a callback method to occur once complete, and then keep the page in a "we are processing your request.." loop cycle. You could then open this up to add some nice UI enhancements as well.</p> <p>Just kinda thinking out loud. That would probably be the sort of thing I would like to do :)</p>
4,940
<p>After some months of good quality prints, since yesterday my heatbed does not heat anymore.</p> <p>I've a BQ Prusa i3 Hephestos with <a href="https://www.reprap.org/wiki/File:RRD-Mk2b-dual-power_blk.jpg" rel="nofollow noreferrer">this</a> heatbed, controlled by <a href="https://images-na.ssl-images-amazon.com/images/I/71M29xMMLZL._AC_SY355_.jpg" rel="nofollow noreferrer">this</a> mechanical relay and powered by <a href="https://www.amazon.it/Lixada-Trasformatore-Tensione-Interruttore-Alimentazione/dp/B00ECW6K74" rel="nofollow noreferrer">this</a> power source. I know that a mechanical relay is not the best choice for a 3D printer, but I only had one of those when I've built the bed and setting <em>bang bang control</em> for the plate gave me some satisfactory prints.</p> <p>Since if I connect directly the heatbed to the power source, the latter stops working (I think because of its shortage protection), I'm almost sure that in some way I've managed to fry my heatbed. Before buying a new one, though, I'd like to understand how I've broken the current heatbed without doing anything but printing, to avoid similar situations in the future.</p> <p>I'm afraid I've forgotten some component whose functionality is to protect the heatbed (maybe a diode or something similar, I'm sorry but I have never studied electronics).</p> <p>I've attached a very simple wiring diagram showing the current configuration.</p> <p><a href="https://i.stack.imgur.com/8bHA7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/8bHA7.png" alt="Wiring diagram" /></a></p>
<p>I see four points of error:</p> <ul> <li>The heatbed could be faulty.</li> <li>The lines could be faulty.</li> <li>The trigger signal could be faulty.</li> <li>The power supply could be faulty.</li> </ul> <p>So, how to check what it might be? We need to measure, but we need to measure in a setup of 12/24 V circuits while they are live. While not necessarily considered &quot;dangerous&quot;, take extra precautions! Remove the parts you will need to access from the machine, ground the power supply, and use your utmost care! Make sure the heatbed is not connected to the Power supply, so we can measure it in the safest way.</p> <h1>Ruling out the Heatbed</h1> <p>The first step can be done without power: the resistance of the heatbed should be non-0, non-open line. It's best to measure directly at the input pins to the bed. If it shows close to 0 (some milli-Ohms), open line (OL), or no continuity (NC), it has a short or is burned out and needs to be replaced.</p> <h1>Ruling out the Power Supply</h1> <p>Once we have reached a safe setup, take a voltmeter and measure the voltage (potential difference) on the pins you reserve for the heatbed. If it is 12 V with some tolerance, it's good, otherwise you might need to get a new power supply or have a professional fix yours.</p> <h1>Ruling out the trigger signal</h1> <p>Next, move your measuring to the output of the board. Now order your board to heat up the bed. Make no illusions, we <strong>will</strong> trigger TRP, as the bed is disconnected. This will need us to reset the board between tests. You should see a 5 V trigger signal. If not, your board or firmware might be faulty and require different investigations.</p> <h1>Ruing out the lines and switch</h1> <p>Next step is to swap to Resistance mode on the multimeter and measure the resistance of the switch, best with the whole power line. Under &quot;heating&quot;, the setup should show a close to 0 Ohm resistance, if not it should show an infinite or open line.</p> <h1>What now?!</h1> <p>If it is neither of the 4, reassemble on the test stand, reconnect the bed to the power supply and investigate all connections between the elements we just checked. Now order a heating procedure - as all components should be ok, it has to be one of the interfaces between the parts.</p>
<p>Assuming you are using the correct voltage hot bed, what you have set up should be just fine.</p> <p>On the other hand, if it’s a 12 volt bed with a 24 volt power supply, you could have easily burned it out.</p> <p>If the voltages were matched properly, you may have just gotten unlucky.</p>
1,758
<p>I'm designing a database table and asking myself this question: <em>How long should the firstname field be?</em></p> <p>Does anyone have a list of reasonable lengths for the most common fields, such as first name, last name, and email address?</p>
<p>I just queried my database with millions of customers in the USA.</p> <ul> <li><p>The maximum <strong>first name</strong> length was 46. I go with 50. (Of course, only 500 of those were over 25, and they were all cases where data imports resulted in extra junk winding up in that field.)</p></li> <li><p><strong>Last name</strong> was similar to first name.</p></li> <li><p><strong>Email addresses</strong> maxed out at 62 characters. Most of the longer ones were actually lists of email addresses separated by semicolons.</p></li> <li><p><strong>Street address</strong> maxes out at 95 characters. The long ones were all valid.</p></li> <li><p>Max <strong>city</strong> length was 35.</p></li> </ul> <p>This should be a decent statistical spread for people in the US. If you have localization to consider, the numbers could vary significantly.</p>
<p>it is varchar right? So it then doesn't matter if you use 50 or 25, better be safe and use 50, that said I believe the longest I have seen is about 19 or so. Last names are longer</p>
4,133
<p>Those of you who have used <a href="http://research.microsoft.com/Pex/" rel="noreferrer">Pex</a>, what do you think its advantages and disadvantages are of Pex as a tool?</p> <p>Also, what do you think are the advantages and disadvantages of "Automated Exploratory Testing" in general, <strong>as a supplement to</strong> TDD/Unit Testing?</p>
<p>I think Pex as an exploratory testing tool is really intriguing. In that regard, I see it as something I'd want to hand off to QA to use.</p> <p>As a TDD tool, it needs some work, as TDD is a design activity. However, I do like the direction that Peli is heading. There's something to be said for automated assisted design. For example, just because TDD is a design tool, there's no reason I can't have an automated tool point out potential edge cases while I'm designing, right? Build quality in from the start.</p> <p>Check out this post in which Peli uses Pex in a TDD style workflow. <a href="http://blog.dotnetwiki.org/TDDingABinaryHeapWithPexPart1.aspx" rel="nofollow noreferrer">http://blog.dotnetwiki.org/TDDingABinaryHeapWithPexPart1.aspx</a></p>
<p>Test-first development makes you structure your code for testability. In this respect, Pex finds clever and awkward paths thru your code, helping out beyond simple coverage metrics.</p> <p>Major forte of Pex with Moles is enabling of tracking side effects when doing Brownfield development: run Pex once and save outputs, then apply code changes, and run Pex again to see what got broken.</p>
8,397
<p>I am using <a href="http://www.simpletest.org/" rel="nofollow noreferrer">Simpletest</a> as my unit test framework for the PHP site I am currently working on. I like the fact that it is shipped with a simple HTML reporter, but I would like a bit more advanced reporter.</p> <p>I have read the reporter API documentation, but it would be nice to be able to use an existing reporter, instead of having to do it yourself.</p> <p>Are there any good extended HTML reporters or GUI's out there for Simpletest?</p> <p>Tips on GUI's for PHPUnit would also be appreciated, but my main focus is Simpletest, for this project. I have tried <a href="http://cool.sourceforge.net/" rel="nofollow noreferrer">Cool PHPUnit Test Runner</a>, but was not convinced.</p>
<p>If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation:</p> <pre><code>python script_a.py | python script_b.py </code></pre> <p>This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on <a href="http://en.wikipedia.org/wiki/Standard_streams" rel="nofollow noreferrer">standard streams</a> on Wikipedia.</p> <p>If you're talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication):</p> <pre><code>import subprocess # Of course you can open things other than python here :) process = subprocess.Popen(["python", "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) x = process.stderr.readline() y = process.stdout.readline() process.wait() </code></pre> <p>See the Python <a href="http://docs.python.org/lib/module-subprocess.html" rel="nofollow noreferrer">subprocess</a> module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard <a href="http://docs.python.org/lib/bltin-file-objects.html" rel="nofollow noreferrer">file objects</a>.</p> <p>For use with pipes, reading from standard input as <a href="https://stackoverflow.com/questions/24931/how-to-capture-python-interpreters-andor-cmdexes-output-from-a-python-script#24939">lassevk</a> suggested you'd do something like this:</p> <pre><code>import sys x = sys.stderr.readline() y = sys.stdin.readline() </code></pre> <p>sys.stdin and sys.stdout are standard file objects as noted above, defined in the <a href="http://docs.python.org/lib/module-sys.html" rel="nofollow noreferrer">sys</a> module. You might also want to take a look at the <a href="http://docs.python.org/lib/module-pipes.html" rel="nofollow noreferrer">pipes</a> module.</p> <p>Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into <a href="http://docs.python.org/lib/poll-objects.html" rel="nofollow noreferrer">polling</a> which unfortunately does not work in windows, but I'm sure there's some alternative out there.</p>
<p>In which context are you asking?</p> <p>Are you trying to capture the output from a program you start on the command line?</p> <p>if so, then this is how to execute it:</p> <pre><code>somescript.py | your-capture-program-here </code></pre> <p>and to read the output, just read from standard input.</p> <p>If, on the other hand, you're executing that script or cmd.exe or similar from within your program, and want to wait until the script/program has finished, and capture all its output, then you need to look at the library calls you use to start that external program, most likely there is a way to ask it to give you some way to read the output and wait for completion.</p>
4,458
<p>Can we have the database and transaction logs on the same drive? What will be its consequences if it is not recommended?</p>
<p>The only downside is that it causes more thrashing on the disk, so worse performance.</p> <p>A single write will require 2 seeks (between: write transaction log, write data, commit log). Having the transaction log on a separate disk means as few as zero seeks, because the drive heads can remain on the transaction log and the data.</p>
<p>In some scenarios you don't need transaction log at all. In that case you can switch database to <a href="http://msdn.microsoft.com/en-us/library/aa173563(SQL.80).aspx" rel="nofollow noreferrer">Simple Recovery Mode</a> and you gain performance and simpler administration benefits.</p>
6,486
<p>I'm having a lot of issues leveling my printer and one failed print came out like this. Is there something wrong with the surface that I need a new bed? This happens to me quite often and I literally can't get it off.</p> <p><a href="https://i.stack.imgur.com/vOVeZ.jpg" rel="nofollow noreferrer" title="Magnetic bed with filament still stuck to bed"><img src="https://i.stack.imgur.com/vOVeZ.jpg" alt="Magnetic bed with filament still stuck to bed" title="Magnetic bed with filament still stuck to bed" /></a></p>
<p>Presuming that you're talking about an 8 hour period, your printer should be designed to run for 8 hours continuous anyway, so nothing will happen regarding the bed or screen that wouldn't happen with a normal print.</p> <p>If the first few layers stick to the bed, it's likely that you're print will at least be partially completed. So even over night it won't be a full 8 hours of printing while failed. Maybe half that period.</p> <p>If the problem is bed adhesion, or anything that doesn't effect the filament being supplied to the nozzle, then your only problem will be wasted filament and disposing of the spaghetti. No harm will come to your printer.</p> <p>If the problem is a break in the filament or filament runout, or a blocked nozzle then you could have damage to the head of the nozzle from printing dry. If you're printing with PLA this isn't really something that you need to worry about too much as you can run a printer dry for several hours without any problems.</p> <p>If you're printing with ABS or something that needs a hotter head then you could cause damage to it if it's allowed to run dry for an entire night. But again this isn't really something that you need to worry about unless it's running dry for 4 or 6 hours.</p> <p>Simply checking in on it once in the night should be enough to prevent any problems.</p>
<p>There are software solutions like &quot;Spaghetti Detective&quot; (recently renamed to &quot;Obico&quot;) which can watch your print via a camera, and potentially stop the job if it looks bad.</p> <p>Most of the time my print failures come early, in the form of poor bed adhesion - watch the job start for a while before leaving it.</p> <p>I can also remote-check my cameras and stop the job if required, but that requires me to look.</p> <p>The second most common failure is lifting from the base at any time in the print, so you have to keep an eye on it.</p> <p>Filament feed issues are probably third on the common list of causes for problems, including running out.</p> <p>I also have occasional issues where my Pi running Octoprint just looses connection to the printer, and it freezes in place with the bed/nozzle heaters on. This is just a waste of power, so a future plan is to wire the printer through a relay allowing me to power it on/off from octoprint's web page.</p> <p>My longest print was ~30 hours - you have to learn to not touch it unless there's a good reason.</p> <p>Finally, try and maintain the environmental conditions to be fairly constant. I have an enclosure even when printing plain PLA, becuase my printer's location is in a garage, and opening the main door allows the air temp to drop quickly. This would upset a running print until I surrounded it.</p> <p>You can also make sure there's a smoke or heat detector in the room where the printer is, for added peace of mind.</p>
2,157
<p>I'd like to set up a cheap Linux box as a web server to host a variety of web technologies (PHP &amp; Java EE come to mind, but I'd like to experiment with Ruby or Python in the future as well). </p> <p>I'm fairly versed in setting up Tomcat to run on Linux for serving up Java EE applications, but I'd like to be able to open this server up, even just so I can create some tools I can use while I am working in the office. All the experience I've had with configuring Java EE sites has all been for intranet applications where we were told not to focus on securing the pages for external users. </p> <p>What is your advice on setting up a personal Linux web server in a secure enough way to open it up for external traffic?</p>
<p>This article has some of the best ways to lock things down:</p> <p><a href="http://www.petefreitag.com/item/505.cfm" rel="noreferrer">http://www.petefreitag.com/item/505.cfm</a></p> <p>Some highlights:</p> <ul> <li>Make sure no one can browse the directories</li> <li>Make sure only root has write privileges to everything, and only root has read privileges to certain config files</li> <li>Run mod_security</li> </ul> <p>The article also takes some pointers from this book:</p> <p><a href="http://spendfish.com/product/0596007248" rel="noreferrer">Apache Securiy</a> (O'Reilly Press)</p> <p>As far as distros, I've run Debain and Ubuntu, but it just depends on how much you want to do. I ran Debian with no X and just ssh'd into it whenever i needed anything. That is a simple way to keep overhead down. Or Ubuntu has some nice GUI things that make it easy to control Apache/MySQL/PHP.</p>
<p>There are plenty of ways to do this that will work just fine. I would usually jsut use a .htaccess file. Quick to set up and secure <em>enough</em> . Probably not the best option but it works for me. I wouldn't put my credit card numbers behind it but other than that I dont really care.</p>
2,706
<p>In cura one of the options under "build plate adhesion" is "skirt", which seems to simply print a loop around, but not touching, my print. How is this supposed to help my prints stick to the bed?</p>
<p>These skirts they don't contribute at all to help your product adhere better to the build plate other than priming your nozzle so that it is ready to lay down filament for your product. </p> <p>A skirt <strong>does</strong> give a good indication of the adhesion prior to printing your product, if the skirt does not adhere, maybe it is a good time to stop the print and re-slice with different options or fix the bed level.</p>
<p>Skirts prime the nozzle- getting the filament to first adhere to the build platform is necessary for the entire print. Once the filament starts to stick it usually will continue to. </p> <p>Skirts can also help block any air drafts that might blow the filament away from adhering in the 1st layer of the print</p>
918
<p>Is there a redistributable .Net 3.5 installation package that is a silent installer? </p> <p>Or alternatively, is there a switch that can be passed to the main redistributable .Net 3.5 installer to make it silent?</p>
<p>dotnetfx35setup.exe /q /norestart</p> <p>see the .net deployment guide at:</p> <p><a href="http://msdn.microsoft.com/en-us/library/cc160716.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/cc160716.aspx</a></p>
<p>For Windows 10 you need to do following</p> <pre><code>DISM /Online /Enable-Feature /FeatureName:NetFx3 /All /LimitAccess /Source:"Path\To\microsoft-windows-netfx3-ondemand-package" </code></pre> <p>You can find thoose packages under sources\sxs of a Windows DVD</p>
7,082
<p>C++ 0x has template aliases (sometimes referred to as template typedefs). See <a href="http://en.wikipedia.org/wiki/C%2B%2B0x#Alias_templates" rel="noreferrer">here</a>. Current spec of C++ does not. </p> <p>What do you like to use as work around ? Container objects or Macros ? Do you feel its worth it ?</p>
<blockquote> <p>What do you like to use as work around ? Container objects or Macros ? Do you feel its worth it ?</p> </blockquote> <p>The canonical way is to use a metafunction like thus:</p> <pre><code>template &lt;typename T&gt; struct my_string_map { typedef std::map&lt;std::string, T&gt; type; }; // Invoke: my_string_map&lt;int&gt;::type my_str_int_map; </code></pre> <p>This is also used in the STL (<code>allocator::rebind&lt;U&gt;</code>) and in many libraries including Boost. We use it extensively in a <a href="http://www.seqan.de/dddoc/html/index.html" rel="noreferrer">bioinformatical library</a>.</p> <p>It's bloated, but it's the best alternative 99% of the time. Using macros here is not worth the many downsides.</p> <p>(EDIT: I've amended the code to reflect Boost/STL conventions as pointed out by Daniel in his comment.)</p>
<p>Sometimes you can just explicitly write out the untemplated typedefs for all the necessary types. If the base class is templated on multiple template args with only one type desired to be typedefed you can inherit a specialized class with typedef effectively included in the inherited class name. This approach is less abstruse than the metafunction approach.</p>
4,576
<p>In the past I've never been a fan of using triggers on database tables. To me they always represented some "magic" that was going to happen on the database side, far far away from the control of my application code. I also wanted to limit the amount of work the DB had to do, as it's generally a shared resource and I always assumed triggers could get to be expensive in high load scenarios.</p> <p>That said, I have found a couple of instances where triggers have made sense to use (at least in my opinion they made sense). Recently though, I found myself in a situation where I sometimes might need to "bypass" the trigger. I felt really guilty about having to look for ways to do this, and I still think that a better database design would alleviate the need for this bypassing. Unfortunately this DB is used by mulitple applications, some of which are maintained by a very uncooperative development team who would scream about schema changes, so I was stuck.</p> <p>What's the general consesus out there about triggers? Love em? Hate em? Think they serve a purpose in some scenarios? Do think that having a need to bypass a trigger means that you're "doing it wrong"?</p>
<p>Triggers are generally used incorrectly, introduce bugs and therefore should be avoided. Never design a trigger to do integrity constraint checking that crosses rows in a table (e.g "the average salary by dept cannot exceed X).</p> <p><a href="http://asktom.oracle.com" rel="noreferrer">Tom Kyte</a>, VP of Oracle has indicated that he would prefer to <a href="http://tkyte.blogspot.com/2006/09/classic-example-of-why-i-despise.html" rel="noreferrer">remove triggers as a feature of the Oracle</a> database because of their frequent role in bugs. He knows it is just a dream, and triggers are here to stay, but if he could he would remove triggers from Oracle, he would (along with the WHEN OTHERS clause and autonomous transactions).</p> <blockquote> <p>Can triggers be used correctly? Absolutely.</p> <p>The problem is - they are not used correctly in so many cases that I'd be willing to give up any perceived benefit just to get rid of the abuses (and bugs) caused by them. - Tom Kyte</p> </blockquote>
<p>I'm not a fan, personally. I'll use them, but only when I uncover a bottleneck in the code that can be cleared by moving actions into a trigger. Generally, I prefer simplicity and one way to keep things simple is to keep logic in one place - the application. I've also worked on jobs where access is very compartmentalized. In those environments, the more code I pack into triggers the more people I have to engage for even the simplest fixes.</p>
3,490
<p>The company I work for is starting to have issues with their current branching model and I was wondering what different kinds of branching strategies the community has been exposed to?</p> <p>Are there any good ones for different situations? What does your company use? What are the advantages and disadvantages of them??</p>
<p>Here is the method I've used in the past with good success:</p> <p>/trunk - bleeding edge. Next major release of the code. May or may not work at any given time.</p> <p>/branches/1.0, 1.1, etc. Stable maintenance branches of the code. Used to fix bugs, stabilize new releases. If a maintenance branch, it should compile (if applicable) and be ready for QA/shipping at any given time. If a stabilization branch, it should compile and be feature complete. No new features should be added, no refactoring, and no code cleanups. You can add a pre- prefix to indicate stabilization branches vs maintenance branches.</p> <p>/branches/cool_feature. Used for highly experimental or destructive work that may or may not make it into trunk (or a maintenance branch). No guarantees about code compiling, working, or otherwise behaving sanely. Should last the minimum time as possible before merging into the mainline branch.</p> <p>/tags/1.0.1, 1.0.2, 1.1.3a, etc. Used for tagging a packaged &amp; shipped release. Never EVER changes. Make as many tags as you want, but they're immutable.</p>
<p>For Subversion, I agree with Ryan Duffield's comment. The chapter he refers to provides a good analyses on which system to use.</p> <p>The reason I asked is that Perforce provides a completely different way to create branches from SVN or CVS. Plus, there are all the DVCSs that give it's own philosophy on branching. Your branching strategy would be dictated by which tool(s) you're using.</p> <p>FYI, <a href="http://www.orcaware.com/svn/wiki/Svnmerge.py" rel="nofollow noreferrer">Svnmerge.py</a> is a tool to assist with merging branches in SVN. It works very well as long as you use it frequently ( every 10-30 ) commits, otherwise the tool can get confused.</p>
5,537
<p>I would like to be able to use the <kbd>Tab</kbd> key within a text box to tab over four spaces. The way it is now, the Tab key jumps my cursor to the next input.</p> <p>Is there some JavaScript that will capture the Tab key in the text box before it bubbles up to the UI?</p> <p>I understand some browsers (i.e. FireFox) may not allow this. How about a custom key-combo like <kbd>Shift</kbd>+<kbd>Tab</kbd>, or <kbd>Ctrl</kbd>+<kbd>Q</kbd>?</p>
<p>Even if you capture the <code>keydown</code>/<code>keyup</code> event, those are the only events that the tab key fires, you still need some way to prevent the default action, moving to the next item in the tab order, from occurring.</p> <p>In Firefox you can call the <code>preventDefault()</code> method on the event object passed to your event handler. In IE, you have to return false from the event handle. The JQuery library provides a <code>preventDefault</code> method on its event object that works in IE and FF.</p> <pre><code>&lt;body&gt; &lt;input type="text" id="myInput"&gt; &lt;script type="text/javascript"&gt; var myInput = document.getElementById("myInput"); if(myInput.addEventListener ) { myInput.addEventListener('keydown',this.keyHandler,false); } else if(myInput.attachEvent ) { myInput.attachEvent('onkeydown',this.keyHandler); /* damn IE hack */ } function keyHandler(e) { var TABKEY = 9; if(e.keyCode == TABKEY) { this.value += " "; if(e.preventDefault) { e.preventDefault(); } return false; } } &lt;/script&gt; &lt;/body&gt; </code></pre>
<p>In Chrome on the Mac, alt-tab inserts a tab character into a <code>&lt;textarea&gt;</code> field.</p> <p>Here’s one: . Wee!</p>
2,550
<p>What would be the easiest way to be able to send and receive raw network packets. Do I have to write my own JNI wrapping of some c API, and in that case what API am I looking for?</p> <p>EDIT: I want to be able to do what wireshark does, i.e. record all incomming packets on an interface, and in addition be able to send back my own created packets. And I want to do it on a mac.</p>
<p>If you start with the idea that you need something <em>like</em> a packet sniffer, you'll want to look at <a href="http://netresearch.ics.uci.edu/kfujii/jpcap/doc/" rel="nofollow noreferrer">http://netresearch.ics.uci.edu/kfujii/jpcap/doc/</a>.</p>
<p><a href="http://www.maxim-ic.com/products/microcontrollers/tini/" rel="nofollow noreferrer">TINI</a> is a java ethernet controller, which may have libraries and classes for directly accessing data from ethernet frames to TCP streams. You may be able to find something in there that implements your needed classes. If not, there should be pointers or user groups that will give you a head start.</p>
6,124
<p>I have Ramps 1.4 and would like to get answer on extrusion in Marlin firmware. I have NEMA 17 stepper motor 1.8 deg, set to 1/16 step. Mk7 direct drive. 38 teeth in extruder drive gear. I bought it from <a href="https://www.robotics.org.za/RDKIT-00?search=extru" rel="nofollow noreferrer">this website</a>.</p> <p>Here are my current settings:</p> <pre><code>#define DEFAULT_AXIS_STEPS_PER_UNIT { 80,80, 4000, 180 } #define DEFAULT_MAX_FEEDRATE { 500, 500, 3, 45 } #define DEFAULT_MAX_ACCELERATION { 9000, 9000, 100, 300 } </code></pre> <p>I am using ABS 1.75 filament and a 0.4 nozzle.</p>
<p>According to the description, the drive gear you have has a <code>10.8mm</code> diameter. This means that (in the ideal case) one full rotation of the drive gear will advance a length of filament equal to its circumference, which is <code>pi x 10.8mm</code> or approximately <code>33.93mm</code>.</p> <p>Your motor rotates <code>1.8</code> degrees per step, so it takes <code>360 / 1.8 = 200 steps</code> for a full rotation. Since you are using 16x microstepping, this is multiplied to <code>200 x 16 = 3200 steps</code>.</p> <p>You thus end up with a steps per mm value of <code>3200 / 33.93 = 94.31 steps/mm</code>.</p> <p>You might need to calibrate this further, for instance by extruding a set length of filament (e.g. 100mm) and measuring how much is actually extruded, and then compensating the steps/mm value to get you closer to the desired 100mm. A simple way to measure this is to put a mark on your filament at 150mm from the extruder, and then (after extruding 100mm) measure how close the mark is to the extruder (which should be 50mm) However, this theoretically computed value should be a good starting point. Note that the speed you do this test at should be close to your normal printing speed, since extruding at a much higher (resp. lower) speed will falsely lead you to believe you are underextruding (resp. overextruding).</p>
<p>Simplest way to calculate your extrusion is:</p> <p>Set your number of perimeters walls 1 top and bottom layer 0 infill 0% and print simple 20x20x20 cube look at the wall thickness with caliper and compare your extrusion width value on your slicer software</p>
656
<p>I'm writing a small web server in Python, using BaseHTTPServer and a custom subclass of BaseHTTPServer.BaseHTTPRequestHandler. Is it possible to make this listen on more than one port?</p> <p>What I'm doing now:</p> <pre><code>class MyRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler): def doGET [...] class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): pass server = ThreadingHTTPServer(('localhost', 80), MyRequestHandler) server.serve_forever() </code></pre>
<p>Sure; just start two different servers on two different ports in two different threads that each use the same handler. Here's a complete, working example that I just wrote and tested. If you run this code then you'll be able to get a Hello World webpage at both <a href="http://localhost:1111/" rel="noreferrer">http://localhost:1111/</a> and <a href="http://localhost:2222/" rel="noreferrer">http://localhost:2222/</a></p> <pre><code>from threading import Thread from SocketServer import ThreadingMixIn from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler class Handler(BaseHTTPRequestHandler): def do_GET(self): self.send_response(200) self.send_header("Content-type", "text/plain") self.end_headers() self.wfile.write("Hello World!") class ThreadingHTTPServer(ThreadingMixIn, HTTPServer): daemon_threads = True def serve_on_port(port): server = ThreadingHTTPServer(("localhost",port), Handler) server.serve_forever() Thread(target=serve_on_port, args=[1111]).start() serve_on_port(2222) </code></pre> <p><em>update:</em></p> <p>This also works with Python 3 but three lines need to be slightly changed:</p> <pre><code>from socketserver import ThreadingMixIn from http.server import HTTPServer, BaseHTTPRequestHandler </code></pre> <p>and</p> <pre><code>self.wfile.write(bytes("Hello World!", "utf-8")) </code></pre>
<p>Not easily. You could have two ThreadingHTTPServer instances, write your own serve_forever() function (don't worry it's not a complicated function).</p> <p>The existing function:</p> <pre><code>def serve_forever(self, poll_interval=0.5): """Handle one request at a time until shutdown. Polls for shutdown every poll_interval seconds. Ignores self.timeout. If you need to do periodic tasks, do them in another thread. """ self.__serving = True self.__is_shut_down.clear() while self.__serving: # XXX: Consider using another file descriptor or # connecting to the socket to wake this up instead of # polling. Polling reduces our responsiveness to a # shutdown request and wastes cpu at all other times. r, w, e = select.select([self], [], [], poll_interval) if r: self._handle_request_noblock() self.__is_shut_down.set() </code></pre> <p>So our replacement would be something like:</p> <pre><code>def serve_forever(server1,server2): while True: r,w,e = select.select([server1,server2],[],[],0) if server1 in r: server1.handle_request() if server2 in r: server2.handle_request() </code></pre>
8,566
<p>Is the real benefit in <code>TDD</code> the actual testing of the application, or the benefits that writing a testable application brings to the table? I ask because I feel too often the conversation revolves so much around testing, and not the total benefits package.</p>
<p>TDD helps you design your software. The tests becomes the design. By writing the test first you think about your code from a consumer perspective, making a more user friendly and more compact software design.</p> <p>Also, by applying TDD you typically end up writing your code in a way where you can supply test mocks and stubs. This leads to less coupled software, making it easier to change and maintain over time.</p> <p>So I guess allot of the talk around TDD is about testing, but by doing that other big benefits follow, such as quality (coverage), flexibility (decoupling), better design (think as the consumer of the API).</p>
<p>Automated testing keeps humans from doing a machine's job.</p> <p>Test-driven development maximizes the amount of automated testing.</p> <p>Beyond a certain point, of course, a human is still required. You reach diminishing returns when you try to apply TDD beyond that point.</p>
7,376
<p>How do you scan a directory for folders and files in C? It needs to be cross-platform.</p>
<p>The following POSIX program will print the names of the files in the current directory:</p> <pre><code>#define _XOPEN_SOURCE 700 #include &lt;stdio.h&gt; #include &lt;sys/types.h&gt; #include &lt;dirent.h&gt; int main (void) { DIR *dp; struct dirent *ep; dp = opendir (&quot;./&quot;); if (dp != NULL) { while ((ep = readdir (dp)) != NULL) puts (ep-&gt;d_name); (void) closedir (dp); return 0; } else { perror (&quot;Couldn't open the directory&quot;); return -1; } } </code></pre> <p>Credit: <a href="http://www.gnu.org/software/libtool/manual/libc/Simple-Directory-Lister.html" rel="nofollow noreferrer">http://www.gnu.org/software/libtool/manual/libc/Simple-Directory-Lister.html</a></p> <p>Tested in Ubuntu 16.04.</p>
<p>You can find the sample code on the <a href="https://en.wikibooks.org/wiki/C_Programming/dirent.h" rel="nofollow noreferrer">wikibooks link</a></p> <pre><code>/************************************************************** * A simpler and shorter implementation of ls(1) * ls(1) is very similar to the DIR command on DOS and Windows. **************************************************************/ #include &lt;stdio.h&gt; #include &lt;dirent.h&gt; int listdir(const char *path) { struct dirent *entry; DIR *dp; dp = opendir(path); if (dp == NULL) { perror("opendir"); return -1; } while((entry = readdir(dp))) puts(entry-&gt;d_name); closedir(dp); return 0; } int main(int argc, char **argv) { int counter = 1; if (argc == 1) listdir("."); while (++counter &lt;= argc) { printf("\nListing %s...\n", argv[counter-1]); listdir(argv[counter-1]); } return 0; } </code></pre>
3,350
<p>I've never been completely happy with the way exception handling works, there's a lot exceptions and try/catch brings to the table (stack unwinding, etc.), but it seems to break a lot of the OO model in the process.</p> <p>Anyway, here's the problem:</p> <p>Let's say you have some class which wraps or includes networked file IO operations (e.g. reading and writing to some file at some particular UNC path somewhere). For various reasons you don't want those IO operations to fail, so if you detect that they fail you retry them and you keep retrying them until they succeed or you reach a timeout. I already have a convenient RetryTimer class which I can instantiate and use to sleep the current thread between retries and determine when the timeout period has elapsed, etc.</p> <p>The problem is that you have a bunch of IO operations in several methods of this class, and you need to wrap each of them in try-catch / retry logic.</p> <p>Here's an example code snippet:</p> <pre><code>RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10)); bool success = false; while (!success) { try { // do some file IO which may succeed or fail success = true; } catch (IOException e) { if (fileIORetryTimer.HasExceededRetryTimeout) { throw e; } fileIORetryTimer.SleepUntilNextRetry(); } } </code></pre> <p>So, how do you avoid duplicating most of this code for every file IO operation throughout the class? My solution was to use anonymous delegate blocks and a single method in the class which executed the delegate block passed to it. This allowed me to do things like this in other methods:</p> <pre><code>this.RetryFileIO( delegate() { // some code block } ); </code></pre> <p>I like this somewhat, but it leaves a lot to be desired. I'd like to hear how other people would solve this sort of problem.</p>
<p>This looks like an excellent opportunity to have a look at Aspect Oriented Programming. Here is a good article on <a href="https://learn.microsoft.com/en-us/archive/blogs/simonince/aspect-oriented-interception" rel="nofollow noreferrer">AOP in .NET</a>. The general idea is that you'd extract the cross-functional concern (i.e. Retry for x hours) into a separate class and then you'd annotate any methods that need to modify their behaviour in that way. Here's how it might look (with a nice extension method on Int32)</p> <pre><code>[RetryFor( 10.Hours() )] public void DeleteArchive() { //.. code to just delete the archive } </code></pre>
<p>Just wondering, what do you feel your method leaves to be desired? You could replace the anonymous delegate with a.. named? delegate, something like</p> <pre><code> public delegate void IoOperation(params string[] parameters); public void FileDeleteOperation(params string[] fileName) { File.Delete(fileName[0]); } public void FileCopyOperation(params string[] fileNames) { File.Copy(fileNames[0], fileNames[1]); } public void RetryFileIO(IoOperation operation, params string[] parameters) { RetryTimer fileIORetryTimer = new RetryTimer(TimeSpan.FromHours(10)); bool success = false; while (!success) { try { operation(parameters); success = true; } catch (IOException e) { if (fileIORetryTimer.HasExceededRetryTimeout) { throw; } fileIORetryTimer.SleepUntilNextRetry(); } } } public void Foo() { this.RetryFileIO(FileDeleteOperation, "L:\file.to.delete" ); this.RetryFileIO(FileCopyOperation, "L:\file.to.copy.source", "L:\file.to.copy.destination" ); } </code></pre>
2,389
<p>When creating a setup/MSI with Visual Studio is it possible to make a setup for a simple application that doesn't require administrator permissions to install? If its not possible under Windows XP is it possible under Vista?</p> <p>For example a simple image manipulation application that allows you to paste photos on top of backgrounds. I believe installing to the Program Files folder requires administrator permissions? Can we install in the \AppData folder instead?</p> <p>The objective is to create an application which will install for users who are not members of the administrators group on the local machine and will not show the UAC prompt on Vista.</p> <p>I believe a limitation this method would be that if it installs under the app data folder for the current user other users couldn't run it.</p> <h3>Update:</h3> <p>Can you package a click once install in a normal setup.exe type installer? You may ask why we want this - the reason is we have an installer that does a prereq check and installs anything required (such as .NET) and we then downloads and executes the MSI. We would like to display a normal installer start screen too even if that's the only thing displayed. We don't mind if the app can only be seen by one user (the user it's installed for).</p>
<p>ClickOnce is a good solution to this problem. If you go to Project Properties > Publish, you can setup settings for this. In particular, "Install Mode and Settings" is good to look at: </p> <ul> <li>The application is available online only -- this is effectively a "run once" application</li> <li>The application is avaiable offline as well (launchable from Start Menu) -- this installs the app on the PC</li> </ul> <p>You don't actually have to use the ClickOnce web deployment stuff. If you do a Build > Publish, and then zip up the contents of the publish\ folder, you can effectively distribute that as an installer. To make it even smoother, create a self-extracting archive from the folder that automatically runs the setup.exe file. </p> <p>Even if you install this way, if you opt to use it, the online update will still work for the application. All you have to do is put the ClickOnce files online, and put the URL in the project's Publish properties page.</p>
<p>Vista is <em>more</em> restrictive about this kind of thing, so if you can't do it for XP you can bet Vista won't let you either.</p> <p>You are right that installing to the program files folder using windows installer requires administrative permissions. In fact, <em>all write access</em> to that folder requires admin permsissions, which is why you should no longer store your data in the same folder as your executable.</p> <p>Fortunately, if you're using .Net you can use ClickOnce deployment instead of an msi, which should allow you to install to a folder in each user's profile without requiring admin permissions.</p>
9,897
<p>Will limiting a query to one result record, improve performance in a large(ish) MySQL table if the table only has one matching result?</p> <p>for example</p> <pre><code> select * from people where name = "Re0sless" limit 1 </code></pre> <p>if there is only one record with that name? and what about if <code>name</code> was the primary key/ set to unique? and is it worth updating the query or will the gain be minimal?</p>
<p>If the column has </p> <p><strong>a unique index: no,</strong> it's no faster</p> <p><strong>a non-unique index: maybe,</strong> because it will prevent sending any additional rows beyond the first matched, if any exist</p> <p><strong>no index: sometimes</strong></p> <ul> <li>if 1 or more rows match the query, <strong>yes</strong>, because the full table scan will be halted after the first row is matched.</li> <li>if no rows match the query, <strong>no</strong>, because it will need to complete a full table scan</li> </ul>
<p>I believe the LIMIT is something done after the data set is found and the result set is being built up so I wouldn't expect it to make any difference at all. Making name the primary key will have a significant positive effect though as it will result in an index being made for the column.</p>
5,472
<p>We all know (or should!) that the repeatability of common spring-arm limit switches is crappy at best. I'm looking to build &amp; install one of the precision height adjusters for the Z-axis limit switch, and noticed a post on some forum suggesting removing the arm and triggering the switch button directly (e.g. with a screw end).</p> <p>Has anyone tried this, and if so has the repeatability of Z-homing improved any?</p> <h2>Edit</h2> <p>Sorry -- this is a stock Prusa i3, which depends on physical contact between the vertically-moving subassembly and a microswitch mounted on the frame.</p>
<p>While I haven't seen this on a Z axis for a printer personally, there is no reason it wouldn't work, and would improve your repeatability in theory. Removing the arm on the switch is taking away the lever. Going back to simple machine mechanics, the lever gives you a larger range of motion in which the button could be triggered, with the tradeoff that you get a larger target to hit. How much of an improvement depends on the exact switch, where the button is compared to the axis of the switch, and how long the switch is. </p> <p>My Shapeoko 3 CNC router has a switch for all three end stops that do not have arms, and my Original Prusa i3 mk2 has switches without lever arms on X and Y axis endstops, so there is is no reason it won't work for your i3 Z axis, you just need to make sure you can accurately hit the small button on the switch.</p>
<p>No. Buy a better switch if it's an issue (see below).</p> <p>You would need to have some very tight tolerances to hit that micro button with whatever your arm is. If you had a machine with good tolerances you would not be considering this modification. That alone is why I would say this is not the greatest idea.</p> <p>Following it might work if your Z is connected to the hot end and smashing into the bed. But I suspect you will still have a myriad of issues, such as the switch getting out of position enough to cause the head to crash into the machine. The real question now is how many rotations of the Z axis could happen if the printer is moving at maximum speed and the button is pressed? That metal arm is your grace period. Now your printer is potentially smashing into the switch.</p> <p>Lastly, just get a switch with a more solid and less springy metal tab.</p> <p>The real question is whether there is actually a variance caused by the metal arm? I would suspect that it hits the switch very precisely, consistently and within an acceptable tolerance. Removing the arm will buy you little. Replacing it with a stiffer-arm switch might serve you better.</p>
422
<p>I have an excel spreadsheet in a format similar to the following...</p> <pre><code>| NAME | CLUB | STATUS | SCORE | | Fred | a | Gent | 145 | | Bert | a | Gent | 150 | | Harry | a | Gent | 195 | | Jim | a | Gent | 150 | | Clare | a | Lady | 99 | | Simon | a | Junior | 130 | | John | b | Junior | 130 | : : | Henry | z | Gent | 200 | </code></pre> <p>I need to convert this table into a list of the "Top Ten" teams. The rules are</p> <ul> <li>Each team score is taken from the sum of four members of that club.</li> <li>These totals should be of the best four scores except... <ul> <li>Each team must consist of at least one Junior or Lady</li> </ul></li> </ul> <p>For example in the table above the team score for club A would be 625 <strong>not</strong> 640 as you would take the scores for Harry(190), Bert(150), Jim(150), and Simon(130). You could not take Fred's(145) score as that would give you only Gents.</p> <p>My question is, can this be done easily as a series of Excel formula, or will I need to resort to using something more procedural?</p> <p>Ideally the solution needs to be automatic in the team selections, I don't want to have to create separate hand crafted formula for each team. I also will not necessarily have a neatly ordered list of each clubs members. Although I could probably generate the list via an extra calculation sheet.</p>
<pre><code>Public Function TopTen(Club As String, Scores As Range) Dim i As Long Dim vaScores As Variant Dim bLady As Boolean Dim lCnt As Long Dim lTotal As Long vaScores = FilterOnClub(Scores.Value, Club) vaScores = SortOnScore(vaScores) For i = LBound(vaScores, 2) To UBound(vaScores, 2) If lCnt = 3 And Not bLady Then If vaScores(3, i) &lt;&gt; "Gent" Then lTotal = lTotal + vaScores(4, i) bLady = True lCnt = lCnt + 1 End If Else lTotal = lTotal + vaScores(4, i) lCnt = lCnt + 1 If vaScores(3, i) &lt;&gt; "Gent" Then bLady = True End If If lCnt = 4 Then Exit For Next i TopTen = lTotal End Function Private Function FilterOnClub(vaScores As Variant, sClub As String) As Variant Dim i As Long, j As Long Dim aTemp() As Variant For i = LBound(vaScores, 1) To UBound(vaScores, 1) If vaScores(i, 2) = sClub Then j = j + 1 ReDim Preserve aTemp(1 To 4, 1 To j) aTemp(1, j) = vaScores(i, 1) aTemp(2, j) = vaScores(i, 2) aTemp(3, j) = vaScores(i, 3) aTemp(4, j) = vaScores(i, 4) End If Next i FilterOnClub = aTemp End Function Private Function SortOnScore(vaScores As Variant) As Variant Dim i As Long, j As Long, k As Long Dim aTemp(1 To 4) As Variant For i = 1 To UBound(vaScores, 2) - 1 For j = i To UBound(vaScores, 2) If vaScores(4, i) &lt; vaScores(4, j) Then For k = 1 To 4 aTemp(k) = vaScores(k, j) vaScores(k, j) = vaScores(k, i) vaScores(k, i) = aTemp(k) Next k End If Next j Next i SortOnScore = vaScores End Function </code></pre> <p>Use as <code>=TopTen(H2,$B$2:$E$30)</code> where <code>H2</code> contains the club letter.</p>
<p>Use a pivot table which will act as a database query on the data you have. Pivot so that the teams go down the columns and team members along with their status type go across the pivot table. I'm not sure for 2003, but Excel 2007 lets you then sort so the highest scores appear to the left. Then your first sum can simply take the first three scores for the each team. However to get the last persons sum, you have to determine if you can use the 4th score, or if you have to use the max of the junior or Lady types. That could be done using a complex and brute force formula somewhat like this:</p> <p>if (type of position 1 is a junior or a lady or ... 2 or 3... ) then use position 4 else if position 5 is a junior or lady then use 5 else if p 6 is ... and so on.</p>
8,239
<p>I got a Tronxy X5S-400, I assembled it and when I power it on, I see on the screen one of the below images and gets stuck there.</p> <p>Is the firmware broken? If yes, where can I get a <code>configuration.h</code> file?</p> <p>I verified that the two buses between the screen and the mainboard are not loose or incorrectly connected.</p> <p><a href="https://i.stack.imgur.com/ilwaq.jpg" rel="nofollow noreferrer" title="Marlin splash screen"><img src="https://i.stack.imgur.com/ilwaq.jpg" alt="Marlin splash screen" title="Marlin splash screen"></a></p> <p><a href="https://i.stack.imgur.com/IIkog.jpg" rel="nofollow noreferrer" title="Screen corruption"><img src="https://i.stack.imgur.com/IIkog.jpg" alt="Screen corruption" title="Screen corruption"></a></p> <p>The board is a MKS Melzi v2.0 clone</p> <p><a href="https://i.stack.imgur.com/Hhtaw.jpg" rel="nofollow noreferrer" title="Controller"><img src="https://i.stack.imgur.com/Hhtaw.jpg" alt="Controller" title="Controller"></a></p>
<p>It looked like the firmware wasn't flashed correctly in the factory. What I did was to flash a bootloader using an Arduino compatible board and to flash the Marlin software e.g. according to <a href="https://www.youtube.com/watch?v=3gwWVFtdg-4" rel="nofollow noreferrer">videos from this guy</a>.</p> <p>Next, the menu wasn't displayed correctly so I added, in the <code>Configuration.h</code> the following lines:</p> <pre><code>#define ST7920_DELAY_1 DELAY_NS(63) #define ST7920_DELAY_2 DELAY_NS(100) #define ST7920_DELAY_3 DELAY_NS(125) </code></pre> <p>Now the display is working fine, and the Marlin firmware can be directly flashed from the computer because the bootloader remains there.</p> <p>I also had a problem with the heating bed which was heating very slow and I had to raise consistently the <code>TEMP_BED_RESIDENCY_TIME</code> and decrease <code>TEMP_BED_HYSTERESIS</code> to 1.</p>
<p>If the controller is one of Tronxy's new Chitu boards, you will not have the option of recompiling the firmware, since they are locked down. Apart from checking that the PSU is delivering the correct voltage, your only option may be to request a new main board from the vendor.</p>
1,286
<p>When I try to run a .NET assembly (<code>boo.exe</code>) from a network share (mapped to a drive), it fails since it's only partially trusted:</p> <pre><code>Unhandled Exception: System.Security.SecurityException: That assembly does not allow partially trusted callers. at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed) at BooCommandLine..ctor() at Program..ctor() at ProgramModule.Main(String[] argv) The action that failed was: LinkDemand The assembly or AppDomain that failed was: boo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=32c39770e9a21a67 The Zone of the assembly that failed was: Intranet The Url of the assembly that failed was: file:///H:/boo-svn/bin/boo.exe </code></pre> <p>With instructions from <a href="http://www.georgewesolowski.com/blog/PermaLink,guid,4cc5fcdf-cc68-4cf0-a083-b22a8bdc92d6.aspx" rel="nofollow noreferrer">a blog post</a>, I added a policy to the .NET Configuration fully trusting all assemblies with <code>file:///H:/*</code> as their URL. I verified this by entering the URL <code>file:///H:/boo-svn/bin/boo.exe</code> into the <em>Evaluate Assembly</em> tool in the .NET Configuration and noting that boo.exe had the <em>Unrestricted</em> permission (which it didn't have before the policy).</p> <p>Even with the permission, <code>boo.exe</code> does not run. I still get the same error message.</p> <p>What can I do to debug this problem? Is there another way to run "partially trusted" assemblies from network shares without having to change something for every assembly I want to run?</p>
<p>With .NET 3.5 SP1, .NET assemblies running from UNC shares have full permissions. </p> <p>See Brad Abrams's <a href="http://blogs.msdn.com/brada/archive/2007/10/26/adhoc-poll-allowing-net-exes-to-run-off-a-network-share.aspx" rel="noreferrer">Allow .exes to be run off a network shares</a> for workaround and discussions, and finally the follow up <a href="http://blogs.msdn.com/brada/archive/2008/08/13/net-framework-3-5-sp1-allows-managed-code-to-be-launched-from-a-network-share.aspx" rel="noreferrer">.NET 3.5 SP1 allows managed code to be launched from a network share</a>.</p>
<p>I think you want to add the <a href="http://msdn.microsoft.com/en-us/library/system.security.allowpartiallytrustedcallersattribute.aspx" rel="nofollow noreferrer">AllowPartiallyTrustedCallers</a> attribute to your assembly. The error message implies that something that's calling into your boo.exe assembly is not fully trusted, and boo.exe doesn't have this attribute allowing it.</p>
4,407
<p>Basically, I've written an API to www.thetvdb.com in Python. The current code can be found <a href="http://github.com/dbr/tvdb_api/tree/master/tvdb_api.py" rel="noreferrer">here</a>.</p> <p>It grabs data from the API as requested, and has to store the data somehow, and make it available by doing:</p> <pre><code>print tvdbinstance[1][23]['episodename'] # get the name of episode 23 of season 1 </code></pre> <p>What is the "best" way to abstract this data within the <code>Tvdb()</code> class?</p> <p>I originally used a extended <code>Dict()</code> that automatically created sub-dicts (so you could do <code>x[1][2][3][4] = "something"</code> without having to do <code>if x[1].has_key(2): x[1][2] = []</code> and so on)</p> <p>Then I just stored the data by doing <code>self.data[show_id][season_number][episode_number][attribute_name] = "something"</code></p> <p>This worked okay, but there was no easy way of checking if <code>x[3][24]</code> was supposed to exist or not (so I couldn't raise the season_not_found exception).</p> <p>Currently it's using four classes: <code>ShowContainer</code>, <code>Show</code>, <code>Season</code> and <code>Episode</code>. Each one is a very basic dict, which I can easily add extra functionality in (the <code>search()</code> function on <code>Show()</code> for example). Each has a <code>__setitem__</code>, <code>__getitem_</code> and <code>has_key</code>.</p> <p>This works mostly fine, I can check in Shows if it has that season in it's <code>self.data</code> dict, if not, <code>raise season_not_found</code>. I can also check in <code>Season()</code> if it has that episode and so on.</p> <p>The problem now is it's presenting itself as a dict, but doesn't have all the functionality, and because I'm overriding the <code>__getitem__</code> and <code>__setitem__</code> functions, it's easy to accidentally recursively call <code>__getitem__</code> (so I'm not sure if extending the <code>Dict</code> class will cause problems).</p> <p>The other slight problem is adding data into the dict is a lot more work than the old <code>Dict</code> method (which was <code>self.data[seas_no][ep_no]['attribute'] = 'something'</code>). See <code>_setItem</code> and <code>_setData</code>. It's not too bad, since it's currently only a read-only API interface (so the users of the API should only ever retrieve data, not add more), but it's hardly... Elegant.</p> <p>I think the series-of-classes system is probably the best way, but does anyone have a better idea for storing the data? And would extending the <code>ShowContainer</code>/etc classes with <code>Dict</code> cause problems?</p>
<p>OK, what you need is <code>classobj</code> from new module. That would allow you to construct exception classes dynamically (<code>classobj</code> takes a string as an argument for the class name). </p> <pre><code>import new myexc=new.classobj("ExcName",(Exception,),{}) i=myexc("This is the exc msg!") raise i </code></pre> <p>this gives you:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; __main__.ExcName: This is the exc msg! </code></pre> <p>remember that you can always get the class name through:</p> <pre><code>self.__class__.__name__ </code></pre> <p>So, after some string mangling and concatenation, you should be able to obtain appropriate exception class name and construct a class object using that name and then raise that exception.</p> <p>P.S. - you can also raise strings, but this is deprecated.</p> <pre><code>raise(self.__class__.__name__+"Exception") </code></pre>
<p>I have done something similar in the past and used an in-memory XML document as a quick and dirty hierarchical database for storage. You can store each show/season/episode as an element (nested appropriately) and attributes of these things as xml attributes on the elements. Then you can use XQuery to get info back out.</p> <p><strong>NOTE:</strong> I'm not a Python guy so I don't know what your xml support is like.</p> <p><strong>NOTE 2:</strong> You'll want to profile this because it'll be bigger and slower than the solution you've already got. Likely enough if you are doing some high-volume processing then XML is probably not going to be your friend.</p>
2,783
<p>I have an inherited project that uses a build script (not make) to build and link the project with various libraries.</p> <p>When it performs a build I would like to parse the build output to determine what and where the actual static libraries being linked into the final executable are and where are they coming from.</p> <p>The script is compiling and linking with GNU tools.</p>
<p>You might try using the <code>nm</code> tool. Given the right options, it will look at a binary (archive or linked image) and tell you what objects were linked into it.</p> <p>Actually, here's a one-liner I use at work:</p> <pre><code>#!/bin/sh nm -Ag $* | sed 's/^.*\/\(.*\.a\):/\1/' | sort -k 3 | grep -v ' U ' </code></pre> <p>to find the culprits for undefined symbols. Just chop off the last grep expression and it should pretty much give you what you want.</p>
<p>Static libraries, that makes life more difficult in this regard. In case of dynamic libraries you could just have used ldd on the resulting executable and be done with it. The best bet would be some kind of configuration file. Alternatively you could try to look for -l arguments to gcc/ld. Those are used to specify libraries. You could write a script for extracting it from the output, though I suspect that you will have to do it manually because by the time you know what the script should look for you probably already know the answer.</p>
7,003
<p>What is the best way to verify/test that a text string is serialized to a byte array with a certain encoding?</p> <p>In my case, I want to verify that an XML structure is serialized to a byte array with the UTF-8 encoding which is of variable character length. As an example, my current ugly procedure is to inject a character known to require two bytes into the structure before serializing, then replacing the two-byte character with an ASCII character and comparing the serialized array lengths. This should yield two serialized arrays where the array containing the two-byte characters should have length +1.</p> <p>Plus if the solution is elegant for Java. I can't think of any elegant way to seek for a byte sequence in a byte array. (Could be used to seek for a known byte sequence representing the desired character representation in UTF-8.)</p>
<p>Perhaps you could deserialise the byte array using a known encoding and ensure that (a) it doesn't throw any exceptions, and (b) deserialises to the original string. It seems that from your description of the scenario, you may not have the original string readily available. Might there be a way to create it?</p>
<p>That's good. You're right, I don't have the original string, since I'm testing a module that creates an XML document as a byte array. I didn't think about deserializing to a String with an expected encoding. That will do the trick.</p>
2,928
<p>So I've got a <code>JPanel</code> implementing <code>MouseListener</code> and <code>MouseMotionListener</code>:</p> <pre><code>import javax.swing.*; import java.awt.*; import java.awt.event.*; public class DisplayArea extends JPanel implements MouseListener, MouseMotionListener { public DisplayArea(Rectangle bounds, Display display) { setLayout(null); setBounds(bounds); setOpaque(false); setPreferredSize(new Dimension(bounds.width, bounds.height)); this.display = display; } public void paintComponent(Graphics g) { Graphics2D g2 = (Graphics2D)g; if (display.getControlPanel().Antialiasing()) { g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); } g2.setColor(Color.white); g2.fillRect(0, 0, getWidth(), getHeight()); } public void mousePressed(MouseEvent event) { System.out.println("mousePressed()"); mx1 = event.getX(); my1 = event.getY(); } public void mouseReleased(MouseEvent event) { System.out.println("mouseReleased()"); mx2 = event.getX(); my2 = event.getY(); int mode = display.getControlPanel().Mode(); switch (mode) { case ControlPanel.LINE: System.out.println("Line from " + mx1 + ", " + my1 + " to " + mx2 + ", " + my2 + "."); } } public void mouseEntered(MouseEvent event) { System.out.println("mouseEntered()"); } public void mouseExited(MouseEvent event) { System.out.println("mouseExited()"); } public void mouseClicked(MouseEvent event) { System.out.println("mouseClicked()"); } public void mouseMoved(MouseEvent event) { System.out.println("mouseMoved()"); } public void mouseDragged(MouseEvent event) { System.out.println("mouseDragged()"); } private Display display = null; private int mx1 = -1; private int my1 = -1; private int mx2 = -1; private int my2 = -1; } </code></pre> <p>The trouble is, none of these mouse functions are ever called. <code>DisplayArea</code> is created like this:</p> <pre><code>da = new DisplayArea(new Rectangle(CONTROL_WIDTH, 0, DISPLAY_WIDTH, DISPLAY_HEIGHT), this); </code></pre> <p>I am not really a Java programmer (this is part of an assignment), but I can't see anything glaringly obvious. Can someone smarter than I see anything?</p>
<p>The <em>implements mouselistener, mousemotionlistener</em> just allows the displayArea class to listen to some, to be defined, Swing component's mouse events. You have to explicitly define what it should be listening at. So I suppose you could add something like this to the constructor:</p> <pre><code>this.addMouseListener(this); this.addMouseMotionListener(this); </code></pre>
<p>I don't see anywhere in the code where you call addMouseListener(this) or addMouseMotionListener(this) for the DisplayArea in order for it to subscribe to those events. </p>
5,377
<p>The RFC for a Java class is set of all methods that can be invoked in response to a message to an object of the class or by some method in the class. RFC = M + R where M = Number of methods in the class. R = Total number of other methods directly invoked from the M.</p> <p>Thinking C is the .class and J is the .java file of which we need to calculate RFC.</p> <pre> class J{ a(){} b(){} c(){ e1.e(); e1.f(); e1.g(); } h(){ i.k(); i.j(); } m(){} n(){ i.o(); i.p(); i.p(); i.p(); } } </pre> <p>here M=6 and R=9 (Don't worry about call inside a loop. It's considered as a single call)</p> <p>Calculating M is easy. Load C using classloader and use reflection to get the count of methods.</p> <p>Calculating R is not direct. We need to count the number of method calls from the class. First level only. </p> <p>For calculating R I must use regex. Usually format would be (calls without using . are not counted)</p> <pre> [variable_name].[method_name]([zero or more parameters]); </pre> <p>or</p> <pre> [variable_name].[method_name]([zero or more parameters]) </pre> <p>with out semicolon when call return is directly becomes parameter to another method. or </p> <pre> [variable_name].[method_name]([zero or more parameters]).method2(); </pre> <p>this becomes two method calls</p> <p>What other patterns of the method call can you think of? Is there any other way other than using RegEx that can be used to calculate R.</p> <hr> <p><strong>UPDATE:</strong><br> <a href="https://stackoverflow.com/questions/19952/rfc-calculation-in-java-need-help-with-algorithm#19983" title="@McDowell">@McDowell</a> Looks like using BCEL I can simplify the whole process. Let me try it.</p>
<p>You could use the <a href="http://jakarta.apache.org/bcel/index.html" rel="nofollow noreferrer">Byte Code Engineering Library</a> with binaries. You can use a <a href="http://jakarta.apache.org/bcel/apidocs/org/apache/bcel/classfile/DescendingVisitor.html" rel="nofollow noreferrer">DescendingVisitor</a> to visit a class' members and references. I've used it to <a href="http://illegalargumentexception.blogspot.com/2008/04/java-finding-binary-class-dependencies.html" rel="nofollow noreferrer">find class dependencies</a>.</p> <p>Alternatively, you could reuse some model of the source files. I'm pretty sure the Java editor in the <a href="http://www.eclipse.org/jdt/" rel="nofollow noreferrer">Eclipse JDT</a> is backed by some form of model.</p>
<p>You should find your answer in the <a href="http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html" rel="nofollow noreferrer">Java language specification</a>.</p> <p>You have forgot static method call, method call inside parameters...</p>
4,029
<p>I will elaborate somewhat. Jsf is kind-of extremely painful for working with from designer's perspective, somewhat in the range of trying to draw a picture while having hands tied at your back, but it is good for chewing up forms and listing lots of data. So sites we are making in my company are jsf admin pages and jsp user pages. Problem occurs when user pages have some complicated forms and stuff and jsf starts kickin' in. </p> <p>Here is the question: I'm on pure jsp page. I need to access some jsf page that uses session bean. How can I initialize that bean? If I was on jsf page, I could have some commandLink which would prepare data. Only thing I can come up with is having dummy jsf page that will do the work and redirect me to needed jsf page, but that's kind of ugly, and I don't want to end up with 50 dummy pages. I would rather find some mechanism to reinitialize bean that is already in session with some wanted parameters.</p> <p>Edit: some more details. In this specific situation, I have a tests that are either full or filtered. It's a same test with same logic and everything, except if test is filtered, it should eliminate some questions depending on answers. Upon a clicking a link, it should start a requested test in one of the two modes. Links are parts of main menu-tree and are visible on many sibling jsp pages. My task is to have 4 links: testA full, testA filtered, testB full, testB filtered, that all lead on same jsf page and TestFormBean should be reinitialized accordingly.</p> <p>Edit: I've researched facelets a bit, and while it won't help me now, I'll definitely keep that in mind for next project.</p>
<p>have you looked into using facelets? It lets you get rid of the whole JSF / JSP differences (it's an alternate and superior view controller).</p> <p>It also supports great design-time semantics with the jsfc tag...</p> <pre><code>&lt;input type="text" jsfc="#{SomeBean.property}" class="foo" /&gt; </code></pre> <p>gets translated internally to the correct JSF stuff, so you can work with your existing tools.</p>
<p>Create a custom JSP tag handler. You can then retrieve the bean from session scope and then initialize it on the fly. See this <a href="http://java.sun.com/products/jsp/tutorial/TagLibrariesTOC.html" rel="nofollow noreferrer">tutorial</a> for more details.</p>
6,443
<p>I would like to have a VM to look at how applications appear and to develop OS-specific applications, however, I want to keep all my code on my Windows machine so if I decide to nuke a VM or anything like that, it's all still there.</p> <p>If it matters, I'm using VirtualBox.</p>
<p>This is usually handled with network shares. Share your code folder from your host machine and access it from the VMs.</p>
<p>I do this all the time. I have a directory in a Windows drive that I mount in my host ubuntu 12.04. I run virtualbox ubuntu 13.04 as a guest. I want the guest to mount the Windows directory with full non-root permissions. I do almost all my work from a bash shell, so this method is natural for me.</p> <p>When searching for methods to automatically mount virtualbox shared folders, reliable and correct methods are hard to distinguish from those that fail. Failures include getting and setting permissions, as well as other problems.</p> <p>Methods that fail include:</p> <ul> <li>modifying /etc/fstab</li> <li>modifying /etc/rc.local</li> </ul> <p>I am fairly certain that rc.local can be used, but no methods I have tried worked. I welcome improvements on these guidelines.</p> <p>On virtualbox 4.2.14 running nautilus (bash terminal) on an ubuntu 13.04 guest, Below is a working method to mount Common (sharename) on /home/$USER/Desktop/Common (mountpoint) with full permissions. (Note the ‘\’ command continuation character in the find command.)</p> <p>First time only: create your mountpoint, modify your .bashrc file, and run it. Respond with password when requested. These are the four command-lines needed:</p> <pre><code>mkdir $HOME/Desktop/Common sudo echo “$USER ALL=(ALL) NOPASSWD:ALL” &gt;&gt; /etc/sudoers find $HOME/Desktop/Common -maxdepth 0 -type d -empty -exec sudo \ mount -t vboxsf -o \ uid=`id -u $USER`,gid=`id -g $USER` Common $HOME/Desktop/Common \; source ~/.bashrc # Needed if you want to mount Common in this bash. </code></pre> <p>All other times: simply launch a bash shell.</p> <p>The find command mounts the shared directory if the mountpoint directory is empty. If the mountpoint directory is not empty, it does not run the mount command.</p> <p>I hope this is error-free and sufficiently general. Please let me know of corrections and improvements.</p>
6,830
<p>How do we create a search plugin for Safari? Like <a href="https://stackoverflow.com/questions/20830/firefox-users-here-is-your-stackoverflow-search-plugin">this post</a> </p>
<p><a href="http://pimpmysafari.com/plugins/keywurl" rel="nofollow noreferrer">Here</a> is a Safari plugin whereby you can customize it to search other sites. May work with Stack Overflow (I haven't tried it). Check out that site too for other Safari plugins.</p>
<p>AFAIK, Safari doesn't have a Search plugin capability. You could try <a href="http://www.inquisitorx.com/safari/index_en.php" rel="nofollow noreferrer">Inquisitor</a>; just add the URL <a href="https://stackoverflow.com/search?s=%@">https://stackoverflow.com/search?s=%@</a></p>
4,262
<p>I'm running some <a href="http://jakarta.apache.org/jmeter/" rel="noreferrer">JMeter</a> tests against a Java process to determine how responsive a web application is under load (500+ users). JMeter will give the response time for each web request, and I've written a script to ping the Tomcat Manager every X seconds which will get me the current size of the JVM heap.</p> <p>I'd like to collect stats on the server of the % of CPU being used by Tomcat. I tried to do it in a shell script using <code>ps</code> like this:</p> <pre><code>PS_RESULTS=`ps -o pcpu,pmem,nlwp -p $PID` </code></pre> <p>...running the command every X seconds and appending the results to a text file. (for anyone wondering, <code>pmem</code> = % mem usage and <code>nlwp</code> is number of threads)</p> <p>However I've found that this gives a different definition of "% of CPU Utilization" than I'd like - according to the manpages for ps, <code>pcpu</code> is defined as:</p> <blockquote> <p>cpu utilization of the process in "##.#" format. It is the CPU time used divided by the time the process has been running (cputime/realtime ratio), expressed as a percentage. </p> </blockquote> <p>In other words, <code>pcpu</code> gives me the % CPU utilization for the process for the <em>lifetime</em> of the process.</p> <p>Since I want to take a sample every X seconds, I'd like to be collecting the CPU utilization of the process at the current time only - similar to what <code>top</code> would give me (CPU utilization of the process since the last update). </p> <p>How can I collect this from within a shell script? </p>
<p>Use <code>top -b</code> (and other switches if you want different outputs). It will just dump to stdout instead of jumping into a curses window.</p>
<p>also use 1 as iteration count, so you will get current snapshot without waiting to get another one in $delay time.</p> <pre><code>top -b -n 1 </code></pre>
7,305
<p>I need to validate a date/time field on a webpage but want it to do it without reloading the page and would like 'instant' feedback for the users.</p> <p>What's the best/easiest solution. BTW: easiest scores 65% of total points</p> <p>Edit: What if best was 65% of total points?</p>
<p>Check out this <a href="http://www.expertsrt.com/scripts/Rod/validate_date.php" rel="nofollow noreferrer">javascript date validation</a> function.</p> <p>It uses javascript, regular expressions and the 'onblur' event of a text input.</p>
<p>A simple javascript method that reads what's in the input field on submit and validates it. If it's not valid, return false so that the form is not submitted to the server.</p> <pre><code>... onSubmit="return validateForm();" ... </code></pre> <p>Make sure you validate on the server side too, it's easy to bypass javascript validation.</p>
3,179
<p>This is a bit hypothetical and grossly simplified but...</p> <p>Assume a program that will be calling functions written by third parties. These parties can be assumed to be non-hostile but can't be assumed to be "competent". Each function will take some arguments, have side effects and return a value. They have no state while they are not running.</p> <p>The objective is to ensure they can't cause memory leaks by logging all mallocs (and the like) and then freeing everything after the function exits.</p> <p>Is this possible? Is this practical?</p> <p>p.s. The important part to me is ensuring that no allocations persist so ways to remove memory leaks without doing that are not useful to me.</p>
<p>You don't specify the operating system or environment, this answer assumes Linux, glibc, and C.</p> <p>You can set __malloc_hook, __free_hook, and __realloc_hook to point to functions which will be called from malloc(), realloc(), and free() respectively. There is a __malloc_hook manpage showing the prototypes. You can add track allocations in these hooks, then return to let glibc handle the memory allocation/deallocation.</p> <p>It sounds like you want to free any live allocations when the third-party function returns. There are ways to have gcc automatically insert calls at every function entrance and exit using -finstrument-functions, but I think that would be inelegant for what you are trying to do. Can you have your own code call a function in your memory-tracking library after calling one of these third-party functions? You could then check if there are any allocations which the third-party function did not already free.</p>
<p>Since you're worried about memory leaks and talking about malloc/free, I assume you're in C. I'm also assuming based on your question that you do not have access to the source code of the third party library.</p> <p>The only thing I can think of is to examine memory consumption of your app before &amp; after the call, log error messages if they're different and convince the third party vendor to fix any leaks you find.</p>
7,366
<p>Given an integer typedef:</p> <pre><code>typedef unsigned int TYPE; </code></pre> <p>or</p> <pre><code>typedef unsigned long TYPE; </code></pre> <p>I have the following code to reverse the bits of an integer:</p> <pre><code>TYPE max_bit= (TYPE)-1; void reverse_int_setup() { TYPE bits= (TYPE)max_bit; while (bits &lt;&lt;= 1) max_bit= bits; } TYPE reverse_int(TYPE arg) { TYPE bit_setter= 1, bit_tester= max_bit, result= 0; for (result= 0; bit_tester; bit_tester&gt;&gt;= 1, bit_setter&lt;&lt;= 1) if (arg &amp; bit_tester) result|= bit_setter; return result; } </code></pre> <p>One just needs first to run reverse_int_setup(), which stores an integer with the highest bit turned on, then any call to reverse_int(<em>arg</em>) returns <em>arg</em> with its bits reversed (to be used as a key to a binary tree, taken from an increasing counter, but that's more or less irrelevant).</p> <p>Is there a platform-agnostic way to have in compile-time the correct value for max_int after the call to reverse_int_setup(); Otherwise, is there an algorithm you consider <em>better/leaner</em> than the one I have for reverse_int()?</p> <p>Thanks.</p>
<pre><code>#include&lt;stdio.h&gt; #include&lt;limits.h&gt; #define TYPE_BITS sizeof(TYPE)*CHAR_BIT typedef unsigned long TYPE; TYPE reverser(TYPE n) { TYPE nrev = 0, i, bit1, bit2; int count; for(i = 0; i &lt; TYPE_BITS; i += 2) { /*In each iteration, we swap one bit on the 'right half' of the number with another on the left half*/ count = TYPE_BITS - i - 1; /*this is used to find how many positions to the left (and right) we gotta move the bits in this iteration*/ bit1 = n &amp; (1&lt;&lt;(i/2)); /*Extract 'right half' bit*/ bit1 &lt;&lt;= count; /*Shift it to where it belongs*/ bit2 = n &amp; 1&lt;&lt;((i/2) + count); /*Find the 'left half' bit*/ bit2 &gt;&gt;= count; /*Place that bit in bit1's original position*/ nrev |= bit1; /*Now add the bits to the reversal result*/ nrev |= bit2; } return nrev; } int main() { TYPE n = 6; printf("%lu", reverser(n)); return 0; } </code></pre> <p>This time I've used the 'number of bits' idea from TK, but made it somewhat more portable by not assuming a byte contains 8 bits and instead using the CHAR_BIT macro. The code is more efficient now (with the inner for loop removed). I hope the code is also slightly less cryptic this time. :)</p> <p>The need for using count is that the number of positions by which we have to shift a bit varies in each iteration - we have to move the rightmost bit by 31 positions (assuming 32 bit number), the second rightmost bit by 29 positions and so on. Hence count must decrease with each iteration as i increases. </p> <p>Hope that bit of info proves helpful in understanding the code... </p>
<p>How about:</p> <pre><code>long temp = 0; int counter = 0; int number_of_bits = sizeof(value) * 8; // get the number of bits that represent value (assuming that it is aligned to a byte boundary) while(value &gt; 0) // loop until value is empty { temp &lt;&lt;= 1; // shift whatever was in temp left to create room for the next bit temp |= (value &amp; 0x01); // get the lsb from value and set as lsb in temp value &gt;&gt;= 1; // shift value right by one to look at next lsb counter++; } value = temp; if (counter &lt; number_of_bits) { value &lt;&lt;= counter-number_of_bits; } </code></pre> <p>(I'm assuming that you know how many bits value holds and it is stored in number_of_bits)</p> <p>Obviously temp needs to be the longest imaginable data type and when you copy temp back into value, all the extraneous bits in temp should magically vanish (I think!). </p> <p>Or, the 'c' way would be to say :</p> <pre><code>while(value) </code></pre> <p>your choice</p>
8,922
<p>I've recently bought myself a preassembled Prusa i3 MK3S printed and made my first projects. One of them was making a cup with my name on it. I want to use it to drink tea, water etc. I know, however, that I need to chose my filament wisely, as using the wrong one might be unsafe. I know that PLA for example is Polylactic acid which is a safe substance and occurs naturally in our body. Another thing is the dye, which can is a chemical substance I know nothing about. Do You recommend any specific type/model? Thanks.</p>
<p>Answer was moved to this question: <a href="https://3dprinting.stackexchange.com/questions/147/which-are-the-food-safe-materials-and-how-do-i-recognize-them">Which are the food-safe materials and how do I recognize them?</a></p>
<p>I think this site will answer some questions about food safe 3D printing: <a href="https://all3dp.com/1/food-safe-3d-printing-abs-pla-food-safe-filament/" rel="nofollow noreferrer">12 Vital Facts About Food Safe 3D Printing</a></p> <p>PLA is not a good choice for hot substances because it will deform at hot water temperatures which is no good for a cup (very dangerous!)</p> <p>I would recommend a filament like PETG, PETE, HDPE, and LDPE: <a href="https://www.custom-pak.com/what-plastics-are-approved-for-food-contact-applications/" rel="nofollow noreferrer">What Plastics Are Approved for Food Contact Applications?</a></p> <p>Those types of plastic require very high printing temperatures and an all metal hot end. You don't want PTFE in your hot end when printing at those temperatures (265&nbsp;°C) as it will emit toxic gasses.</p> <p>I've seen food safe filaments for sale so it might be best to search Google for one of them to use.</p> <p>Please keep in mind that printing anything will cause voids and gaps that will allow bacteria to grow. Personally I don't think I would want to risk it for daily use items but a coffee/tea cup might be alright. This is covered in the first link.</p>
1,361
<p>When creating a criteria in NHibernate I can use</p> <p>Restriction.In() or<br> Restriction.InG()</p> <p>What is the difference between them?</p>
<p>InG is the generic equivalent of In (for collections)</p> <p>The signatures of the methods are as follows (only the ICollection In overload is shown):</p> <pre><code>In(string propertyName, ICollection values) </code></pre> <p>vs.</p> <pre><code>InG&lt;T&gt;(string propertyName, ICollection&lt;T&gt; values) </code></pre> <p>Looking at NHibernate's source code (trunk) it seems that they both copy the collection to an object array and use that going forward, so I don't think there is a performance difference between them.</p> <p>I personally just use the In one most of the time - its easier to read.</p>
<p>Restriction.In definately creates a subquery with whatever criteria you pass to the .In() method, but not sure what InG() does. never seen it.</p>
5,137
<p>PHP's explode function returns an array of strings split on some provided substring. It will return empty strings when there are leading, trailing, or consecutive delimiters, like this:</p> <pre><code>var_dump(explode('/', '1/2//3/')); array(5) { [0]=&gt; string(1) &quot;1&quot; [1]=&gt; string(1) &quot;2&quot; [2]=&gt; string(0) &quot;&quot; [3]=&gt; string(1) &quot;3&quot; [4]=&gt; string(0) &quot;&quot; } </code></pre> <p>Is there some different function or option or anything that would return everything <em>except</em> the empty strings?</p> <pre><code>var_dump(different_explode('/', '1/2//3/')); array(3) { [0]=&gt; string(1) &quot;1&quot; [1]=&gt; string(1) &quot;2&quot; [2]=&gt; string(1) &quot;3&quot; } </code></pre>
<p>Try <a href="http://php.net/preg_split" rel="nofollow noreferrer">preg_split</a>.</p> <p><code>$exploded = preg_split('@/@', '1/2//3/', -1, PREG_SPLIT_NO_EMPTY);</code></p>
<p>I usually wrap it in a call to <a href="http://uk.php.net/manual/en/function.array-filter.php" rel="nofollow noreferrer">array_filter</a>, e.g.</p> <pre><code>var_dump(array_filter(explode('/', '1/2//3/')) =&gt; array(3) { [0]=&gt; string(1) "1" [1]=&gt; string(1) "2" [3]=&gt; string(1) "3" } </code></pre> <p>Be aware, of course, that array keys are maintained; if you <em>don't</em> want this behaviour, remember to add an outer wrapper call to array_values().</p>
9,013
<p>Assuming String a and b:</p> <pre><code>a += b a = a.concat(b) </code></pre> <p>Under the hood, are they the same thing?</p> <p>Here is concat decompiled as reference. I'd like to be able to decompile the <code>+</code> operator as well to see what that does.</p> <pre><code>public String concat(String s) { int i = s.length(); if (i == 0) { return this; } else { char ac[] = new char[count + i]; getChars(0, count, ac, 0); s.getChars(0, i, ac, count); return new String(0, count + i, ac); } } </code></pre>
<p>No, not quite.</p> <p>Firstly, there's a slight difference in semantics. If <code>a</code> is <code>null</code>, then <code>a.concat(b)</code> throws a <code>NullPointerException</code> but <code>a+=b</code> will treat the original value of <code>a</code> as if it were <code>null</code>. Furthermore, the <code>concat()</code> method only accepts <code>String</code> values while the <code>+</code> operator will silently convert the argument to a String (using the <code>toString()</code> method for objects). So the <code>concat()</code> method is more strict in what it accepts.</p> <p>To look under the hood, write a simple class with <code>a += b;</code></p> <pre><code>public class Concat { String cat(String a, String b) { a += b; return a; } } </code></pre> <p>Now disassemble with <code>javap -c</code> (included in the Sun JDK). You should see a listing including:</p> <pre><code>java.lang.String cat(java.lang.String, java.lang.String); Code: 0: new #2; //class java/lang/StringBuilder 3: dup 4: invokespecial #3; //Method java/lang/StringBuilder."&lt;init&gt;":()V 7: aload_1 8: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 11: aload_2 12: invokevirtual #4; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; 15: invokevirtual #5; //Method java/lang/StringBuilder.toString:()Ljava/lang/ String; 18: astore_1 19: aload_1 20: areturn </code></pre> <p>So, <code>a += b</code> is the equivalent of</p> <pre><code>a = new StringBuilder() .append(a) .append(b) .toString(); </code></pre> <p>The <code>concat</code> method should be faster. However, with more strings the <code>StringBuilder</code> method wins, at least in terms of performance.</p> <p>The source code of <code>String</code> and <code>StringBuilder</code> (and its package-private base class) is available in src.zip of the Sun JDK. You can see that you are building up a char array (resizing as necessary) and then throwing it away when you create the final <code>String</code>. In practice memory allocation is surprisingly fast.</p> <p><strong>Update:</strong> As Pawel Adamski notes, performance has changed in more recent HotSpot. <code>javac</code> still produces exactly the same code, but the bytecode compiler cheats. Simple testing entirely fails because the entire body of code is thrown away. Summing <code>System.identityHashCode</code> (not <code>String.hashCode</code>) shows the <code>StringBuffer</code> code has a slight advantage. Subject to change when the next update is released, or if you use a different JVM. From <a href="https://twitter.com/lukaseder" rel="noreferrer">@lukaseder</a>, <a href="https://gist.github.com/apangin/7a9b7062a4bd0cd41fcc" rel="noreferrer">a list of HotSpot JVM intrinsics</a>.</p>
<p>Note that <code>s.concat(&quot;hello&quot;);</code> would result in a <code>NullPointereException</code> when s is null. In Java, the behavior of the + operator is usually determined by the left operand:</p> <p><code>System.out.println(3 + 'a'); //100</code></p> <p>However, Strings are an exception. If either operand is a String, the result is expected to be a String. This is the reason null is converted into &quot;null&quot;, even though you might expect a <code>RuntimeException</code>.</p>
6,987