instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>How would I remove the border from an iframe embedded in my web app? An example of the iframe is:</p> <pre><code>&lt;iframe src="myURL" width="300" height="300"&gt;Browser not compatible.&lt;/iframe&gt; </code></pre> <p>I would like the transition from the content on my page to the contents of the iframe to be seamless, assuming the background colors are consistent. The target browser is IE6 only and unfortunately solutions for others will not help.</p>
<p>Add the <code>frameBorder</code> attribute (note the <strong>capital ‘B’</strong>).</p> <p>So it would look like:</p> <pre><code>&lt;iframe src="myURL" width="300" height="300" frameBorder="0"&gt;Browser not compatible.&lt;/iframe&gt; </code></pre>
<pre><code>iframe src="XXXXXXXXXXXXXXX" marginwidth="0" marginheight="0" width="xxx" height="xxx" </code></pre> <p>Works with Firefox ;)</p>
9,073
<p>I need to take a BufferedImage and convert it to YCbCr format so that I can do a more efficient Brightness/contrast manipulation on it, but I can't figure out how to do this. I've tried ColorConvertOp but there doesn't seem to be an appropriate ColorSpace for YCbCr (though there is a type for it?). </p> <p>I could do the conversion manually (the conversion is not difficult) but this would immediately kick my image out of the 'fast-path'. Does anyone know a solution?</p>
<p>Are the two partial classes in the same namespace? That could be an explanation.</p>
<p>Just for reference (VS 2020)... Error CS0103 =&gt; All same but different folder.</p> <p>But classes should have same namespace AND ALSO BE in same folder !!!</p> <p>Although they could be defined in the same namespace, both files should be in the same folder. I know that the folder structure should reflect the namespace but for clarity between the generated code and my added code, I wanted to separate by folder, but it does not works.</p>
22,369
<p>How do I iterate over a timespan after days, hours, weeks or months?</p> <p>Something like:</p> <pre><code>for date in foo(from_date, to_date, delta=HOURS): print date </code></pre> <p>Where foo is a function, returning an iterator. I've been looking at the calendar module, but that only works for one specific year or month, not between dates.</p>
<p>Use <a href="http://labix.org/python-dateutil" rel="noreferrer">dateutil</a> and its rrule implementation, like so:</p> <pre><code>from dateutil import rrule from datetime import datetime, timedelta now = datetime.now() hundredDaysLater = now + timedelta(days=100) for dt in rrule.rrule(rrule.MONTHLY, dtstart=now, until=hundredDaysLater): print dt </code></pre> <p>Output is</p> <pre><code>2008-09-30 23:29:54 2008-10-30 23:29:54 2008-11-30 23:29:54 2008-12-30 23:29:54 </code></pre> <p>Replace MONTHLY with any of YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, or SECONDLY. Replace dtstart and until with whatever datetime object you want.</p> <p>This recipe has the advantage for working in all cases, including MONTHLY. Only caveat I could find is that if you pass a day number that doesn't exist for all months, it skips those months.</p>
<p>This library provides a handy calendar tool: <a href="http://www.egenix.com/products/python/mxBase/mxDateTime/" rel="nofollow noreferrer">mxDateTime</a>, that should be enough :)</p>
18,542
<p>I've got an <code>RSA</code> private key in <code>PEM</code> format, is there a straight forward way to read that from .NET and instantiate an <code>RSACryptoServiceProvider</code> to decrypt data encrypted with the corresponding public key?</p>
<h3>Update 03/03/2021</h3> <p>.NET 5 now supports this out of the box.</p> <p>To try the code snippet below, generate a keypair and encrypt some text at <a href="http://travistidwell.com/jsencrypt/demo/" rel="noreferrer">http://travistidwell.com/jsencrypt/demo/</a></p> <pre><code>var privateKey = @&quot;-----BEGIN RSA PRIVATE KEY----- { the full PEM private key } -----END RSA PRIVATE KEY-----&quot;; var rsa = RSA.Create(); rsa.ImportFromPem(privateKey.ToCharArray()); var decryptedBytes = rsa.Decrypt( Convert.FromBase64String(&quot;{ base64-encoded encrypted string }&quot;), RSAEncryptionPadding.Pkcs1 ); // this will print the original unencrypted string Console.WriteLine(Encoding.UTF8.GetString(decryptedBytes)); </code></pre> <h3>Original answer</h3> <p>I solved, thanks. In case anyone's interested, <a href="http://www.bouncycastle.org/" rel="noreferrer">bouncycastle</a> did the trick, just took me some time due to lack of knowledge from on my side and documentation. This is the code:</p> <pre><code>var bytesToDecrypt = Convert.FromBase64String(&quot;la0Cz.....D43g==&quot;); // string to decrypt, base64 encoded AsymmetricCipherKeyPair keyPair; using (var reader = File.OpenText(@&quot;c:\myprivatekey.pem&quot;)) // file containing RSA PKCS1 private key keyPair = (AsymmetricCipherKeyPair) new PemReader(reader).ReadObject(); var decryptEngine = new Pkcs1Encoding(new RsaEngine()); decryptEngine.Init(false, keyPair.Private); var decrypted = Encoding.UTF8.GetString(decryptEngine.ProcessBlock(bytesToDecrypt, 0, bytesToDecrypt.Length)); </code></pre>
<p>Check <a href="http://msdn.microsoft.com/en-us/library/dd203099.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/dd203099.aspx</a></p> <p>under Cryptography Application Block.</p> <p>Don't know if you will get your answer, but it's worth a try.</p> <p><strong>Edit after Comment</strong>.</p> <p>Ok then check this code.</p> <pre><code>using System.Security.Cryptography; public static string DecryptEncryptedData(stringBase64EncryptedData, stringPathToPrivateKeyFile) { X509Certificate2 myCertificate; try{ myCertificate = new X509Certificate2(PathToPrivateKeyFile); } catch{ throw new CryptographicException("Unable to open key file."); } RSACryptoServiceProvider rsaObj; if(myCertificate.HasPrivateKey) { rsaObj = (RSACryptoServiceProvider)myCertificate.PrivateKey; } else throw new CryptographicException("Private key not contained within certificate."); if(rsaObj == null) return String.Empty; byte[] decryptedBytes; try{ decryptedBytes = rsaObj.Decrypt(Convert.FromBase64String(Base64EncryptedData), false); } catch { throw new CryptographicException("Unable to decrypt data."); } // Check to make sure we decrpyted the string if(decryptedBytes.Length == 0) return String.Empty; else return System.Text.Encoding.UTF8.GetString(decryptedBytes); } </code></pre>
30,182
<p>I know the answer is not going to be simple, and I already use a couple of (I think ugly) cludges. I am simply looking for some elegant answers.</p> <p>Abstract class:</p> <pre><code>public interface IOtherObjects; public abstract class MyObjects&lt;T&gt; where T : IOtherObjects { ... public List&lt;T&gt; ToList() { ... } } </code></pre> <p>Children:</p> <pre><code>public class MyObjectsA : MyObjects&lt;OtherObjectA&gt; //(where OtherObjectA implements IOtherObjects) { } public class MyObjectsB : MyObjects&lt;OtherObjectB&gt; //(where OtherObjectB implements IOtherObjects) { } </code></pre> <p>Is it possible, looping through a collection of MyObjects (or other similar grouping, generic or otherwise) to then utilise to <em>ToList</em> method of the <em>MyObjects</em> base class, as we do not specifically know the type of T at this point. </p> <p><strong>EDIT</strong> As for specific examples, whenever this has come up, I've thought about it for a while, and done something different instead, so there is no current requirement. but as it has come up quite frequently, I thought I would float it.</p> <p><strong>EDIT</strong> @Sara, it's not the specific type of the collection I care about, it could be a List, but still the ToList method of each instance is relatively unusable, without an anonymous type)</p> <p>@aku, true, and this question may be relatively hypothetical, however being able to retrieve, and work with a list of T of objects, knowing only their base type would be very useful. Having the ToList returning a List Of BaseType has been one of my workarounds</p> <p><strong>EDIT</strong> @ all: So far, this has been the sort of discussion I was hoping for, though it largely confirms all I suspected. Thanks all so far, but anyone else, feel free to input.</p> <p><strong>EDIT</strong>@Rob, Yes it works for a defined type, but not when the type is only known as a List of IOtherObjects. </p> <p>@Rob <strong>Again</strong> Thanks. That has usually been my cludgy workaround (no disrespect :) ). Either that or using the ConvertAll function to Downcast through a delegate. Thanks for taking the time to understand the problem.</p> <p><strong>QUALIFYING EDIT</strong> in case I have been a little confusing</p> <p>To be more precise, (I may have let my latest implementation of this get it too complex):</p> <p>lets say I have 2 object types, B and C inheriting from object A.</p> <p>Many scenarios have presented themselves where, from a List of B or a List of C, or in other cases a List of either - but I don't know which if I am at a base class, I have needed a less specific List of A. </p> <p>The above example was a watered-down example of the <em>List Of Less Specific</em> problem's latest incarnation.</p> <p>Usually it has presented itself, as I think through possible scenarios that limit the amount of code that needs writing and seems a little more elegant than other options. I really wanted a discussion of possibilities and other points of view, which I have more or less got. I am surprised no one has mentioned ConvertAll() so far, as that is another workaround I have used, but a little too verbose for the scenarios at hand</p> <p>@Rob <strong>Yet Again</strong> and Sara</p> <p>Thanks, however I do feel I understand generics in all their static contexted glory, and did understand the issues at play here.</p> <p>The actual design of our system and usage of generics it (and I can say this without only a touch of bias, as I was only one of the players in the design), has been done well. It is when I have been working with the core API, I have found situations when I have been in the wrong scope for doing something simply, instead I had to deal with them with a little less elegant than I like (trying either to be clever or perhaps lazy - I'll accept either of those labels).</p> <p>My distaste for what I termed a cludge is largely that we require to do a loop through our record set simply to convert the objects to their base value which may be a performance hit.</p> <p>I guess I was wondering if anyone else had come across this in their coding before, and if anyone had been cleverer, or at least more elegant, than me in dealing with it.</p>
<p>In your case MyObjectsA and MyObjectsB don't have common predecessor. Generic class is template for <em>different</em> classes not a common base class. If you want to have common properties in different classes use interfaces. You can't call <em>ToList</em> in a loop cause it has different signature in different classes. You can create ToList that returns <em>objects</em> rather than specific type.</p>
<p>Generics are used for static time type checks <strong>not</strong> runtime dispatch. Use inheritance/interfaces for runtime dispatch, use generics for compile-time type guarantees.</p> <pre><code>interface IMyObjects : IEnumerable&lt;IOtherObjects&gt; {} abstract class MyObjects&lt;T&gt; : IMyObjects where T : IOtherObjects {} IEnumerable&lt;IMyObjects&gt; objs = ...; foreach (IMyObjects mo in objs) { foreach (IOtherObjects oo in mo) { Console.WriteLine(oo); } } </code></pre> <p>(Obviously, I prefer Enumerables over Lists.)</p> <p><strong>OR</strong> Just use a proper dynamic language like VB. :-)</p>
7,682
<p>I do web site debugging with Internet&nbsp;Explorer (as well as other browsers), but my problem is with Internet&nbsp;Explorer, as it is the browser I usually use for regular browsing.</p> <p>In order to debug you need to turn on debug mode in the advanced options. OK, fine. It's turned on. But the issue I have, that is quite annoying, is that it seems 30% of websites have JavaScript errors, and Internet&nbsp;Explorer in debug mode causes a popup. This is now also the case with Stack&nbsp;Overflow as well, where I spend a lot of time now. Every time I edit I get a JavaScript error pup up.</p> <p>I guess it comes down to this: Is there a way to QUICKLY enable and disable debug mode, such as a Hokey, or an add-in, so you don't have to go into Advanced Options to enable and disable?</p> <p>I should mention I do mainly <a href="http://en.wikipedia.org/wiki/ASP.NET" rel="nofollow noreferrer">ASP.NET</a> development and use Visual Studio. I do already use Firefox/<a href="http://en.wikipedia.org/wiki/Firebug_%28software%29" rel="nofollow noreferrer">Firebug</a> for some scenarios and non Internet&nbsp;Explorer-related issues. I'm not really looking to switch around what I do or how I do it, mainly looking for a solution to the problem at hand. Even a workaround that doesn't involve using other browsers/debuggers.</p>
<p>The quickest way I can think of would be to write a small utility to:</p> <ul> <li>Close all IE windows</li> <li>Toggle the REG_SZ registry value HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Main\Disable Script Debugger (from "yes" to "no" or vice versa)</li> <li>Optionally restart IE</li> </ul> <p>As far as I know, there's no way to make IE recognize the changed registry value without restarting it, even using an IE plugin.</p> <p>As an aside, unless the IE/VS integration is critical for you, you may want to look into the combination of Firefox and <a href="http://getfirebug.com/" rel="nofollow noreferrer">Firebug</a> for Javascript debugging: I find it much nicer in general, and debugging can easily be enabled or disabled, either interactively or on a per-site basis.</p>
<p>Have a look at <a href="http://www.debugbar.com/" rel="nofollow noreferrer">debugbar</a>. It's free for personal use, and it has a 60 days trial for commercial. It works a bit like fireug for Firefox, but obviously it's going to cost to use.</p>
23,728
<p>Fun with enums in C#. Take one generic list that is created to store some Enum that you had defined previously and add few items in it. Iterate with foreach or <code>GetEnumerator&lt;T&gt;()</code> but specify some other enum then the original and see what happens. I was expecting InvalidCastException or something like that but it perfectly works :). </p> <p> For the illustration let's take a simple console application and create two enums there: Cars and Animals: </p> <pre><code> public enum Cars { Honda = 0, Toyota = 1, Chevrolet = 2 } public enum Animals { Dog = 0, Cat = 1, Tiger = 2 } </code></pre> <p>And do this in main method:</p> <pre><code> public static void Main() { List&lt;Cars&gt; cars = new List&lt;Cars&gt;(); List&lt;Animals&gt; animals = new List&lt;Animals&gt;(); cars.Add(Cars.Chevrolet); cars.Add(Cars.Honda); cars.Add(Cars.Toyota); foreach (Animals isItACar in cars) { Console.WriteLine(isItACar.ToString()); } Console.ReadLine(); } </code></pre> <p>It will print this in console:</p> <blockquote> <pre><code>Tiger Dog Cat </code></pre> </blockquote> <p>Why is this happening? My first guess was that enum is not actually a Type by himself it's just and int but that's not true: If we write:</p> <p><code>Console.WriteLine(Animals.Tiger.GetType().FullName);</code> We will get his fully qualified name printed! So why this?</p>
<p>Enum types are distinct, but you're being confused by an implicit cast which is in foreach.</p> <p>Let's rewrite your loop a bit:</p> <pre><code>public static void Main() { List&lt;Cars&gt; cars = new List&lt;Cars&gt;(); List&lt;Animals&gt; animals = new List&lt;Animals&gt;(); cars.Add(Cars.Chevrolet); cars.Add(Cars.Honda); cars.Add(Cars.Toyota); foreach (Cars value in cars) { // This time the cast is explicit. Animals isItACar = (Animals) value; Console.WriteLine(isItACar.ToString()); } Console.ReadLine(); } </code></pre> <p>Now does the result surprise you? Hopefully not, except possibly the fact that you <em>can</em> cast from one enum to another. This is just a more explicit version of what your original code is doing.</p> <p>The fact that there's a cast implicit in every <code>foreach</code> loop (even though it's usually a no-op) is the bit which most developers would find confusing, I think.</p> <p>From section 8.8.4 of the C# 3.0 spec:</p> <blockquote> <p>The above steps, if successful, unambiguously produce a collection type C, enumerator type E and element type T. A foreach statement of the form</p> </blockquote> <pre><code>foreach (V v in x) embedded-statement </code></pre> <blockquote> <p>is then expanded to: </p> </blockquote> <pre><code>{ E e = ((C)(x)).GetEnumerator(); try { V v; while (e.MoveNext()) { v = (V)(T)e.Current; embedded-statement } } finally { ... // Dispose e } } </code></pre> <p>The enumeration conversion itself is covered in section 6.2.2:</p> <blockquote> <p>The explicit enumeration conversions are:</p> </blockquote> <ul> <li>From sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or decimal to any enum-type.</li> <li>From any enum-type to sbyte, byte, short, ushort, int, uint, long, ulong, char, float, double, or decimal.</li> <li>From any enum-type to any other enum-type.</li> </ul> <blockquote> <p>An explicit enumeration conversion between two types is processed by treating any participating enum-type as the underlying type of that enum-type, and then performing an implicit or explicit numeric conversion between the resulting types. For example, given an enum-type E with and underlying type of int, a conversion from E to byte is processed as an explicit numeric conversion (§6.2.1) from int to byte, and a conversion from byte to E is processed as an implicit numeric conversion (§6.1.2) from byte to int.</p> </blockquote>
<p>You can also derive an enum from a specific type.</p> <pre><code>public enum Cats : byte { ... } public enum Dogs : int { ... } </code></pre>
45,859
<p>I need to convert a bundle of static HTML documents into a single PDF file programmatically on the server side on a Java/J2EE platform using a batch process preferably. The pdf files would be distributed to site users for offline browsing of the web pages. </p> <p>The major points of the requirements are:</p> <ol> <li>The banner at the top should not be present in the final pdf document.</li> <li>The navigation bar on the left should be transformed into pdf bookmarks from html hyperlinks.</li> <li>All hyperlinked contents (html/pdf/doc/docx etc.) present in the web pages should be part of the final pdf document with pdf bookmarks.</li> </ol> <p>Is there any standard open source way of doing this?</p>
<p>Try <a href="http://xmlgraphics.apache.org/fop/" rel="nofollow noreferrer">Apache FOP</a>. I just used it to <a href="https://stackoverflow.com/questions/212577/how-do-you-create-a-pdf-from-xml-in-java">convert XML to PDF</a> and I think you can do the same with HTML/DOM. The website has <a href="http://xmlgraphics.apache.org/fop/0.95/embedding.html" rel="nofollow noreferrer">a whole section</a> on running FOP in a Java application and there's <a href="http://xmlgraphics.apache.org/fop/0.95/embedding.html#ExampleDOM2PDF" rel="nofollow noreferrer">example code for DOM to PDF</a>.</p>
<p>You can try <a href="http://www.lowagie.com/iText" rel="nofollow noreferrer">iText</a> - but I am not sure whether it handles all that you require. </p> <p>Moreover, it is always better if you explore many options and then decide what you can and cannot do. In many cases there won't be any library/API that will out of the box support all that you ask for. </p>
29,606
<p>I'm looking for a clean C++ way to parse a string containing expressions wrapped in ${} and build a result string from the programmatically evaluated expressions.</p> <p>Example: "Hi ${user} from ${host}" will be evaluated to "Hi foo from bar" if I implement the program to let "user" evaluate to "foo", etc.</p> <p>The current approach I'm thinking of consists of a state machine that eats one character at a time from the string and evaluates the expression after reaching '}'. Any hints or other suggestions?</p> <p>Note: boost:: is most welcome! :-)</p> <p><strong>Update</strong> Thanks for the first three suggestions! Unfortunately I made the example too simple! I need to be able examine the contents within ${} so it's not a simple search and replace. Maybe it will say ${uppercase:foo} and then I have to use "foo" as a key in a hashmap and then convert it to uppercase, but I tried to avoid the inner details of ${} when writing the original question above... :-)</p>
<pre><code>#include &lt;iostream&gt; #include &lt;conio.h&gt; #include &lt;string&gt; #include &lt;map&gt; using namespace std; struct Token { enum E { Replace, Literal, Eos }; }; class ParseExp { private: enum State { State_Begin, State_Literal, State_StartRep, State_RepWord, State_EndRep }; string m_str; int m_char; unsigned int m_length; string m_lexme; Token::E m_token; State m_state; public: void Parse(const string&amp; str) { m_char = 0; m_str = str; m_length = str.size(); } Token::E NextToken() { if (m_char &gt;= m_length) m_token = Token::Eos; m_lexme = ""; m_state = State_Begin; bool stop = false; while (m_char &lt;= m_length &amp;&amp; !stop) { char ch = m_str[m_char++]; switch (m_state) { case State_Begin: if (ch == '$') { m_state = State_StartRep; m_token = Token::Replace; continue; } else { m_state = State_Literal; m_token = Token::Literal; } break; case State_StartRep: if (ch == '{') { m_state = State_RepWord; continue; } else continue; break; case State_RepWord: if (ch == '}') { stop = true; continue; } break; case State_Literal: if (ch == '$') { stop = true; m_char--; continue; } } m_lexme += ch; } return m_token; } const string&amp; Lexme() const { return m_lexme; } Token::E Token() const { return m_token; } }; string DoReplace(const string&amp; str, const map&lt;string, string&gt;&amp; dict) { ParseExp exp; exp.Parse(str); string ret = ""; while (exp.NextToken() != Token::Eos) { if (exp.Token() == Token::Literal) ret += exp.Lexme(); else { map&lt;string, string&gt;::const_iterator iter = dict.find(exp.Lexme()); if (iter != dict.end()) ret += (*iter).second; else ret += "undefined(" + exp.Lexme() + ")"; } } return ret; } int main() { map&lt;string, string&gt; words; words["hello"] = "hey"; words["test"] = "bla"; cout &lt;&lt; DoReplace("${hello} world ${test} ${undef}", words); _getch(); } </code></pre> <p>I will be happy to explain anything about this code :)</p>
<p>How many evaluation expressions do intend to have? If it's small enough, you might just want to use brute force.</p> <p>For instance, if you have a <code>std::map&lt;string, string&gt;</code> that goes from your <code>key</code> to its <code>value</code>, for instance <code>user</code> to <code>Matt Cruikshank</code>, you might just want to iterate over your entire map and do a simple replace on your string of every <code>"${" + key + "}"</code> to its <code>value</code>.</p>
32,965
<p>We're testing WYSIWYG editors, and we cannot see to make them work with asynchronous postbacks. We put the TextBox(/textarea) in the UpdatePanel and call a simple save to the DB, and all of our WYSIWYG toolbars disappear, leaving us with a bunch of HTML in textboxes.</p> <p>This is the one we've been working to implement: nicedit.com/ We have found that CuteEditor works with asynch. postbacks, but we've had so many problems with it, we're scrapping it entirely.</p> <p>Those are just two examples, but we've tried a number of others, including TinyMCE. What is causing this to mess up on the AJAX call?</p> <p><em>Edit</em> - I agree with Thomas that it has something to do with the WYSIWYG editor running javascript during the "onLoad" event. Unfortunately the UpdatePanel request kills that and doesn't re-render the WYSIWYG editors. So other people can experiment, here's another SO question that hooks into the <a href="https://stackoverflow.com/questions/338702/how-to-call-a-client-side-javascript-function-after-a-specific-updatepanel-has-be">client-side PageLoad event</a>.</p> <p><em>Edit 2</em> - Ultimately I ended up binding the WYSIWYG load/render event to the <a href="http://docs.jquery.com/Events/bind" rel="nofollow noreferrer">element's onfocus event using jQuery</a>.</p>
<p>This is mostly (independent upon your WYSIWYG control) due to two problems. Either the WYSIWG editor runs JS on the "onLoad" event (which you cannot fix easily) or your WYSIWYG editor includes JavaScript upon becoming Visible (which won't be rendered back to client in an Ajax Request without taking special actions)</p>
<p>From what I remember from TinyMCE, you need to turn off the editor before your POST.</p> <p>I've also had success with <a href="http://www.innovastudio.com/" rel="nofollow noreferrer">InnovaStudio</a>, but you have to pay for it ($59.99).</p> <p>I'm waiting for <a href="http://www.37signals.com/svn/posts/1330-introducing-wysihat-an-eventually-better-open-source-wysiwyg-editor" rel="nofollow noreferrer">WysiHat</a> myself.</p>
31,328
<p>I'm looking for some software that allows me to control a server based application, that is, there are bunch of interdependent processes that I'd like to be able to start up, shut down and monitor in a controller manner.</p> <p>I've come across programs like Autosys, but that's expensive and very much over the top for what I want. I've also seen <a href="http://appctl.sourceforge.net/" rel="nofollow noreferrer">AppCtl</a>, but that seems not to handle dependencies. Maybe it would be possible to repurpose the init scripts?</p> <p>Oh, and as an added complication it should be able to run on a Solaris 10 or Linux box without installing any new binaries. On the boxes I've seen recently, that means shell scripts and Perl but not Python.</p> <p>Do any such programs exist or do I need to dust off my copy of Programming Perl?</p>
<p>Try Supervise, which is what qmail uses to keep track of it's services/startup applications:</p> <p><a href="http://cr.yp.to/daemontools/supervise.html" rel="nofollow noreferrer">http://cr.yp.to/daemontools/supervise.html</a></p>
<p>Solaris-only as far as I know, but wouldn't Solaris 10's <a href="http://www.sun.com/bigadmin/content/selfheal/smf-quickstart.jsp" rel="nofollow noreferrer">SMF</a> do what you want?</p>
5,871
<p>Is there something similar to <code>sprintf()</code> in C#?</p> <p>I would for instance like to convert an integer to a 2-byte byte-array.</p> <p>Something like:</p> <pre><code>int number = 17; byte[] s = sprintf("%2c", number); </code></pre>
<pre><code>string s = string.Format("{0:00}", number) </code></pre> <p>The first 0 means "the first argument" (i.e. number); the 00 after the colon is the format specifier (2 numeric digits).</p> <p>However, note that .NET strings are UTF-16, so a 2-character string is 4 bytes, not 2</p> <p>(edit: question changed from <code>string</code> to <code>byte[]</code>)</p> <p>To get the bytes, use <code>Encoding</code>:</p> <pre><code>byte[] raw = Encoding.UTF8.GetBytes(s); </code></pre> <p>(obviously different encodings may give different results; UTF8 will give 2 bytes for this data)</p> <p>Actually, a shorter version of the first bit is:</p> <pre><code>string s = number.ToString("00"); </code></pre> <p>But the <code>string.Format</code> version is more flexible.</p>
<p>EDIT: I'm assuming that you want to convert the value of an integer to a byte array and not the value converted to a string first and then to a byte array (check marc's answer for the latter.)</p> <p>To convert an int to a byte array you can use:</p> <pre><code>byte[] array = BitConverter.GetBytes(17); </code></pre> <p>but that will give you an array of 4 bytes and not 2 (since an int is 32 bits.) To get an array of 2 bytes you should use:</p> <pre><code>byte[] array = BitConverter.GetBytes((short)17); </code></pre> <p>If you just want to convert the value 17 to two characters then use:</p> <pre><code>string result = string.Format("{0:00}", 17); </code></pre> <p>But as marc pointed out the result will consume 4 bytes since each character in .NET is 2 bytes (UTF-16) (including the two bytes that hold the string length it will be 6 bytes).</p>
40,345
<p>I am currently printing PLA infused with 80% copper powder. So far I mainly used it because it looks and feels really nice and post-processing is almost limitless, however recently I have thought that metal-like filaments might actually be a good idea for gears (in case I don't want to use polycarbonate or carbon fiber PLA).</p> <p>I have been researching about the material properties of copper-infused PLA and found a few studies about the &quot;strength&quot;, however, those seem to have exclusively focussed on how much weight can be suspended on a hook where it showed pretty good results. The only other info I found was an unsourced &quot;it is more brittle&quot;, however the objects I printed so far do not feel more brittle.</p> <p>Does anyone have any experience with spur gears printed from copper-infused PLA? Are there any advantages over regular PLA? Any downsides (I could imagine higher abrasiveness is not really helpful)?</p>
<p>With the right material, you could print the gear and then sinter it, resulting in actual metal gears. However, 80 % metal-filled PLA is at the lowest border to achieve this, and a lot of that technology is patented.</p> <h2>Filamet<sup>TM</sup></h2> <p>Filamet<sup>TM</sup> is a <a href="https://shop.thevirtualfoundry.com/" rel="nofollow noreferrer">Virtual Foundry</a> product that contains around <strong>80-92 %</strong> metal powder of 100-400 µm particle size, suspended in a carrier. The carrier material is supposedly PLA or at least functionally similar. The resulting filament is highly abrasive, requiring stainless steel<sup>1</sup> to print more than short sections. The high metal content also gives the material a <em>memory</em> of its spooled-up shape. This demands extra special treatment during printing to prevent snapping the filament in the shape of a pre-heater to get it spooled off properly. The same company also offers similar products for ceramics. After printing, the models are burned-out and sintered in an oven at very high temperatures. This sintering is done in a crucible filled with carbon and alumina, burning out the PLA carrier while retaining the shape. Their material-making process is <a href="https://thevirtualfoundry.com/2019/11/21/the-virtual-foundry-wins-a-patent-for-the-process-used-to-produce-its-extrudable-plastic-infused-materials/" rel="nofollow noreferrer">patented</a> <a href="https://www.freepatentsonline.com/y2018/0193912.html" rel="nofollow noreferrer">(patent itself)</a> and covers all their metal, ceramic, and glass materials.</p> <p><sub>1 - or something even more hardy, like an <a href="https://web.archive.org/web/20210707122849/http://olssonruby.com/" rel="nofollow noreferrer">Olsson Ruby</a> by <a href="https://3dverkstan.se/" rel="nofollow noreferrer">3DVerkstan</a></sub></p> <h2>MetalX<sup>TM</sup></h2> <p>The MetalX<sup>TM</sup> system by <a href="https://markforged.com/" rel="nofollow noreferrer">Markforged</a> uses a special printer and proprietary <em>Bound Powder Metal Filament</em> that contains an unknown plastic binder. A lot of this machine and surrounding peripheries are <a href="https://markforged.com/patents" rel="nofollow noreferrer">patented</a> and information spare. Among others, their <a href="https://patents.justia.com/patent/10076875" rel="nofollow noreferrer">method of creating composite filaments</a> and their <a href="https://patents.justia.com/patent/10377083" rel="nofollow noreferrer">binder material, support material &amp; sintering process</a> are only described in patents. From their advertisement I could deduce the following process: The MetalX printer prints the item with unknown print settings, resulting in a raw item containing metal and the binder. After wash-cleaning using a liquid known as Opteon<sup>TM</sup> SF79 <a href="https://www.opteon.de/-/media/files/opteon/opteon-sf79-cleaning-fluid.pdf?rev=082d2f050b3440e8b47f8dd9b58324a9" rel="nofollow noreferrer">(Datasheet)</a> to remove the specialty binder, the sintering happens in a free oven at 1300 °C, leaving behind a metal product. Free oven means here, that the printed part is not embedded in a filled crucible like with Filamet<sup>TM</sup>.</p> <hr /> <p><sub>Disclaimer: I am not affiliated with either Virtual Foundry, Markforged, 3DVerkstan, any of their products or affiliates.</sub></p>
<p>At a guess, copper really isn't that strong so you're likely to see minimal improvements, if any.</p> <p>The PLA carrier plastic is still PLA, with a low melting point.</p> <p>The copper won't &quot;fuse&quot; with the PLA, it will still be flakes of metal embedded in a tiny pocket inside of a plastic structure.</p> <p>However this is all speculation, and your best option for an answer is to print some gears and methodically test them against plain PLA, and perhaps a metal gear if you can. Try and use identical setups/bearings/pressures and times.</p> <p>Perhaps a high torque and a high-speed test, in both lubricated and unlubed, for PLA, copper-PLA, and a straight metal gear? That would be 12 tests in all and clear out all questions.</p>
2,088
<p>Say I have a method that needs to pull 8 values from a map with 100 elements in it. Which do you think would be preferable:</p> <p>Walk in a for loop from begin to end once, pulling the elements out by switching on the key?</p> <p>Or using find 8 times to get those values?</p>
<p>Walking the list will take you O(n) time to find a random element.</p> <p>Map is a balanced binary tree, so doing a find is O(log n). </p> <p>Thus doing 8 finds results in 8*log2(n) and walking the list is (n). The larger the list, the larger the gains, but in all <em>random</em> cases doing finds will be faster than doing iterations.</p> <p>In non-random cases if there is reason to thing the items you want are near each other in the tree, or near the "begining" (left side) then walking/iterating would be faster. But that seems unlikey.</p>
<p>Let's assume "find" bails when it finds the key.</p> <p>Let's further assume that you code the "switch" sensibly, and it quits checking after it finds a match. We will also assume you <em>don't</em> bother to code it to bail on the whole process once all 8 have been found (that would probably be a pain to code up).</p> <p>The "8 find" approach can expect (iow: on average) to perform 50 * 8 = 400 comparisons.</p> <p>The "switch" approach can expect (iow: on average) to perform (8 * 100) - 28 = 772 comparisons.</p> <p>So in terms of comparisons, the 8 finds approach is better. However, the number of comparisons is small enough that you'd be better off just going with the option that is easier to understand. That will probably be the 8 find approach too though.</p>
36,764
<p>I have a collection of data stored in XDocuments and DataTables, and I'd like to address both as a single unified data space with XPath queries. So, for example, "/Root/Tables/Orders/FirstName" would fetch the value of the Firstname column in every row of the DataTable named "Orders". </p> <p>Is there a way to do this without copying all of the records in the DataTable into the XDocument?</p> <p>I'm using .Net 3.5</p>
<p>I eventually figured out the answer to this myself. I discovered a class in System.Xml.LINQ called XStreamingElement that can create an XML structure on-the-fly from a LINQ expression. Here's an example of casting a DataTable into an XML-space.</p> <pre><code>Dictionary&lt;string,DataTable&gt; Tables = new Dictionary&lt;string,DataTable&gt;(); // ... populate dictionary of tables ... XElement TableRoot = new XStreamingElement("Tables", from t in Tables select new XStreamingElement(t.Key, from DataRow r in t.Value.Rows select new XStreamingElement("row", from DataColumn c in t.Value.Columns select new XElement(c.ColumnName, r[c]))))) </code></pre> <p>The result is an XElement (TableRoot) with a structure similar to the following, assuming the dictionary contains one table called "Orders" with two rows.</p> <pre><code>&lt;Tables&gt; &lt;Orders&gt; &lt;row&gt; &lt;sku&gt;12345&lt;/sku&gt; &lt;quantity&gt;2&lt;/quantity&gt; &lt;price&gt;5.95&lt;/price&gt; &lt;/row&gt; &lt;row&gt; &lt;sku&gt;54321&lt;/sku&gt; &lt;quantity&gt;3&lt;/quantity&gt; &lt;price&gt;2.95&lt;/price&gt; &lt;/row&gt; &lt;/Orders&gt; &lt;/Tables&gt; </code></pre> <p>That can be merged with a larger XElement/XDocument based hierarchy and queried with XPath.</p>
<p>You would have to merge your documents, or at lest perform the same transformations on all of your documents. You may consider moving your documents to a single DataTable, then filtering the DataTable if the XPath / XSLT is not do-able.</p>
18,086
<p>If I want to check for the null string I would do</p> <pre><code>[ -z $mystr ] </code></pre> <p>but what if I want to check whether the variable has been defined at all? Or is there no distinction in Bash scripting?</p>
<p>I think the answer you are after is implied (if not stated) by <a href="https://stackoverflow.com/users/5190/vinko-vrsalovic">Vinko</a>'s <a href="https://stackoverflow.com/a/228552/15168">answer</a>, though it is not spelled out simply. To distinguish whether VAR is set but empty or not set, you can use:</p> <pre><code>if [ -z &quot;${VAR+xxx}&quot; ]; then echo &quot;VAR is not set at all&quot;; fi if [ -z &quot;$VAR&quot; ] &amp;&amp; [ &quot;${VAR+xxx}&quot; = &quot;xxx&quot; ]; then echo &quot;VAR is set but empty&quot;; fi </code></pre> <p>You probably can combine the two tests on the second line into one with:</p> <pre><code>if [ -z &quot;$VAR&quot; -a &quot;${VAR+xxx}&quot; = &quot;xxx&quot; ]; then echo &quot;VAR is set but empty&quot;; fi </code></pre> <p>However, if you read the documentation for Autoconf, you'll find that they do not recommend combining terms with '<code>-a</code>' and do recommend using separate simple tests combined with <code>&amp;&amp;</code>. I've not encountered a system where there is a problem; that doesn't mean they didn't used to exist (but they are probably extremely rare these days, even if they weren't as rare in the distant past).</p> <p>You can find the details of these, and other related <a href="https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion" rel="nofollow noreferrer">shell parameter expansions</a>, the <a href="https://www.gnu.org/software/bash/manual/bash.html#index-_005b" rel="nofollow noreferrer"><code>test</code> or <code>[</code></a> command and <a href="https://www.gnu.org/software/bash/manual/bash.html#Bash-Conditional-Expressions" rel="nofollow noreferrer">conditional expressions</a> in the Bash manual.</p> <hr> <p>I was recently asked by email about this answer with the question:</p> <blockquote> <p>You use two tests, and I understand the second one well, but not the first one. More precisely I don't understand the need for variable expansion</p> <pre><code>if [ -z &quot;${VAR+xxx}&quot; ]; then echo &quot;VAR is not set at all&quot;; fi </code></pre> <p>Wouldn't this accomplish the same?</p> <pre><code>if [ -z &quot;${VAR}&quot; ]; then echo &quot;VAR is not set at all&quot;; fi </code></pre> </blockquote> <p>Fair question - the answer is 'No, your simpler alternative does not do the same thing'.</p> <p>Suppose I write this before your test:</p> <pre><code>VAR= </code></pre> <p>Your test will say &quot;VAR is not set at all&quot;, but mine will say (by implication because it echoes nothing) &quot;VAR is set but its value might be empty&quot;. Try this script:</p> <pre><code>( unset VAR if [ -z &quot;${VAR+xxx}&quot; ]; then echo &quot;JL:1 VAR is not set at all&quot;; fi if [ -z &quot;${VAR}&quot; ]; then echo &quot;MP:1 VAR is not set at all&quot;; fi VAR= if [ -z &quot;${VAR+xxx}&quot; ]; then echo &quot;JL:2 VAR is not set at all&quot;; fi if [ -z &quot;${VAR}&quot; ]; then echo &quot;MP:2 VAR is not set at all&quot;; fi ) </code></pre> <p>The output is:</p> <pre> JL:1 VAR is not set at all MP:1 VAR is not set at all MP:2 VAR is not set at all </pre> <p>In the second pair of tests, the variable is set, but it is set to the empty value. This is the distinction that the <code>${VAR=value}</code> and <code>${VAR:=value}</code> notations make. Ditto for <code>${VAR-value}</code> and <code>${VAR:-value}</code>, and <code>${VAR+value}</code> and <code>${VAR:+value}</code>, and so on.</p> <hr> <p>As <a href="https://stackoverflow.com/users/14731/gili">Gili</a> points out in his <a href="https://stackoverflow.com/a/20003892">answer</a>, if you run <code>bash</code> with the <code>set -o nounset</code> option, then the basic answer above fails with <code>unbound variable</code>. It is easily remedied:</p> <pre><code>if [ -z &quot;${VAR+xxx}&quot; ]; then echo &quot;VAR is not set at all&quot;; fi if [ -z &quot;${VAR-}&quot; ] &amp;&amp; [ &quot;${VAR+xxx}&quot; = &quot;xxx&quot; ]; then echo &quot;VAR is set but empty&quot;; fi </code></pre> <p>Or you could cancel the <code>set -o nounset</code> option with <code>set +u</code> (<code>set -u</code> being equivalent to <code>set -o nounset</code>).</p>
<p>Call <em><a href="https://ss64.com/bash/set.html" rel="nofollow noreferrer">set</a></em> without any arguments... it outputs all the defined variables.</p> <p>The last ones on the list would be the ones defined in your script.</p> <p>So you could pipe its output to something that could figure out what things are defined and what’s not.</p>
28,279
<p><B>This came out being incomprehensible. I will rephrase</B></p> <p>Is there an algorithm or approach that will allow sorting an array in such a way that it minimizes the differences between successive elements? </p> <pre><code>struct element { uint32 positions[8]; } </code></pre> <p>These records are order-insensitive.<br> The output file format is defined to be:</p> <pre><code>byte present; // each bit indicating whether position[i] is present uint32 position0; -- (only bits set in Present are actually written in the file). uint32 positionN; // N is the bitcount of "present" byte nextpresent; </code></pre> <p>All records are guaranteed to be unique, so a 'present' byte of 0 represents EOF. The file is parsed by updating a "current" structure with the present fields, and the result is added to the list. </p> <p>Eg: { 1, 2, 3}, { 2, 3, 2}, { 4, 2, 3}<br> Would be: 111b 1 2 3 001b 4 111b 2 3 2<br> Saving 2 numbers off the unsorted approach.</p> <p>My goal is to to minimize the output file size.</p>
<h2>Your problem</h2> <p>I think this question should really be tagged with 'compression'.</p> <p>As I understand it, you have unordered records which consist of eight 4-byte integers: 32 bytes in total. You want to store these records with a minimum file size, and have decided to use some form of <a href="http://en.wikipedia.org/wiki/Delta_encoding" rel="noreferrer">delta encoding</a> based on a <a href="http://en.wikipedia.org/wiki/Hamming_distance" rel="noreferrer">Hamming distance</a>. You're asking how to best sort your data for the compression scheme you've constructed.</p> <h2>Your assumptions</h2> <p>From what you've told us, I don't see any real reason for you to split up your 32 bytes in the way you've described (apart from the fact that word boundaries are convenient)! If you get the same data back, do you really care if it's encoded as eight lots of 4 bytes, or sixteen lots of 2 bytes, or as one huge 32-byte integer?</p> <p>Furthermore, unless there's something about the problem domain which makes your method the favourite, your best bet is probably to use a <a href="http://en.wikipedia.org/wiki/Data_compression#Lossless_data_compression" rel="noreferrer">tried-and-tested compression scheme</a>. You should be able to find code that's already written, and you'll get good performance on typical data.</p> <h2>Your question</h2> <p>Back to your original question, if you really do want to take this route. It's easy to imagine picking a starting record (I don't think it will make much difference which, but it probably makes sense to pick the 'smallest' or 'largest'), and computing the Hamming distance to all other records. You could then pick the one with the minimum distance to store next, and repeat. Obviously this is O(n^2) in the number of records. Unfortunately, <a href="http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.7.3940" rel="noreferrer">this paper</a> (which I haven't read or understood in detail) makes it look like computing the minimum Hamming distance from one string to a set of others is intrinsically hard, and doesn't have very good approximations.</p> <p>You could obviously get better complexity by sorting your records based on <a href="http://en.wikipedia.org/wiki/Hamming_weight" rel="noreferrer">Hamming weight</a> (which comes down to the population count of that 32-byte integer), which is O(n log(n)) in the number of records. Then use some difference coding on the result. But I don't think this will make a terribly good compression scheme: the integers from 0 to 7 might end up as something like:</p> <p>000, 100, 010, 001, 101, 011, 110, 111</p> <p>0, 4, 2, 1, 5, 3, 6, 7</p> <p>Which brings us back to the question I asked before: are you sure your compression scheme is better than something more standard for your particular data?</p>
<p>You're looking at a pair of subproblems, defining the difference between structures, then the sort.</p> <p>I'm not terribly clear on your description of the structure, nor on the precedence of differences, but I'll assume you can work that out and compute a difference score between two instances. For files, there are known algorithms for discussing these things, like the one used in <a href="http://en.wikipedia.org/wiki/Diff" rel="nofollow noreferrer">diff</a>.</p> <p>For your ordering, you're looking at a classic <a href="http://en.wikipedia.org/wiki/Travelling_salesman_problem" rel="nofollow noreferrer">travelling salesman problem</a>. If you're sorting a few of these things, its easy. If you are sorting a lot of them, you'll have to settle for a 'good enough' sort, unless you're ready to apply domain knowledge and many little tricks from TSP to the effort. </p>
41,338
<p>I need to test a web form that takes a file upload. The filesize in each upload will be about 10 MB. I want to test if the server can handle over 100 simultaneous uploads, and still remain responsive for the rest of the site.</p> <p>Repeated form submissions from our office will be limited by our local DSL line. The server is offsite with higher bandwidth.</p> <p>Answers based on experience would be great, but any suggestions are welcome.</p>
<p>Use the <a href="http://httpd.apache.org/docs/2.0/programs/ab.html" rel="noreferrer">ab (ApacheBench)</a> command-line tool that is bundled with Apache (I have just discovered this great little tool). Unlike cURL or wget, ApacheBench was designed for performing stress tests on web servers (any type of web server!). It generates plenty statistics too. The following command will send a HTTP POST request including the file <code>test.jpg</code> to <code>http://localhost/</code> 100 times, with up to 4 concurrent requests.</p> <pre><code>ab -n 100 -c 4 -p test.jpg http://localhost/ </code></pre> <p>It produces output like this:</p> <pre><code>Server Software: Server Hostname: localhost Server Port: 80 Document Path: / Document Length: 0 bytes Concurrency Level: 4 Time taken for tests: 0.78125 seconds Complete requests: 100 Failed requests: 0 Write errors: 0 Non-2xx responses: 100 Total transferred: 2600 bytes HTML transferred: 0 bytes Requests per second: 1280.00 [#/sec] (mean) Time per request: 3.125 [ms] (mean) Time per request: 0.781 [ms] (mean, across all concurrent requests) Transfer rate: 25.60 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 0 2.6 0 15 Processing: 0 2 5.5 0 15 Waiting: 0 1 4.8 0 15 Total: 0 2 6.0 0 15 Percentage of the requests served within a certain time (ms) 50% 0 66% 0 75% 0 80% 0 90% 15 95% 15 98% 15 99% 15 100% 15 (longest request) </code></pre>
<p>I would perhaps guide you towards using cURL and submitting just random stuff (like, read 10MB out of <code>/dev/urandom</code> and encode it into base32), through a POST-request and manually fabricate the body to be a file upload (it's not rocket science).</p> <p>Fork that script 100 times, perhaps over a few servers. Just make sure that sysadmins don't think you are doing a DDoS, or something :)</p> <p>Unfortunately, this answer remains a bit vague, but hopefully it helps you by nudging you in the right track.</p> <p><strong>Continued as per Liam's comment:</strong><br/> If the server receiving the uploads is not in the same LAN as the clients connecting to it, it would be better to get as remote nodes as possible for stress testing, if only to simulate behavior as authentic as possible. But if you don't have access to computers outside the local LAN, the local LAN is always better than nothing.</p> <p>Stress testing from inside the same hardware would be not a good idea, as you would do double load on the server: Figuring out the random data, packing it, sending it through the TCP/IP stack (although probably not over Ethernet), and <em>only then</em> can the server do its magic. If the sending part is outsourced, you get double (taken with an arbitrary sized grain of salt) performance by the receiving end.</p>
28,350
<p>I have an application which is fully unicode compatible in Delphi 2006. I had replaced all AnsiStrings with WideStrings, replaced all VCL controls with TNT controls, and changed all string functions from AnsiStrings to WideStrings. It looks like all that work was for nothing, because I'm going to have to reverse it all. Is there anyway to Trick Delphi 2009 into thinking Widestrings are in fact UnicodeStrings?</p>
<p>No, there really isn't. But you won't regret the work to truly Unicode enable your application.</p> <p>The TNT controls can easily be replaced with the regular VCL controls. You can do that pretty simply using the wizard from GExperts (<a href="http://www.gexperts.org" rel="nofollow noreferrer">http://www.gexperts.org</a>) that replaces one control type with another automatically. </p> <p>Then, you can change all your WideString declarations to regular strings. String is now an alias for UnicodeString, and so all your strings can hold Unicode data just fine. </p> <p>BTW, the author of the TNT controls, Troy Wolbrink, now vastly prefers Delphi 2009 over his own controls.</p>
<p>Main advantage of TNT Controls is only that It can work as Ansi program in Windows 9x. It is not full unicode. If you want full unicode support everywhere (such as Stringlist.LoadFromFile, Form.OnKeyPress) it's good to move to Delphi 2009.</p>
38,512
<p>Given:</p> <pre><code>DateTime.UtcNow </code></pre> <p>How do I get a string which represents the same value in an <a href="http://en.wikipedia.org/wiki/ISO_8601" rel="noreferrer">ISO 8601</a>-compliant format?</p> <p>Note that ISO 8601 defines a number of similar formats. The specific format I am looking for is:</p> <pre><code>yyyy-MM-ddTHH:mm:ssZ </code></pre>
<blockquote> <p><strong>Note to readers:</strong> Several commenters have pointed out some problems in this answer (related particularly to the first suggestion). Refer to the comments section for more information.</p> </blockquote> <pre><code>DateTime.UtcNow.ToString(&quot;yyyy-MM-ddTHH\\:mm\\:ss.fffffffzzz&quot;, CultureInfo.InvariantCulture); </code></pre> <p>Using <a href="https://learn.microsoft.com/dotnet/standard/base-types/custom-date-and-time-format-strings" rel="noreferrer">custom date-time formatting</a>, this gives you a date similar to<br /> <strong>2008-09-22T13:57:31.2311892-04:00</strong>.</p> <p>Another way is:</p> <pre><code>DateTime.UtcNow.ToString(&quot;o&quot;, CultureInfo.InvariantCulture); </code></pre> <p>which uses the standard <a href="https://learn.microsoft.com/dotnet/standard/base-types/standard-date-and-time-format-strings#Roundtrip" rel="noreferrer">&quot;round-trip&quot; style</a> (ISO 8601) to give you<br /> <strong>2008-09-22T14:01:54.9571247Z</strong>.</p> <p>To get the specified format, you can use:</p> <pre><code>DateTime.UtcNow.ToString(&quot;yyyy-MM-ddTHH:mm:ssZ&quot;, CultureInfo.InvariantCulture) </code></pre>
<p>As mentioned in other answer, <code>DateTime</code> has issues by design.</p> <h2>NodaTime</h2> <p>I suggest to use <a href="https://nodatime.org/" rel="nofollow noreferrer">NodaTime</a> to manage date/time values:</p> <ul> <li>Local time, date, datetime</li> <li>Global time</li> <li>Time with timezone</li> <li>Period</li> <li>Duration</li> </ul> <h3>Formatting</h3> <p>So, to create and format <code>ZonedDateTime</code> you can use the following code snippet:</p> <pre><code>var instant1 = Instant.FromUtc(2020, 06, 29, 10, 15, 22); var utcZonedDateTime = new ZonedDateTime(instant1, DateTimeZone.Utc); utcZonedDateTime.ToString("yyyy-MM-ddTHH:mm:ss'Z'", CultureInfo.InvariantCulture); // 2020-06-29T10:15:22Z var instant2 = Instant.FromDateTimeUtc(new DateTime(2020, 06, 29, 10, 15, 22, DateTimeKind.Utc)); var amsterdamZonedDateTime = new ZonedDateTime(instant2, DateTimeZoneProviders.Tzdb["Europe/Amsterdam"]); amsterdamZonedDateTime.ToString("yyyy-MM-ddTHH:mm:ss'Z'", CultureInfo.InvariantCulture); // 2020-06-29T12:15:22Z </code></pre> <p>For me <code>NodaTime</code> code looks quite verbose. But types are really useful. They help to handle date/time values correctly.</p> <h3>Newtonsoft.Json</h3> <blockquote> <p>To use <code>NodaTime</code> with <code>Newtonsoft.Json</code> you need to add reference to <code>NodaTime.Serialization.JsonNet</code> NuGet package and configure JSON options.</p> </blockquote> <pre><code>services .AddMvc() .AddJsonOptions(options =&gt; { var settings=options.SerializerSettings; settings.DateParseHandling = DateParseHandling.None; settings.ConfigureForNodaTime(DateTimeZoneProviders.Tzdb); }); </code></pre>
14,028
<p>Many times we find ourselves working on a problem, only to figure out the solution being created is far more complex than the problem requires. Are there controls, best practices, techniques, etc that help you control over complication in your workplace?</p>
<p>Getting someone new to look at it. </p>
<p>It is inevitable once you have been a programmer that this will happen. If you seriously have unestimated the effort or hit a problem where your solution just doesn't work then stop coding and get talking to your project manager. I always like to take the solutions with me to the meeting, problem is A, you can do x which will take 3 days or we can try y which will take 6 days. Don't make the choice yourself.</p>
11,183
<p>How does the SQL Server JDBC Trusted Connection Authentication work? (ie how does the trusted connection authenticate the logged in AD user in such a transparent and elegant fashion and how can I implement a similar authentication solution for my client-server applications in Java without a database connection or any use of the existing SQL Server solution.)</p> <p>Assumptions * Working within a Windows 2003 domain * You have access to the Windows API via JNI/JNA</p>
<p>It depends on the client. For example if you have a Web Browser, it can use the NTLM Authentication to pass the domain authentication of your current client to the server. In this case the browser like IE or FF supports this, and you web server needs the support for NTLM. For example here for Tomcat: <a href="http://jcifs.samba.org/src/docs/ntlmhttpauth.html" rel="nofollow noreferrer">http://jcifs.samba.org/src/docs/ntlmhttpauth.html</a></p> <p>There is also the SPNEGO protcol in combination with Kerberos, as explained here: <a href="http://java.sun.com/javase/6/docs/technotes/guides/security/jgss/lab/index.html" rel="nofollow noreferrer">http://java.sun.com/javase/6/docs/technotes/guides/security/jgss/lab/index.html</a></p> <p>If you have your own client, it depends on the client's framework if it is able to use the local user's security context and is able to pass it on. The page above describes this at least for a kerberos scenario.</p> <p>Greetings Bernd</p> <p>PS: I am not sure if you can pass the authentication context established with the jcifs/ntmlm solution to a backend component like SQL Server. It should work with Kerberos tickets (if configured).</p>
<p>Have you looked at <a href="https://stackoverflow.com/questions/167464/can-i-connect-to-sql-server-using-windows-authentication-from-java-ee-webapp">this question</a>? The situation seems to be similar to yours (connecting to a SQL Server database using Windows authentication).</p>
27,244
<p>When setting up a Home Directory on IIS6 properties for a web site there's an option to "Index this resource" which is checked on by default.</p> <p>Microsoft's site says: </p> <blockquote> <p>Grant this permission to allow Microsoft Indexing Service to include this folder in a full-text index of the Web site. When you grant this permission, users can perform queries on this resource.</p> </blockquote> <p>Can someone give me more information on when you would check this option on? What sort of queries would a user perform on this resource? What are the pro's and con's of having this set to on/off for a web site?</p>
<p>Windows index service continuously extracts contents from files (for which an appropriate IFilter is installed) under a specified directory and constructs an indexed catalog to facilitate efficient and rapid searching.</p> <p>When you set "Index this resource" on IIS 6 and Windows Index Service is running, the service adds the actual physical path of the website/virtual directory/directory/sub-directory to the list of directories to be indexed in the Web catalog and the service starts to index the files.</p> <p>There are various ways to interact programmatically with the Windows Index Service to search the indexed files/contents; such as OLE DB Provider, Query Helper &amp; <a href="http://msdn.microsoft.com/en-us/library/ms690384%28v=VS.85%29.aspx#_idxs_query_helper_api" rel="noreferrer">Others...</a>.</p> <p><strong>Set Option On:</strong> When</p> <ul> <li>Custom searching is to be performed through Windows Index Service</li> <li>Web Site/Directory contains files which will be searched.</li> </ul> <p><strong>Set Option Off:</strong> When</p> <ul> <li>Custom searches won't use Windows Index Service.</li> </ul> <p>Windows Index Service continuously indexs contents of sites/directories which have the option turned on and this can result in performance issues. It's recommended to turn the option off on site/s which don't use Microsoft Index Services.</p> <p><em>Note: Windows Index Service is disabled by default on Windows Server 2003.</em></p>
<p>This is for using the indexing service which used to drive the Search. I don't think anyone uses this anymore. It's pretty intensive against the HD. Check to see if the indexing service is even enabled on your server. We would disable by default.</p> <p>If you open the indexing service mmc there will be a system and a web scope. Checking this box would add the web site to the web scope. If you were writing your own search algorithm, you would write a search query against the Web scope. Since it's 2008, you will use Google.</p>
21,205
<p>I am printing small mechanical pieces in ABS:</p> <ul> <li>100 ºC bed temperature</li> <li>70 ºC Room temperature</li> <li>250 ºC nozzle temperature</li> <li>0.4 mm nozzle, at 0.15 mm per layer.</li> <li>100.8 % scale to compensate ABS dimensional innacuracy.</li> </ul> <p>The first layer is printed correctly, but later, corners warp and first 10 mm get deformed (See images).</p> <p><a href="https://i.stack.imgur.com/5QsSPm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5QsSPm.jpg" alt="enter image description here" /></a></p> <p><a href="https://i.stack.imgur.com/Nsummm.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nsummm.jpg" alt="enter image description here" /></a></p> <p>How do I solve this? Unfortunately, I cannot increase room temperature over 70 ºC</p> <p>Here is a picture while printing, we can see that the edges get warped even far over the first layer. (Sorry, the picture quality is not so good):</p> <p><a href="https://i.stack.imgur.com/dWjCG.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dWjCG.jpg" alt="enter image description here" /></a></p>
<p>The up-curling of overhangs is frequently seen when printing PLA or PETG when the just deposited layer hasn't been cooled enough. The residual heat will allow the curling as the plastic has not been fully set (above the so called glass temperature) because of insufficient part cooling.</p> <p>Knowing that ABS doesn't need much cooling (to improve the inter-layer bonding), you most probably will not require full power of the fan (depending on the cooling power of the fan). You do need a little cooling though, but not for the first (few) layer(s), so keep the fan off at the first layer. Be sure it is up to speed at the layer you require the cooling as the first few percentage of the fan is generally not enough to rotate the fan. E.g. my fans start spinning at about 20-25 %.</p>
<p>We usually stick the masking tape on the printer's bottom plate, so that the model is formed on the side of the masking tape which without glue, which looks good. When there is no masking tape, we sometimes manually adjust the height of the bottom plate to make the nozzle appress to the bottom plate when printing the first layer. At this time, the melted material can hardly flow out. The strong pressure will adhere the material tightly to the bottom plate, which can effectively solve this problem. However, this may damage the extruder motor.</p>
1,719
<p>If you have two applications residing on the same server, can you use Server.Transfer to load a page in a different AppDomain/Application?</p> <p>My guess is no, because Server.Transfer() copies HttpContext.Items, among other things. To copy this data between AppDomains, would cause threading and memory sharing concerns a in a world were thread isolation is strictly enforced. </p> <p>Thoughts?</p>
<p>Nope, it's not possible.</p> <p><code>Server.Transfer</code> and <code>Server.Execute</code> cannot be used in these scenarios.</p> <p>It does not, however, copy the <code>HttpContext.Items</code>. It's not copied. The same <code>HttpContext</code> is reused.</p>
<p>You can't use Server.Transfer() across web apps. The reason being that it actually just changes the page that the HttpHandler was going to return, rather than finishing the request and making a new one. It causes an extra trip to the browser, but Response.Redirect() is really the way to do it.</p> <p><a href="http://www.developer.com/net/asp/article.php/3299641" rel="nofollow noreferrer">Server.Transfer vs Response.Redirect</a></p>
49,641
<p>After attending a recent Alt.NET group on IoC, I got to thinking about the tools available and how they might work. <code>StructureMap</code> in particular uses both attributes and bootstrapper concepts to map requests for <code>IThing</code> to <code>ConcreteThing</code>. Attributes automatically throw up flags for me that either reflection or IL injection is going on. Does anyone know exactly how this works (for <code>StructureMap</code> or other IoC tools) and what the associated overhead might be either at run-time or compile-time?</p>
<p>I can't say much for other IoC toolkits but I use Spring.Net and have found that there is a one off initial performance penalty at startup. Once the container has been configured the application runs unaffected.</p>
<p>They major problem is that code becomes hard to understand. It might become <em>pure magical</em> if one overuse IoC. Another problem is performance. In most cases performance lost is not noticeable. But when you start creating most of your objects via IoC container, it can suddenly drop below ocean level.</p>
8,243
<p>I'm going to try something with the format of this question and I'm very open to suggestions about a better way to handle it.</p> <p>I didn't want to just dump a bunch of code in the question so I've posted the code for the class on <code>refactormycode</code>.</p> <p><strong><a href="http://www.refactormycode.com/codes/461-base-class-for-easy-class-property-handling" rel="nofollow noreferrer">base class for easy class property handling</a></strong></p> <p>My thought was that people can either post code snippets here or make changes on <code>refactormycode</code> and post links back to their refactorings. I'll make upvotes and accept an answer (assuming there's a clear "winner") based on that.</p> <p>At any rate, on to the class itself:</p> <p>I see a lot of debate about getter/setter class methods and is it better to just access simple property variables directly or should every class have explicit get/set methods defined, blah blah blah. I like the idea of having explicit methods in case you have to add more logic later. Then you don't have to modify any code that uses the class. However I hate having a million functions that look like this:</p> <pre><code>public function getFirstName() { return $this-&gt;firstName; } public function setFirstName($firstName) { return $this-&gt;firstName; } </code></pre> <p>Now I'm sure I'm not the first person to do this (I'm hoping that there's a better way of doing it that someone can suggest to me).</p> <p>Basically, the PropertyHandler class has a __call magic method. Any methods that come through __call that start with "get" or "set" are then routed to functions that set or retrieve values into an associative array. The key into the array is the name of the calling method after getting or setting. So, if the method coming into __call is "getFirstName", the array key is "FirstName".</p> <p>I liked using __call because it will automatically take care of the case where the subclass already has a "getFirstName" method defined. My impression (and I may be wrong) is that the __get &amp; __set magic methods don't do that.</p> <p>So here's an example of how it would work:</p> <pre><code>class PropTest extends PropertyHandler { public function __construct() { parent::__construct(); } } $props = new PropTest(); $props-&gt;setFirstName("Mark"); echo $props-&gt;getFirstName(); </code></pre> <p>Notice that PropTest doesn't actually have "setFirstName" or "getFirstName" methods and neither does PropertyHandler. All that's doing is manipulating array values.</p> <p>The other case would be where your subclass is already extending something else. Since you can't have true multiple inheritances in PHP, you can make your subclass have a PropertyHandler instance as a private variable. You have to add one more function but then things behave in exactly the same way.</p> <pre><code>class PropTest2 { private $props; public function __construct() { $this-&gt;props = new PropertyHandler(); } public function __call($method, $arguments) { return $this-&gt;props-&gt;__call($method, $arguments); } } $props2 = new PropTest2(); $props2-&gt;setFirstName('Mark'); echo $props2-&gt;getFirstName(); </code></pre> <p>Notice how the subclass has a __call method that just passes everything along to the PropertyHandler __call method.</p> <hr> <p>Another good argument against handling getters and setters this way is that it makes it really hard to document.</p> <p>In fact, it's basically impossible to use any sort of document generation tool since the explicit methods to be don't documented don't exist.</p> <p>I've pretty much abandoned this approach for now. It was an interesting learning exercise but I think it sacrifices too much clarity.</p>
<p>The way I do it is the following:</p> <pre><code>class test { protected $x=''; protected $y=''; function set_y ($y) { print "specific function set_y\n"; $this-&gt;y = $y; } function __call($function , $args) { print "generic function $function\n"; list ($name , $var ) = split ('_' , $function ); if ($name == 'get' &amp;&amp; isset($this-&gt;$var)) { return $this-&gt;$var; } if ($name == 'set' &amp;&amp; isset($this-&gt;$var)) { $this-&gt;$var= $args[0]; return; } trigger_error ("Fatal error: Call to undefined method test::$function()"); } } $p = new test(); $p-&gt;set_x(20); $p-&gt;set_y(30); print $p-&gt;get_x(); print $p-&gt;get_y(); $p-&gt;set_z(40); </code></pre> <p>Which will output (line breaks added for clarity)</p> <pre><code>generic function set_x specific function set_y generic function get_x 20 generic function get_y 30 generic function set_z Notice: Fatal error: Call to undefined method set_z() in [...] on line 16 </code></pre>
<p>I've always handled this issue in a similar with a __call which ends up pretty much as boiler plate code in many of my classes. However, it's compact, and uses the reflection classes to only add getters / setters for properties you have already set (won't add new ones). Simply adding the getter / setter explicitly will add more complex functionality. It expects to be </p> <p>Code looks like this:</p> <pre><code>/** * Handles default set and get calls */ public function __call($method, $params) { //did you call get or set if ( preg_match( "|^[gs]et([A-Z][\w]+)|", $method, $matches ) ) { //which var? $var = strtolower($matches[1]); $r = new ReflectionClass($this); $properties = $r-&gt;getdefaultProperties(); //if it exists if ( array_key_exists($var,$properties) ) { //set if ( 's' == $method[0] ) { $this-&gt;$var = $params[0]; } //get elseif ( 'g' == $method[0] ) { return $this-&gt;$var; } } } } </code></pre> <p>Adding this to a class where you have declared default properties like: </p> <pre><code>class MyClass { public $myvar = null; } $test = new MyClass; $test-&gt;setMyvar = "arapaho"; echo $test-&gt;getMyvar; //echos arapaho </code></pre> <p>The reflection class may add something of use to what you were proposing. Neat solution @Mark.</p>
5,207
<p>I see iframe/p3p trick is the most popular one around, but I personally don't like it because javascript + hidden fields + frame really make it look like a hack job. I've also come across a master-slave approach using web service to communicate (<a href="http://www.15seconds.com/issue/971108.htm" rel="noreferrer">http://www.15seconds.com/issue/971108.htm</a>) and it seems better because it's transparent to the user and it's robust against different browsers. </p> <p>Is there any better approaches, and what are the pros and cons of each?</p>
<p>My approach designates one domain as the 'central' domain and any others as 'satellite' domains.</p> <p>When someone clicks a 'sign in' link (or presents a persistent login cookie), the sign in form ultimately sends its data to a URL that is on the central domain, along with a hidden form element saying which domain it came from (just for convenience, so the user is redirected back afterwards).</p> <p>This page at the central domain then proceeds to set a session cookie (if the login went well) and redirect back to whatever domain the user logged in from, with a specially generated token in the URL which is unique for that session.</p> <p>The page at the satellite URL then checks that token to see if it does correspond to a token that was generated for a session, and if so, it redirects to itself without the token, and sets a local cookie. Now that satellite domain has a session cookie as well. This redirect clears the token from the URL, so that it is unlikely that the user or any crawler will record the URL containing that token (although if they did, it shouldn't matter, the token can be a single-use token).</p> <p>Now, the user has a session cookie at both the central domain and the satellite domain. But what if they visit another satellite? Well, normally, they would appear to the satellite as unauthenticated.</p> <p>However, throughout my application, whenever a user is in a valid session, all links to pages on the other satellite domains have a ?s or &amp;s appended to them. I reserve this 's' query string to mean &quot;check with the central server because we reckon this user has a session&quot;. That is, no token or session id is shown on any HTML page, only the letter 's' which cannot identify someone.</p> <p>A URL receiving such an 's' query tag will, if there is no valid session yet, do a redirect to the central domain saying &quot;can you tell me who this is?&quot; by putting something in the query string.</p> <p>When the user arrives at the central server, if they are authenticated there the central server will simply receive their session cookie. It will then send the user back to the satellite with another single use token, which the satellite will treat just as a satellite would after logging in (see above). Ie, the satellite will now set up a session cookie on that domain, and redirect to itself to remove the token from the query string.</p> <p>My solution works without script, or iframe support. It does require '?s' to be added to any cross-domain URLs where the user may not yet have a cookie at that URL. I did think of a way of getting around this: when the user first logs in, set up a chain of redirects around every single domain, setting a session cookie at each one. The only reason I haven't implemented this is that it would be complicated in that you would need to be able to have a set order that these redirects would happen in and when to stop, and would prevent you from expanding beyond 15 domains or so (too many more and you become dangerously close to the 'redirect limit' of many browsers and proxies).</p> <p><em>Follow up note: this was written 11 years ago when the web was very different - for example, XMLhttprequest was not regarded as something you could depend on, much less across domains.</em></p>
<p>What you do is on the domain receiving the variables you check the referrer address as well so you can confirm the link was from your own domain and not someone simply typing the link into the address bar. This approach works well. </p>
32,923
<p>I didn't realize until recently that Perl 5.10 had significant new features and I was wondering if anyone could give me some good resources for learning about those. I searched for them on Google and all I found was some slides and a quick overview. Some of the features (to me at least) would be nice if they had more explanation.</p> <p>Any links would be appreciated.</p> <p>-fREW</p>
<p>There's been a string of articles in <a href="http://perltraining.com.au/tips/" rel="nofollow noreferrer">Perl Tips</a> about Perl 5.10:</p> <ul> <li><a href="http://perltraining.com.au/tips/2008-02-08.html" rel="nofollow noreferrer">Regular Expressions in Perl 5.10</a></li> <li><a href="http://perltraining.com.au/tips/2008-03-03.html" rel="nofollow noreferrer">Perl 5.10: Defined-or and state</a></li> <li><a href="http://perltraining.com.au/tips/2008-03-12.html" rel="nofollow noreferrer">Switch (given and when)</a></li> <li><a href="http://perltraining.com.au/tips/2008-03-25.html" rel="nofollow noreferrer">Perl 5.10 and Hash::Util::FieldHash</a></li> <li><a href="http://perltraining.com.au/tips/2008-04-18.html" rel="nofollow noreferrer">Smart-match in Perl 5.10</a></li> </ul> <p>There are also my <em>What's new in Perl 5.10</em> slides on <a href="http://perltraining.com.au/tips/2008-04-18.html" rel="nofollow noreferrer">Perl Training Australia's presentations page</a>, but since they were written before 5.10 was released, some things may have changed slightly. I believe that rjbs' <a href="http://www.slideshare.net/rjbs/perl-510-for-people-who-arent-totally-insane/" rel="nofollow noreferrer">Perl 5.10 for people who aren't totally insane</a> now covers everything my slides used to.</p> <p>All the best,</p> <p><em>Paul</em></p> <p><em>Mandatory bias disclosure: I wrote almost all of the resources mentioned in this post,</em></p>
<p>See Ricardo Signes' slides for his excellent "Perl 5.10 For People Who Aren't Totally Insane."</p> <p><a href="http://www.slideshare.net/rjbs/perl-510-for-people-who-arent-totally-insane" rel="nofollow noreferrer">http://www.slideshare.net/rjbs/perl-510-for-people-who-arent-totally-insane</a></p>
20,345
<p>I'm looking for the equivalent of right clicking on the drive in windows and seeing the disk space used and remaining info.</p>
<p>Look for the commands <code>du</code> (disk usage) and <code>df</code> (disk free)</p>
<p>du -sm * => RULLLLLEZ</p>
28,525
<p>Where would the physical files be?</p>
<p>It depends on the OS and whether or not roaming user profiles are enabled.</p> <p>For example, on XP, with non-roaming profiles, the location is</p> <pre><code>&lt;SYSTEMDRIVE&gt;\Documents and Settings\&lt;user&gt;\Local Settings\Application Data\Microsoft\IsolatedStorage </code></pre> <p>On Vista with roaming profile storage,</p> <pre><code>&lt;SYSTEMDRIVE&gt;\Users\&lt;user&gt;\AppData\Roaming\Microsoft\IsolatedStorage </code></pre> <p>See an <a href="http://msdn.microsoft.com/en-us/library/3ak841sy.aspx" rel="noreferrer">Introduction to Isolated Storage</a> for more info.</p>
<p>When accessed/created by a system account, I found the folder here:</p> <pre><code>C:\Windows\SysWOW64\config\systemprofile\AppData\Local\IsolatedStorage </code></pre>
34,728
<p>I have a question about locking. This doesn't have to be only about record locking, but anyway.</p> <p>Let's say I'm writing a web accessible CMS. I am struggling with some ideas.</p> <p>I could, on the moment when a user opens an article for editing, flag the article as being 'in use'. so far so good.</p> <p>but when do I remove the flag? when the user saves the article? but what if the user doesn't feel like typing anymore and decides to close his browser and go to bed?</p> <p>a time-out mechanism comes to mind, but how long does it take to write an article? 10 minutes too short, 30 minutes too long..</p> <p>Maybe I am over-complicating this. I'd like to hear your thoughts on this subject.</p>
<p>Why not use timestamps? Don't actually worry about locking anything, just react to the event where the record (article) has changed.</p> <p>Basically, before you save the article, check if your version (timestamp) is the same as what is on disk. If same, then you still have latest copy so write it, if not then ... offer to merge, offer to save as new, discard it - its application specific.</p>
<p>Use rowversion for mssql 2005 and up, timestamp for mssql 2000 and below. Use the hidden xmin field for postgresql.</p> <p>Let all other users open the record. Along with saving the record, tag who saved it, and with the aid of rowversion, on catch(DbConcurrencyException) re-throw an error which indicate to other users who saved the record before they do, and request them to re-open the record to see the changes made by the user who saved the record first.</p>
20,025
<p>I am a big fan of the Lightbox2 library, and have used it in the past just not on an MVC project. In the past I remember that Lightbox2 was picky about the paths it scripts, css, and images resided in. I remember specifically have to put everything in subdirectories of the page's path, else it wouldn't work.</p> <p>In a non-MVC application that approach was fine, but now I find myself working on an MVC application and a page's URL may have nothing to do with the directory structure. So linking to Lightbox2 per the instructions of:</p> <pre><code>&lt;script type="text/javascript" src="js/prototype.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/scriptaculous.js?load=effects,builder"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="js/lightbox.js"&gt;&lt;/script&gt; </code></pre> <p>obviously does not work.</p> <p>I tried putting the absolute path to the JavaScript which gave me the effects, just without the images. I am suspecting that the JavaScript "knows" where its images are, and cannot find them.</p> <p>Has anyone had success with Lightbox2 in an MVC environment? Perhaps just success deploying Lightbox2 to a non-subdirectory?</p> <p>Thanks!</p>
<p>I believe Lightbox assumes you have a structure as follows:</p> <pre> /images prevlabel.gif nextlabel.gif loading.gif closelabel.gif /css lightbox.css lightbox.js </pre> <p>You can just open lightbox.js and find:</p> <pre><code>fileLoadingImage: 'images/loading.gif', fileBottomNavCloseImage: 'images/closelabel.gif', </code></pre> <p>And in lightbox.css find:</p> <pre><code>#prevLink:hover, #prevLink:visited:hover { background: url(../images/prevlabel.gif) left 15% no-repeat; } #nextLink:hover, #nextLink:visited:hover { background: url(../images/nextlabel.gif) right 15% no-repeat; } </code></pre> <p>And do as you please with it.</p>
<p>Which MVC framework are we talking about here? While I'm not familiar with that particular lightbox library, I'd highly recommend you figure out the proper way to reference the javascript files via an absolute path at the root of your site:</p> <pre> <code> &lt;script type="text/javascript" src="/js/prototype.js"> </code> </pre> <p>If you can figure out how to get that to work, I'll bet it will solve your problem with the images.</p> <p>Also, having copies of the same javascript files littered all over your site is a bad idea. Besides the obvious clutter problem, browsers will have to download the same files over and over again instead of reading them from cache because they're at different URLs.</p>
26,718
<p>Can you provide examples of applications today that are procedural and maintain a high level of integrity and efficiency? Are there any books, tutorials or links that provide examples of how to successfully build and maintain an imperative system? If you were to give guidance in this area, what tips would you give on how it should be structured? I ask because OOP is often presented as a natural progression of procedural programming, but I have trouble believing that is always the case.</p>
<p>Examples of successful procedural applications??</p> <p>You mean like, say, the Linux kernel? BSD kernel? Apache web server? The vast bulk of the Unix userland utilities? Applications like that?</p> <p>Of course OOP techniques have value in the organization, maintainability, and abstractions within software, but even today OOP is likely a minority subset of all the code and applications written today.</p> <p>Consider all of the Java or C# or VB code that while written in a OOP capable programming language, the only reason they're using much OOP technique at all is to interact with external libraries or systems. Meanwhile the applications themselves, while leveraging OOP frameworks, are likely quite procedural in design and implementation.</p> <p>OOP is a fine paradigm, but in truth it's not really necessary for the bulk of logic in many systems.</p>
<p>While I cant point toward any existing system directly, there are massive amounts of legacy enterprise systems written pre-OO COBOL. Many classic 4GL programs are procedural and are aimed at high integrity systems engineering. Some are well written, others not so much.</p> <p>Books include "COBOL from Micro to Mainframes", "Enterprise COBOL Programming Guide."</p> <p>Structural tips on good imperative code are similar to OO techniques: name things well, seperate your concerns, dont repeat yourself, single responsibility principle, dont leave broken windows unmended. </p> <p>In fact I'd simply suggest reading the "Pragmatic Programmer" would give most people the right idea in any paradigm. </p> <p>As far as a compelling reason for moving to OO for business oriented applications; procedural languages allow for a <a href="http://martinfowler.com/eaaCatalog/transactionScript.html" rel="nofollow noreferrer">transaction script</a> approach to domain logic, whereas OO languages allow for the <a href="http://martinfowler.com/eaaCatalog/domainModel.html" rel="nofollow noreferrer">domain model</a> approach.</p> <p>Certainly for simple exercises, there is no real need for the use of OO languages, but as soon as complexity rises, the maintainability of OO languages wins over procedural languages low overhead.</p>
32,183
<p>I'm having an unusual problem with an IE document with contentEditable set to true. Calling select() on a range that is positioned at the end of a text node that immediately precedes a block element causes the selection to be shifted to the right one character and appear where it shouldn't. I've submitted a bug to Microsoft against IE8. If you can, please vote for this issue so that it can be fixed.</p> <p><a href="https://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=390995" rel="nofollow noreferrer">https://connect.microsoft.com/IE/feedback/ViewFeedback.aspx?FeedbackID=390995</a></p> <p>I've written a test case to demonstrate the effect:</p> <pre><code>&lt;html&gt; &lt;body&gt; &lt;iframe id="editable"&gt; &lt;html&gt; &lt;body&gt; &lt;div id="test"&gt; Click to the right of this line -&amp;gt; &lt;p id="par"&gt;Block Element&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; &lt;/iframe&gt; &lt;input id="mytrigger" type="button" value="Then Click here to Save and Restore" /&gt; &lt;script type="text/javascript"&gt; window.onload = function() { var iframe = document.getElementById('editable'); var doc = iframe.contentDocument || iframe.contentWindow.document; // An IFRAME without a source points to a blank document. Here we'll // copy the content we stored in between the IFRAME tags into that // document. It's a hack to allow us to use only one HTML file for this // test. doc.body.innerHTML = iframe.textContent || iframe.innerHTML; // Marke the IFRAME as an editable document if (doc.body.contentEditable) { doc.body.contentEditable = true; } else { var mydoc = doc; doc.designMode = 'On'; } // A function to demonstrate the bug. var myhandler = function() { // Step 1 Get the current selection var selection = doc.selection || iframe.contentWindow.getSelection(); var range = selection.createRange ? selection.createRange() : selection.getRangeAt(0); // Step 2 Restore the selection if (range.select) { range.select(); } else { selection.removeAllRanges(); selection.addRange(range); doc.body.focus(); } } // Set up the button to perform the test code. var button = document.getElementById('mytrigger'); if (button.addEventListener) { button.addEventListener('click', myhandler, false); } else { button.attachEvent('onclick', myhandler); } } &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>The problem is exposed in the myhandler function. This is all that I'm doing, there is no Step 3 in between the saving and restoring the selection, and yet the cursor moves. It doesn't seem to happen unless the selection is empty (ie. I have a blinking cursor, but no text), and it only seems to happen whenever the cursor is at the end of a text node that immediately precedes a block node.</p> <p>It seems that the range is still in the correct position (if I call parentElement on the range it returns the div), but if I get a new range from the current selection, the new range is inside the paragraph tag, and that is its parentElement.</p> <p><strong>How do I work around this and consistently save and restore the selection in internet explorer?</strong></p>
<p>I've figured out a few methods for dealing with IE ranges like this.</p> <p>If all you want to do is save where the cursor is, and then restore it, you can use the pasteHTML method to insert an empty span at the current position of the cursor, and then use the moveToElementText method to put it back at that position again:</p> <pre><code>// Save position of cursor range.pasteHTML('&lt;span id="caret"&gt;&lt;/span&gt;') ... // Create new cursor and put it in the old position var caretSpan = iframe.contentWindow.document.getElementById("caret"); var selection = iframe.contentWindow.document.selection; newRange = selection.createRange(); newRange.moveToElementText(caretSpan); </code></pre> <p>Alternatively, you can count how many characters precede the current cursor position and save that number:</p> <pre><code>var selection = iframe.contentWindow.document.selection; var range = selection.createRange().duplicate(); range.moveStart('sentence', -1000000); var cursorPosition = range.text.length; </code></pre> <p>To restore the cursor, you set it to the beginning and then move it that number of characters:</p> <pre><code>var newRange = selection.createRange(); newRange.move('sentence', -1000000); newRange.move('character', cursorPosition); </code></pre> <p>Hope this helps.</p>
<p>I recently worked at a site which used Microsoft CMS with the "MSIB+ pack" of controls which included a WYSIWYG editor which ran in Internet Explorer.</p> <p>I seem to remember some comments in the editor client-side Javascript which were specifically related to this bug in IE and the Range.Select() method.</p> <p>Unfortunately, I'm not working there anymore so I can't access the Javascript files, but perhaps you may be able to get them from elsewhere?</p> <p>Good luck</p>
15,808
<p>I have an application that I have to run as Administrator.</p> <p>One small part of that application is to start other applications with Process.Start</p> <p>The started applications will also be run as administrators, but I'd rather see them run as the 'normal' user.</p> <p>How do I accomplish that?</p> <p>/johan/</p>
<p>The WinSafer API's allow a process to be launched as a limited, normal, or elevated user.</p> <p><strong>Sample Usage:</strong></p> <pre><code>CreateSaferProcess(@"calc.exe", "", SaferLevel.NormalUser); </code></pre> <p><strong>Source code:</strong></p> <pre><code>//http://odetocode.com/Blogs/scott/archive/2004/10/28/602.aspx public static void CreateSaferProcess(String fileName, String arguments, SaferLevel saferLevel) { IntPtr saferLevelHandle = IntPtr.Zero; //Create a SaferLevel handle to match what was requested if (!WinSafer.SaferCreateLevel( SaferLevelScope.User, saferLevel, SaferOpen.Open, out saferLevelHandle, IntPtr.Zero)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } try { //Generate the access token to use, based on the safer level handle. IntPtr hToken = IntPtr.Zero; if (!WinSafer.SaferComputeTokenFromLevel( saferLevelHandle, // SAFER Level handle IntPtr.Zero, // NULL is current thread token. out hToken, // Target token SaferTokenBehaviour.Default, // No flags IntPtr.Zero)) // Reserved { throw new Win32Exception(Marshal.GetLastWin32Error()); } try { //Now that we have a security token, we can lauch the process //using the standard CreateProcessAsUser API STARTUPINFO si = new STARTUPINFO(); si.cb = Marshal.SizeOf(si); si.lpDesktop = String.Empty; PROCESS_INFORMATION pi = new PROCESS_INFORMATION(); // Spin up the new process Boolean bResult = Windows.CreateProcessAsUser( hToken, fileName, arguments, IntPtr.Zero, //process attributes IntPtr.Zero, //thread attributes false, //inherit handles 0, //CREATE_NEW_CONSOLE IntPtr.Zero, //environment null, //current directory ref si, //startup info out pi); //process info if (!bResult) throw new Win32Exception(Marshal.GetLastWin32Error()); if (pi.hProcess != IntPtr.Zero) Windows.CloseHandle(pi.hProcess); if (pi.hThread != IntPtr.Zero) Windows.CloseHandle(pi.hThread); } finally { if (hToken != IntPtr.Zero) Windows.CloseHandle(hToken); } } finally { WinSafer.SaferCloseLevel(saferLevelHandle); } } </code></pre> <p><strong>P/Invoke declarations:</strong></p> <pre><code>using System; using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; namespace PInvoke { public class WinSafer { /// &lt;summary&gt; /// The SaferCreateLevel function opens a SAFER_LEVEL_HANDLE. /// &lt;/summary&gt; /// &lt;param name="scopeId"&gt;The scope of the level to be created.&lt;/param&gt; /// &lt;param name="levelId"&gt;The level of the handle to be opened.&lt;/param&gt; /// &lt;param name="openFlags"&gt;Must be SaferOpenFlags.Open&lt;/param&gt; /// &lt;param name="levelHandle"&gt;The returned SAFER_LEVEL_HANDLE. When you have finished using the handle, release it by calling the SaferCloseLevel function.&lt;/param&gt; /// &lt;param name="reserved"&gt;This parameter is reserved for future use. IntPtr.Zero&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; [DllImport("advapi32", SetLastError = true, CallingConvention = CallingConvention.StdCall)] public static extern bool SaferCreateLevel(SaferLevelScope scopeId, SaferLevel levelId, SaferOpen openFlags, out IntPtr levelHandle, IntPtr reserved); /// &lt;summary&gt; /// The SaferComputeTokenFromLevel function restricts a token using restrictions specified by a SAFER_LEVEL_HANDLE. /// &lt;/summary&gt; /// &lt;param name="levelHandle"&gt;SAFER_LEVEL_HANDLE that contains the restrictions to place on the input token. Do not pass handles with a LevelId of SAFER_LEVELID_FULLYTRUSTED or SAFER_LEVELID_DISALLOWED to this function. This is because SAFER_LEVELID_FULLYTRUSTED is unrestricted and SAFER_LEVELID_DISALLOWED does not contain a token.&lt;/param&gt; /// &lt;param name="inAccessToken"&gt;Token to be restricted. If this parameter is NULL, the token of the current thread will be used. If the current thread does not contain a token, the token of the current process is used.&lt;/param&gt; /// &lt;param name="outAccessToken"&gt;The resulting restricted token.&lt;/param&gt; /// &lt;param name="flags"&gt;Specifies the behavior of the method.&lt;/param&gt; /// &lt;param name="lpReserved"&gt;Reserved for future use. This parameter should be set to IntPtr.EmptyParam.&lt;/param&gt; /// &lt;returns&gt;&lt;/returns&gt; [DllImport("advapi32", SetLastError = true, CallingConvention = CallingConvention.StdCall)] public static extern bool SaferComputeTokenFromLevel(IntPtr levelHandle, IntPtr inAccessToken, out IntPtr outAccessToken, SaferTokenBehaviour flags, IntPtr lpReserved); /// &lt;summary&gt; /// The SaferCloseLevel function closes a SAFER_LEVEL_HANDLE that was opened by using the SaferIdentifyLevel function or the SaferCreateLevel function.&lt;/summary&gt; /// &lt;param name="levelHandle"&gt;The SAFER_LEVEL_HANDLE to be closed.&lt;/param&gt; /// &lt;returns&gt;TRUE if the function succeeds; otherwise, FALSE. For extended error information, call GetLastWin32Error.&lt;/returns&gt; [DllImport("advapi32", SetLastError = true, CallingConvention = CallingConvention.StdCall)] public static extern bool SaferCloseLevel(IntPtr levelHandle); } //class WinSafer /// &lt;summary&gt; /// Specifies the behaviour of the SaferComputeTokenFromLevel method /// &lt;/summary&gt; public enum SaferTokenBehaviour : uint { /// &lt;summary&gt;&lt;/summary&gt; Default = 0x0, /// &lt;summary&gt;If the OutAccessToken parameter is not more restrictive than the InAccessToken parameter, the OutAccessToken parameter returns NULL.&lt;/summary&gt; NullIfEqual = 0x1, /// &lt;summary&gt;&lt;/summary&gt; CompareOnly = 0x2, /// &lt;summary&gt;&lt;/summary&gt; MakeInert = 0x4, /// &lt;summary&gt;&lt;/summary&gt; WantFlags = 0x8 } /// &lt;summary&gt; /// The level of the handle to be opened. /// &lt;/summary&gt; public enum SaferLevel : uint { /// &lt;summary&gt;Software will not run, regardless of the user rights of the user.&lt;/summary&gt; Disallowed = 0, /// &lt;summary&gt;Allows programs to execute with access only to resources granted to open well-known groups, blocking access to Administrator and Power User privileges and personally granted rights.&lt;/summary&gt; Untrusted = 0x1000, /// &lt;summary&gt;Software cannot access certain resources, such as cryptographic keys and credentials, regardless of the user rights of the user.&lt;/summary&gt; Constrained = 0x10000, /// &lt;summary&gt;Allows programs to execute as a user that does not have Administrator or Power User user rights. Software can access resources accessible by normal users.&lt;/summary&gt; NormalUser = 0x20000, /// &lt;summary&gt;Software user rights are determined by the user rights of the user.&lt;/summary&gt; FullyTrusted = 0x40000 } /// &lt;summary&gt; /// The scope of the level to be created. /// &lt;/summary&gt; public enum SaferLevelScope : uint { /// &lt;summary&gt;The created level is scoped by computer.&lt;/summary&gt; Machine = 1, /// &lt;summary&gt;The created level is scoped by user.&lt;/summary&gt; User = 2 } public enum SaferOpen : uint { Open = 1 } } //namespace PInvoke </code></pre>
<p>I had the same requirement and I come to the solution to use the task scheduler service from Windows.</p> <p>So, first add <a href="https://taskscheduler.codeplex.com/" rel="nofollow">the <code>Task Scheduler Managed Wrapper</code></a> <a href="https://www.nuget.org/packages/TaskScheduler/" rel="nofollow">library to your project</a> and use this code to create a task, configure it to run as limited user (<code>td.Principal.RunLevel = TaskRunLevel.LUA;</code>), register the task, run the task and after finish, delete the task.</p> <pre><code>// Get the service on the local machine using (var ts = new TaskService()) { const string taskName = "foo"; // Create a new task definition and assign properties var td = ts.NewTask(); td.RegistrationInfo.Description = "start foo.exe as limited user"; // Create an action that will launch foo.exe, with argument bar in workingdir C:\\ td.Actions.Add(new ExecAction("C:\\foo.exe", "bar", "C:\\")); td.Settings.Priority = ProcessPriorityClass.Normal; // run with limited token td.Principal.RunLevel = TaskRunLevel.LUA; td.Settings.AllowDemandStart = true; td.Settings.DisallowStartIfOnBatteries = false; td.Settings.StopIfGoingOnBatteries = false; // Register the task in the root folder var ret = ts.RootFolder.RegisterTaskDefinition(taskName, td); var fooTask = ts.FindTask(taskName, true); if (null != fooTask ) { if (fooTask.Enabled) { fooTask.Run(); Thread.Sleep(TimeSpan.FromSeconds(1)); // find process and wait for Exit var processlist = Process.GetProcesses(); foreach(var theprocess in processlist) { if (theprocess.ProcessName != "foo") continue; theprocess.WaitForExit(); break; } } } // Remove the task we just created ts.RootFolder.DeleteTask(taskName); } </code></pre>
23,938
<p>Will IE6 negotiate a 256 bit AES SSL connection if the server is capable?</p>
<p>Sometimes there is just a plain and simple way of finding out. If you look at the internet explorer help > about internet explorer, it will tell you the max cipher bits that it supports, and on IE6 its 128.</p>
<p>The about dialog in Internet Explorer 6 on Windows XP with SP3 states cipher support as 128-bit.</p>
12,290
<p>What is the idiomatic Python equivalent of this C/C++ code?</p> <pre class="lang-cpp prettyprint-override"><code>void foo() { static int counter = 0; counter++; printf("counter is %d\n", counter); } </code></pre> <p>specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?</p>
<p>A bit reversed, but this should work:</p> <pre><code>def foo(): foo.counter += 1 print "Counter is %d" % foo.counter foo.counter = 0 </code></pre> <p>If you want the counter initialization code at the top instead of the bottom, you can create a decorator:</p> <pre><code>def static_vars(**kwargs): def decorate(func): for k in kwargs: setattr(func, k, kwargs[k]) return func return decorate </code></pre> <p>Then use the code like this:</p> <pre><code>@static_vars(counter=0) def foo(): foo.counter += 1 print "Counter is %d" % foo.counter </code></pre> <p>It'll still require you to use the <code>foo.</code> prefix, unfortunately.</p> <p><sup>(Credit: <a href="https://stackoverflow.com/questions/279561/what-is-the-python-equivalent-of-static-variables-inside-a-function/279586#comment41067162_279586">@ony</a>)</sup></p>
<p>Sure this is an old question but I think I might provide some update.</p> <p>It seems that the performance argument is obsolete. The same test suite appears to give similar results for siInt_try and isInt_re2. Of course results vary, but this is one session on my computer with python 3.4.4 on kernel 4.3.01 with Xeon W3550. I have run it several times and the results seem to be similar. I moved the global regex into function static, but the performance difference is negligible. </p> <pre><code>isInt_try: 0.3690 isInt_str: 0.3981 isInt_re: 0.5870 isInt_re2: 0.3632 </code></pre> <p>With performance issue out of the way, it seems that try/catch would produce the most future- and cornercase- proof code so maybe just wrap it in function</p>
35,339
<p>I am trying to process files one at a time that are stored over a network. Reading the files is fast due to buffering is not the issue. The problem I have is just listing the directories in a folder. I have at least 10k files per folder over many folders.</p> <p>Performance is super slow since File.list() returns an array instead of an iterable. Java goes off and collects all the names in a folder and packs it into an array before returning.</p> <p>The bug entry for this is <a href="http://bugs.sun.com/view_bug.do;jsessionid=db7fcf25bcce13541c4289edeb4?bug_id=4285834" rel="noreferrer">http://bugs.sun.com/view_bug.do;jsessionid=db7fcf25bcce13541c4289edeb4?bug_id=4285834</a> and doesn't have a work around. They just say this has been fixed for JDK7.</p> <p>A few questions:</p> <ol> <li>Does anybody have a workaround to this performance bottleneck?</li> <li>Am I trying to achieve the impossible? Is performance still going to be poor even if it just iterates over the directories?</li> <li>Could I use the beta JDK7 builds that have this functionality without having to build my entire project on it?</li> </ol>
<p>Although it's not pretty, I solved this kind of problem once by piping the output of dir/ls to a file before starting my app, and passing in the filename.</p> <p>If you needed to do it within the app, you could just use system.exec(), but it would create some nastiness.</p> <p>You asked. The first form is going to be blazingly fast, the second should be pretty fast as well.</p> <p>Be sure to do the one item per line (bare, no decoration, no graphics), full path and recurse options of your selected command.</p> <p>EDIT: </p> <p>30 minutes just to get a directory listing, wow.</p> <p>It just struck me that if you use exec(), you can get it's stdout redirected into a pipe instead of writing it to a file.</p> <p>If you did that, you should start getting the files immediately and be able to begin processing before the command has completed.</p> <p>The interaction may actually slow things down, but maybe not--you might give it a try.</p> <p>Wow, I just went to find the syntax of the .exec command for you and came across this, possibly exactly what you want (it lists a directory using exec and "ls" and pipes the result into your program for processing): <a href="http://web.archive.org/web/20080912133319/http://java.sun.com/developer/JDCTechTips/2003/tt0304.html" rel="nofollow noreferrer">good link in wayback</a> (Jörg provided in a comment to replace <a href="http://java.sun.com/developer/JDCTechTips/2003/tt0304.html" rel="nofollow noreferrer" title="this broken link here">this one</a> from sun that Oracle broke)</p> <p>Anyway, the idea is straightforward but getting the code right is annoying. I'll go steal some codes from the internets and hack them up--brb</p> <pre> /** * Note: Only use this as a last resort! It's specific to windows and even * at that it's not a good solution, but it should be fast. * * to use it, extend FileProcessor and call processFiles("...") with a list * of options if you want them like /s... I highly recommend /b * * override processFile and it will be called once for each line of output. */ import java.io.*; public abstract class FileProcessor { public void processFiles(String dirOptions) { Process theProcess = null; BufferedReader inStream = null; // call the Hello class try { theProcess = Runtime.getRuntime().exec("cmd /c dir " + dirOptions); } catch(IOException e) { System.err.println("Error on exec() method"); e.printStackTrace(); } // read from the called program's standard output stream try { inStream = new BufferedReader( new InputStreamReader( theProcess.getInputStream() )); processFile(inStream.readLine()); } catch(IOException e) { System.err.println("Error on inStream.readLine()"); e.printStackTrace(); } } // end method /** Override this method--it will be called once for each file */ public abstract void processFile(String filename); } // end class </pre> <p>And thank you code donor at <a href="http://publib.boulder.ibm.com/infocenter/iseries/v5r3/index.jsp?topic=/rzaha/jvlngex1.htm" rel="nofollow noreferrer" title="IBM">IBM</a></p>
<p>I wonder why there are 10k files in a directory. Some file systems do not work well with so many files. There are specifics limitations for file systems like max amount of files per directory and max amount of levels of subdirectory.</p> <p>I solve a similar problem with an iterator solution. </p> <p>I needed to walk across huge directorys and several levels of directory tree recursively.</p> <p>I try FileUtils.iterateFiles() of Apache commons io. But it implement the iterator by adding all the files in a List and then returning List.iterator(). It's very bad for memory.</p> <p>So I prefer to write something like this:</p> <pre><code>private static class SequentialIterator implements Iterator&lt;File&gt; { private DirectoryStack dir = null; private File current = null; private long limit; private FileFilter filter = null; public SequentialIterator(String path, long limit, FileFilter ff) { current = new File(path); this.limit = limit; filter = ff; dir = DirectoryStack.getNewStack(current); } public boolean hasNext() { while(walkOver()); return isMore &amp;&amp; (limit &gt; count || limit &lt; 0) &amp;&amp; dir.getCurrent() != null; } private long count = 0; public File next() { File aux = dir.getCurrent(); dir.advancePostition(); count++; return aux; } private boolean walkOver() { if (dir.isOutOfDirListRange()) { if (dir.isCantGoParent()) { isMore = false; return false; } else { dir.goToParent(); dir.advancePostition(); return true; } } else { if (dir.isCurrentDirectory()) { if (dir.isDirectoryEmpty()) { dir.advancePostition(); } else { dir.goIntoDir(); } return true; } else { if (filter.accept(dir.getCurrent())) { return false; } else { dir.advancePostition(); return true; } } } } private boolean isMore = true; public void remove() { throw new UnsupportedOperationException(); } } </code></pre> <p>Note that the iterator stop by an amount of files iterateds and it has a FileFilter also.</p> <p>And DirectoryStack is:</p> <pre><code>public class DirectoryStack { private class Element{ private File files[] = null; private int currentPointer; public Element(File current) { currentPointer = 0; if (current.exists()) { if(current.isDirectory()){ files = current.listFiles(); Set&lt;File&gt; set = new TreeSet&lt;File&gt;(); for (int i = 0; i &lt; files.length; i++) { File file = files[i]; set.add(file); } set.toArray(files); }else{ throw new IllegalArgumentException("File current must be directory"); } } else { throw new IllegalArgumentException("File current not exist"); } } public String toString(){ return "current="+getCurrent().toString(); } public int getCurrentPointer() { return currentPointer; } public void setCurrentPointer(int currentPointer) { this.currentPointer = currentPointer; } public File[] getFiles() { return files; } public File getCurrent(){ File ret = null; try{ ret = getFiles()[getCurrentPointer()]; }catch (Exception e){ } return ret; } public boolean isDirectoryEmpty(){ return !(getFiles().length&gt;0); } public Element advancePointer(){ setCurrentPointer(getCurrentPointer()+1); return this; } } private DirectoryStack(File first){ getStack().push(new Element(first)); } public static DirectoryStack getNewStack(File first){ return new DirectoryStack(first); } public String toString(){ String ret = "stack:\n"; int i = 0; for (Element elem : stack) { ret += "nivel " + i++ + elem.toString()+"\n"; } return ret; } private Stack&lt;Element&gt; stack=null; private Stack&lt;Element&gt; getStack(){ if(stack==null){ stack = new Stack&lt;Element&gt;(); } return stack; } public File getCurrent(){ return getStack().peek().getCurrent(); } public boolean isDirectoryEmpty(){ return getStack().peek().isDirectoryEmpty(); } public DirectoryStack downLevel(){ getStack().pop(); return this; } public DirectoryStack goToParent(){ return downLevel(); } public DirectoryStack goIntoDir(){ return upLevel(); } public DirectoryStack upLevel(){ if(isCurrentNotNull()) getStack().push(new Element(getCurrent())); return this; } public DirectoryStack advancePostition(){ getStack().peek().advancePointer(); return this; } public File[] peekDirectory(){ return getStack().peek().getFiles(); } public boolean isLastFileOfDirectory(){ return getStack().peek().getFiles().length &lt;= getStack().peek().getCurrentPointer(); } public boolean gotMoreLevels() { return getStack().size()&gt;0; } public boolean gotMoreInCurrentLevel() { return getStack().peek().getFiles().length &gt; getStack().peek().getCurrentPointer()+1; } public boolean isRoot() { return !(getStack().size()&gt;1); } public boolean isCurrentNotNull() { if(!getStack().isEmpty()){ int currentPointer = getStack().peek().getCurrentPointer(); int maxFiles = getStack().peek().getFiles().length; return currentPointer &lt; maxFiles; }else{ return false; } } public boolean isCurrentDirectory() { return getStack().peek().getCurrent().isDirectory(); } public boolean isLastFromDirList() { return getStack().peek().getCurrentPointer() == (getStack().peek().getFiles().length-1); } public boolean isCantGoParent() { return !(getStack().size()&gt;1); } public boolean isOutOfDirListRange() { return getStack().peek().getFiles().length &lt;= getStack().peek().getCurrentPointer(); } } </code></pre>
46,213
<p>I have a SharePoint site that is locked down through standard Windows permissions.</p> <p>I keep getting an repeated login box prompt, and it appears that it has to do with the Themes images and the CSS style sheets.</p> <p><a href="https://i.stack.imgur.com/dXRS0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dXRS0.png" alt="alt text"></a><br> <sub>(source: <a href="http://www.oscommerce-ssl.com/OGS_Authorization_Issues.png" rel="nofollow noreferrer">oscommerce-ssl.com</a>)</sub> </p> <p>Where do I need to update permissions so that these files have the same permissions as the rest of the site and the user only needs to login once?</p> <p>Thanks.</p>
<p>Using <a href="http://www.fiddler2.com/fiddler2/" rel="nofollow noreferrer">Fiddler</a> which is a web inspection tool, you can actually determine which <em>domains</em> the rejected requests are attempting to access. As <a href="https://stackoverflow.com/questions/375498/sharepoint-permissions-repeated-login-boxes/395005#395005">Kinjal</a> mentioned, it is possible that some of the images, css, or javascript requests are attempting to access through the ip, and not through the domain name. </p> <p><a href="https://stackoverflow.com/questions/375498/sharepoint-permissions-repeated-login-boxes/382123#382123">MacGyver's</a> option is possible, although that merely masks the problem, in that the multiple domains (or ways of accessing the same domain) are still being requested, but you are hiding it by caching the credentials that are to be used. This solution is also inadvisable if you are the one who is developing the solution, or administrating the farm, as you (usually) cannot possibly apply this hotfix to <em>all</em> the machines in your network.</p> <p>The permissions possibility (as <a href="https://stackoverflow.com/questions/375498/sharepoint-permissions-repeated-login-boxes/393998#393998">Øyvind</a> points out) should also be verified, by checking which files are being rejected, and then verifying that the App Pool user has access to each of those locations. </p>
<p>If your running Windows XP the following should solve your problem.</p> <p>Try setting your network passwords using Stored User Names and Passwords app.</p> <p><a href="http://support.microsoft.com/kb/306992" rel="nofollow noreferrer">http://support.microsoft.com/kb/306992</a></p>
49,140
<p>I would like to make a 24&nbsp;V (3D printer board and shield) setup, as opposed to the usual 12&nbsp;V, and to do so I had been considering using the Taurino Power board, or the clone Eruduino. However, I just found this board:</p> <p><a href="https://i.stack.imgur.com/FoUYh.jpg" rel="nofollow noreferrer" title="Re-ARM microcontroller, with SD card slot"><img src="https://i.stack.imgur.com/FoUYh.jpg" alt="Re-ARM microcontroller, with SD card slot" title="Re-ARM microcontroller, with SD card slot"></a></p> <p>The specifications state a DC input of up to 36&nbsp;V:</p> <p><a href="https://i.stack.imgur.com/UX1QF.png" rel="nofollow noreferrer" title="Specifications"><img src="https://i.stack.imgur.com/UX1QF.png" alt="Specifications" title="Specifications"></a></p> <p>Does anyone know whether that <em>really</em> means it can handle 24&nbsp;V in the same manner as the Taurino/Eruduino? If so, then that looks like a double win: not only 24&nbsp;V support, but also a faster processor. Anyone have experience with this board?</p> <p>I was thinking of using with a RAMPS1.6 Plus (maybe), or just a regular RAMPS 1.4 (<a href="https://reprap.org/wiki/RAMPS_24v" rel="nofollow noreferrer">hacked to support 24&nbsp;V</a>). I'm just shopping about, and I thought that if I was going to spend £14 on an Eruduino, then I just as well spend that money on something better.</p> <p>It does work with Marlin apparently, as some of the customer reviews would suggest, but none of the reviews that I could find referred to a 24&nbsp;V setup (heated bed etc.), hence my question.</p>
<p>Given that the capacitor near the input is quite clearly marked 35&nbsp;V, a 36&nbsp;V rating seems questionable.</p> <p>The (buck) regulator used on the (genuine version of the) board is the <a href="http://www.aosmd.com/res/data_sheets/AOZ1282CI.pdf" rel="nofollow noreferrer">AOZ1282CI</a> which supports up to 36&nbsp;V input. This is probably where they got the 36&nbsp;V rating from, but obviously the 35&nbsp;V-rated capacitors drop the input voltage down below this.</p> <p><a href="https://reprap.org/mediawiki/images/f/fa/Re_ARM_Schematic.pdf" rel="nofollow noreferrer">Schematics for the board are available on the RepRap wiki</a> and show that the input voltage only feeds into the regulator. I see no reason why this board couldn't handle 24&nbsp;V input, as this is well within the rating of both the regulator and the capacitors.</p>
<p>For completion, I've just seen this, <a href="https://www.reddit.com/r/3Dprinting/comments/9wfrmk/can_a_ramps_16_support_24v/" rel="nofollow noreferrer">Can a ramps 1.6 support 24v?</a> (which basically confirms the 24&nbsp;V support of the Re-ARM board) although it isn't particularly useful w.r.t. the RAMPS 1.6 side of things, although I would imagine the the <a href="https://reprap.org/wiki/RAMPS_24v" rel="nofollow noreferrer">24&nbsp;V RAMPS hack</a> would still apply.</p> <p>In addition, Alex Kenis does a great review, and he has successfully tried it with 24&nbsp;V, watch <a href="https://www.youtube.com/watch?v=P-wekOqM5gY" rel="nofollow noreferrer">32-bit series part 4: Re-ARM board "review?"</a>. Whilst the RE-ARm offers a lot of advantages, some of the main down points to be aware of are:</p> <ul> <li>No 5&nbsp;V <em>analogue inputs</em>, they are 3.3&nbsp;V, so the endstops use 3V3 logic (not a problem from mechanical switches, but 5&nbsp;V optical endstops will have a problem</li> <li>Some of the pins of the Mega are missing from the Re-ARM.</li> </ul>
1,412
<p>Now that the G1 with Google's Android OS is now available (soon), will the android platform ever support .Net?</p>
<p><strong>Update</strong>: Since I wrote this answer two years ago, we productized Mono to run on Android. The work included a few steps: porting Mono to Android, integrating it with Visual Studio, building plugins for MonoDevelop on Mac and Windows and exposing the Java Android APIs to .NET languages. This is now available at <a href="http://monodroid.net" rel="nofollow noreferrer">http://monodroid.net</a></p> <ul> <li>Getting Started: <a href="http://monodroid.net/Welcome" rel="nofollow noreferrer">http://monodroid.net/Welcome</a></li> <li>Documentation: <a href="http://monodroid.net/Documentation" rel="nofollow noreferrer">http://monodroid.net/Documentation</a></li> <li>Tutorials: <a href="http://monodroid.net/Tutorials" rel="nofollow noreferrer">http://monodroid.net/Tutorials</a></li> </ul> <p>Mono on Android is based on the Mono 2.10 runtime, and defaults to 4.0 profile with the C# 4.0 compiler and uses Mono's new SGen garbage collection engine, as well as our new distributed garbage collection system that performs GC across Java and Mono.</p> <hr> <p>The links below reflect Mono on Android as of January of 2009, I have kept them for historical context</p> <p>Mono now works on Android thanks to the work of Koushik Dutta and Marc Crichton.</p> <p>You can see a video of it running here: <a href="http://www.koushikdutta.com/2009/01/mono-on-android-with-gratuitous-shaky.html" rel="nofollow noreferrer">http://www.koushikdutta.com/2009/01/mono-on-android-with-gratuitous-shaky.html</a></p> <p>And you can get the instructions to build Mono yourself here: <a href="http://www.koushikdutta.com/2009/01/building-mono-for-android.html" rel="nofollow noreferrer">http://www.koushikdutta.com/2009/01/building-mono-for-android.html</a></p> <p>You can get a benchmark comparing Mono's JIT vs Dalvik's interpreter here: <a href="http://www.koushikdutta.com/2009/01/dalvik-vs-mono.html" rel="nofollow noreferrer">http://www.koushikdutta.com/2009/01/dalvik-vs-mono.html</a></p> <p>And of course, you can get a pre-configured image with Mono here (go to the bottom of the post for details on using that): <a href="http://www.koushikdutta.com/2009/01/building-mono-for-android.html" rel="nofollow noreferrer">http://www.koushikdutta.com/2009/01/building-mono-for-android.html</a></p>
<p>.NET for Android seems like a real possibility to me. There is news that Microsoft will release proper Silverlight for Android- Never underestimate the advantages to Microsoft for putting the boot into Apple. A smartphone that is faster, more feature rich, faster development lifecycle, impressive hardware, Flash &amp; Silverlight as a standard installable. </p> <p>Microsoft has a vested interest in improving Android, and at the same time, applications will be devloped for Silverlight on Android will also work on Windows Phone 7 OS with multi-touch, GPS, etc., etc.</p>
26,379
<p>What does <code>STRAIGHT_JOIN</code> do in this code ?</p> <pre><code>SELECT STRAIGHT_JOIN ClosingBalance FROM Accounts WHERE idAccounts = FidDebit; </code></pre>
<p>STRAIGHT_JOIN is intended as an instruction to the MySQL query optimiser that the tables must be joined from left to right in the order they are listed in the query.</p> <p><a href="http://dev.mysql.com/doc/refman/5.0/en/join.html" rel="noreferrer">http://dev.mysql.com/doc/refman/5.0/en/join.html</a></p> <p>As you only have one table in this query, it wouldn't appear to be doing anything.</p>
<p>From <a href="http://dev.mysql.com/doc/refman/5.0/en/join.html" rel="nofollow noreferrer">here</a>:</p> <blockquote> <p>STRAIGHT_JOIN is similar to JOIN, except that the left table is always read before the right table. This can be used for those (few) cases for which the join optimizer puts the tables in the wrong order.</p> </blockquote>
40,454
<p>So the controller context depends on some asp.net internals. What are some ways to cleanly mock these up for unit tests? Seems like its very easy to clog up tests with tons of setup when I only need, for example, Request.HttpMethod to return "GET".</p> <p>I've seen some examples/helpers out on the nets, but some are dated. Figured this would be a good place to keep the latest and greatest.</p> <p>I'm using latest version of rhino mocks</p>
<p>Using MoQ it looks something like this:</p> <pre><code>var request = new Mock&lt;HttpRequestBase&gt;(); request.Expect(r =&gt; r.HttpMethod).Returns("GET"); var mockHttpContext = new Mock&lt;HttpContextBase&gt;(); mockHttpContext.Expect(c =&gt; c.Request).Returns(request.Object); var controllerContext = new ControllerContext(mockHttpContext.Object , new RouteData(), new Mock&lt;ControllerBase&gt;().Object); </code></pre> <p>I think the Rhino Mocks syntax is similar.</p>
<p>I find that long mocking procedure to be too much friction.</p> <p>The best way we have found - using ASP.NET MVC on a real project - is to abstract the HttpContext to an IWebContext interface that simply passes through. Then you can mock the IWebContext with no pain.</p> <p>Here is an <a href="http://code.google.com/p/tarantino/source/browse/trunk/src/Tarantino.Core/Commons/Services/Web/IWebContext.cs" rel="nofollow noreferrer">example</a></p>
5,261
<p>I have run into a bit of a tricky problem in some C++ code, which is most easily described using code. I have classes that are something like:</p> <pre><code>class MyVarBase { } class MyVar : public MyVarBase { int Foo(); } class MyBase { public: MyBase(MyVarBase* v) : m_var(v) {} virtual MyVarBase* GetVar() { return m_var; } private: MyVarBase* m_var; } </code></pre> <p>I also have a subclass of MyBase that needs to have a member of type MyVar because it needs to call Foo. Moving the Foo function into MyVarBase is not an option. Does it make sense to do this:</p> <pre><code>class MyClass : public MyBase { public: MyClass(MyVar* v) : MyBase(v), m_var(v) {} MyVar* GetVar() { return m_var; } private: MyVar* m_var; } </code></pre> <p>This seems to work but looks really bad and I'm not sure if it's going to cause a memory leak or break a copy constructor. My other options might be to name the MyVar variable in MyClass something else but have it be equal to the m_var pointer in the base, or to templatise MyBase on the MyVar type. </p> <p>All these options don't seem ideal so I wanted to know if anyone else has run into a situation like this and if there is a good way to make it work.</p>
<p>The correct way to do this is to have the variable only in the base class. As the derived class knows it must be of dynamic type <code>MyVar</code>, this is totally reasonable:</p> <pre><code>class MyClass : public MyBase { public: MyClass(MyVar* v) : MyBase(v) {} MyVar* GetVar() { return static_cast&lt;MyVar*&gt;(MyBase::GetVar()); } } </code></pre> <p>Since MyVar is derived from MyVarBase, the different return-types of <code>GetVar</code> would still work if GetVar was virtual (as is the case here). Note that with that method, there must be no function in <code>MyBase</code> that can reset the pointer to something different, obviously. </p> <p>Note that <code>static_cast</code> is the right cast in that case. Using <code>dynamic_cast</code>, as proposed by one commenter, will tell the readers and users of GetVar that <code>MyBase::GetVar()</code> could return a pointer to an object not of type MyVar. But that doesn't reflect our intention, as you only ever pass MyVar. To be consequent is the most important thing in software development. What you <em>could</em> do is to assert it is non-null. It will abort at runtime with an error-message in debug-builds of your project:</p> <pre><code>MyVar* GetVar() { assert(dynamic_cast&lt;MyVar*&gt;(MyBase::GetVar()) != 0); return static_cast&lt;MyVar*&gt;(MyBase::GetVar()); } </code></pre>
<p>I think your mention of templates may be a good option, so something like:</p> <pre><code>class MyVarBase { }; class MyVar : public MyVarBase { int Foo(); }; template &lt;class T&gt; class MyBase { public: MyBase(T* v) : m_var(v) {} T* GetVar() { return m_var; } private: T* m_var; }; class MyClass : public MyBase&lt;MyVar&gt; { public: MyClass(MyVar* v) : MyBase(v) {} }; </code></pre> <p>However this would depend on what classes you can actually change. Also, the 'MyClass' definition could be redundant, unless it has other members over and above the MyBase class.</p>
38,230
<p>XML, granted, is very useful, but can be quite verbose. What alternatives are there and are they specialised for any particular purpose? Library support to interrogate the contents easily is a big plus point.</p>
<p>There seems to be a lot of multi-platform support for <a href="http://www.json.org/" rel="noreferrer">JSON</a>.</p>
<p>If you're asking in the perspective of a DSL, <a href="http://www.gnu.org/software/guile/guile.html" rel="nofollow noreferrer">Guile Scheme</a> could help, as already suggested with the S-expressions.</p> <p>Personally I also use JSON for AJAX transactions.</p>
6,592
<p>We're currently in the process of setting up a source control/build/and more-server for .NET development and we're thinking about either utilizing the Team Foundation Server (which costs a lot of dough) or combining several open source options, such as SourceForge Enterprise/GForge and Subversion and CruiseControl.net and so on. Has anyone walked down the full blown OSS road or is it TFS only if you want to get it right and get to work soon?</p>
<p>My work is currently using a mostly OSS build process with Cruise Control as the engine and it is great. I would suggest that if you don't know why you would need TFS, it's probably not worth the cost.</p> <p>The thing you have to keep in mind with the OSS stuff is that the software has either been in use by the Java crew for years previously, or the software is a port of similar Java code. It is robust and is suitable for purpose.</p> <p>Microsoft cannot ship OSS code, which is why they have to re-implement a lot of Open Source stuff. So, no, it is not necessary, and there have been millions of projects shipped on that stack. The flip side is that there is also a lot of nice features that you get with TFS that you won't (easily) get with the OSS stack, such as integration with your bug/feature tracking software.</p>
<p>I've seen both in action (though I'm a Java developer). The upsides from a pick and mix approach is that you can choose the best bits for everything (e.g. I'd check out Hudson for CI - its excellent for Java, works for .Net too and has <em>loads</em> of plugins and is really simple to use). The downside is that you have to do all the integration yourself. However, this is getting a <em>lot</em> easier in the Java world. Also, don;t let folks tell you a supported product is better. On many OSS products in this space the quality is excellent and you get <em>better</em> support from the cimmunity rather than waiting for an answer from your vendor's support contract (IBM, I'm looking at you)</p> <p>Hope this helps.</p>
8,729
<p>Every time I have to build a form with a <code>DateTime</code> field I try to find a decent free custom control - I always fail.</p> <p>I cannot figure out why it isn't built in the .NET but let's forget about for a minute and concentrate on my question :D</p> <p>Anyone got one?</p>
<p>Just combine these two</p> <p><a href="http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/" rel="nofollow noreferrer">http://www.kelvinluck.com/assets/jquery/datePicker/v2/demo/</a></p> <p><a href="http://keith-wood.name/timeEntry.html" rel="nofollow noreferrer">http://keith-wood.name/timeEntry.html</a></p> <p>jQuery is where it's at!</p>
<p>I just did a quick Google and came across this one...</p> <p><a href="http://www.softcomplex.com/products/tigra_calendar/demo1.html" rel="nofollow noreferrer">http://www.softcomplex.com/products/tigra_calendar/demo1.html</a></p> <p>Looks like it supports dates and times, and it appears to be free.</p>
36,584
<p>Scanner can only get input from system console? not be able to get from any dialog window?</p> <p>Thanks.</p>
<p>A <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/Scanner.html" rel="nofollow noreferrer">Scanner</a> can read text from any object which implements the <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Readable.html" rel="nofollow noreferrer">Readable</a> interface. </p> <p>That includes <code>BufferedReader</code>, <code>CharArrayReader</code>, <code>CharBuffer</code>, <code>FileReader</code>, <code>FilterReader</code>, <code>InputStreamReader</code>, <code>LineNumberReader</code>, <code>PipedReader</code>, <code>PushbackReader</code>, and <code>StringReader</code> (from the <code>Readable</code> javadoc). Unfortunately, that does not include any dialog windows.</p> <p>The easiest way to hook a dialog window to a <code>Scanner</code> would probably be to build a <code>Scanner</code> using the constructor that takes a <code>String</code>, passing the user input from the dialog directly to the <code>Scanner</code>.</p>
<p>Well, I tried with the example given at <a href="https://stackoverflow.com/questions/277143/best-way-to-determine-the-total-number-of-words-of-a-file-in-java#277190" title="Scanner example">Best way to determine the total number of words of a file in Java?</a>: just replace <code>new File("my-text-file.txt")</code> with a String variable, and it works...</p> <p>So if you get the textual content of the component into a String, you can use Scanner.</p>
34,937
<p>It's not uncommon for me to record a patch, pull it into my staging branch and then realize I've done something small and silly like a typo in a logging message, or something similarly trivial which doesn't require (to my mind) a whole new patch.</p> <p>In these instances, I've been using:</p> <pre><code>darcs amend-record </code></pre> <p>To update the patch. But when I re-pull darcs will treat the patches as conflicting, so I end up having to unrecord and revert the patch in the staging branch, and then pull it again.</p> <p>Is there a darcs command or option that will allow me to more simply pull an amended patch?</p>
<p>You could try first running darcs unpull on the staging branch then pulling in the amended patch.</p>
<p>You could try first running darcs unpull on the staging branch then pulling in the amended patch.</p>
43,409
<p>I'm looking for an implementation of the <a href="http://en.wikipedia.org/wiki/Logo_programming_language" rel="nofollow noreferrer">LOGO</a> programming language that supports 'dynaturtles' - animated turtles that can programmatically change shape, speed and direction as well as detect collisions with each other or other objects in the environment.</p> <p>Back in the mists of time when the earth was new and 8 bit micros ruled supreme, <a href="http://en.wikipedia.org/wiki/Atari_LOGO" rel="nofollow noreferrer">Atari LOGO</a> did this famously well. One could create all sorts of small games and simulated environments using this technique very easily as that implementation of the language had a very well thought out, elegant syntax.</p> <p>I know about LCSI's <a href="http://www.microworlds.com/" rel="nofollow noreferrer">Microworlds</a> but I'm looking for something I can use to get some friends and their kids involved in programming without breaking my budget.</p>
<p>Digging around a bit online, I've found <a href="http://education.mit.edu/openstarlogo/" rel="nofollow noreferrer">OpenStarLogo</a>. Though they don't specifically mention "dynaturtles" the docs do mention collision detection. The site has code and documentation downloads.</p> <p>From this <a href="http://en.wikipedia.org/wiki/Logo_(programming_language)" rel="nofollow noreferrer">wikipedia article</a>, under the Implementations section, there is a PDF listing known current and antique implementations. Some of these, such as <a href="http://education.mit.edu/drupal/starlogo-tng" rel="nofollow noreferrer">StarLogo TNG</a> and <a href="http://www.elica.net/site/index.html" rel="nofollow noreferrer">Elica</a> have support for 3D objects. These are definitely not like the LOGO programs I wrote as a kid...</p>
<p>Check out the turtle python package. It is in the standard python distribution and it supports a graphical turtle interface.</p>
38,342
<p>I use the right button>Refactor>Encapsultate field to have my accessor every time. The problem is when I create new class, I can have more than 10 attributes and it's long to do 1 by 1 every accessor. Is there a faster way to create them?</p> <p>Thank you for your time.</p>
<p>If you create a new class, you can use code snippets to create encapsulated fields instead of first creating field and then encapsulating it. In C#, the shortcuts are prop and propg (for private set).</p>
<p>Looks like the refactoring built into studio only supports a single field at a time for the Encapsulate Field refactoring. Refactor Pro! (<a href="http://www.devexpress.com/Products/Visual_Studio_Add-in/Refactoring/" rel="nofollow noreferrer">http://www.devexpress.com/Products/Visual_Studio_Add-in/Refactoring/</a>) or Resharper (<a href="http://www.jetbrains.com/resharper/index.html" rel="nofollow noreferrer">http://www.jetbrains.com/resharper/index.html</a>) both have support for encapsulating multiple fields.</p> <p>You may be able to get fancy and put together a macro that would allow you to select multiple fields and then encapsulate each one, but VS macros are not my ball of wax.</p>
15,439
<p>What are the <code>access.log.*</code> files?</p>
<p>Apache, I believe, does log rotation. So these would be the older log files with the access.log file being the current one.</p>
<p>Apache / apache2 itself doesn't do its own log rotation. On *nix systems, logs (including logs by Apache) are usually rotated via <a href="https://en.wikipedia.org/wiki/Log_rotation" rel="nofollow noreferrer">logrotate</a>, a command which looks like a service but is actually only a script triggered by cron in defined intervals. (@nobody already pointed that out in comments). One default logrotate configuration appends &quot;.1&quot; to an older, rotated log, so a file like <em>access.log.1</em> would end up in your logs directory. This is what you are probably seeing.</p> <p><strong>Is it possible to have apache log to multiple log files?</strong></p> <p>The question's title can be ambiguous. For anyone coming here to learn if it is possible to make Apache write to multiple log files simultaneously, the answer is: Yes.</p> <p>The <em>TransferLog</em> or <em>CustomLog</em> directives are used to define logfiles. These directives can be repeated to make Apache write to more than one log file. This also works for VHOSTS / Virtual Host entris. Only ancient Apache releases were limited to only one logfile per server configuration.</p>
20,845
<p>I'm looking for advice on how to dynamically create content in flash based on a database. Initially I was thinking that we would export the database to an XML file and use the built in Actionscript XML parser to take care of that, however the size of the XML file may prove prohibitive. </p> <p>I have read about using an intermediary step (PHP, ASP) to retrieve information and pass it back as something that Actionscript can read, but I would prefer not to do that if possible. Has anyone worked with the <a href="http://code.google.com/p/assql/" rel="nofollow noreferrer">asSQL</a> libraries before? Or is there something else that I am missing?</p>
<p>If you plan to deploy your flash content to a website, you should use some sort of backend - otherwise you would have a potential security problem. I use remoting with <a href="http://www.amfphp.org/" rel="noreferrer">AMFPHP</a>, it has worked out really well.</p>
<p>The general practice that I've experienced is that if it's something like a config file or just a really small amount of data then you could probably get away with just having an XML file on the server with your SWF files.</p> <p>If you want the data to be more dynamic or you anticipate changing it quite often I would definitely do as Nouveau has already said and use PHP or a similiar technology to output database queries into an XML structure for your flash to load.</p> <p>If there is a lot of data however and you are really noticing your program choking or lagging on loading up the XML in that format I would definitely recommend remoting like Kristian has suggested, AMFPHP seems to be one of the more popular choices.</p> <p>Check out grapefrukt's answer to another question about flash and database interaction<br> <a href="https://stackoverflow.com/questions/38674/does-adobe-flash-support-databases#39266">Does Adobe Flash support databases?</a></p>
8,838
<p>I have a PHP form (mortgage app) that is about 400 fields, traffic on the site will be low.</p> <p>What is the ideal Session size for 400 fields going into a MySQL db?</p> <p>In <code>php.ini</code> what do I set?</p> <p>Anything I should set that I am missing?</p>
<p>Well, personally I have had very large sessions before with very little problems. Probably the largest size I've had before is ~10MB. It's not optimal, but I haven't had a problem with slow scripts even with that size. I wouldn't worry about sessions getting to large, but I would try to keep it under control. My theory is, if keeping it in the session makes it much faster than quering the database every time (such as in the case of a search) then I go for it.</p>
<p>You should also check, post_max_size, max_input_vars (1000 default so you are ok)</p>
26,719
<p>Classes that use other classes (as members, or as arguments to methods) need instances that behave properly for unit test. If you have these classes available and they introduce no additional dependencies, isn't it better to use the real thing instead of a mock? </p>
<p>I say use real classes whenever you can.</p> <p>I'm a big believer in expanding the boundaries of "unit" tests as much as possible. At this point they aren't really unit tests in the traditional sense, but rather just an automated regression suite for your application. I still practice TDD and write all my tests first, but my tests are a little bigger than most people's and my green-red-green cycles take a little longer. But now that I've been doing this for a little while I'm completely convinced that unit tests in the traditional sense aren't all they're cracked up to be.</p> <p>In my experience writing a bunch of tiny unit tests ends up being an impediment to refactoring in the future. If I have a class A that uses B and I unit test it by mocking out B, when I decide to move some functionality from A to B or vice versa all of my tests and mocks have to change. Now if I have tests that verify that the end to end flow through the system works as expected then my tests actually help me to identify places where my refactorings might have caused a change in the external behavior of the system.</p> <p>The bottom line is that mocks codify the contract of a particular class and often end up actually specifying some of the implementation details too. If you use mocks extensively throughout your test suite your code base ends up with a lot of extra inertia that will resist any future refactoring efforts.</p>
<p>If you write your code in terms of interfaces, then unit testing becomes a joy because you can simply inject a fake version of any class into the class you are testing. </p> <p>For example, if your database server is down for whatever reason, you can still conduct unit testing by writing a fake data access class that contains some cooked data stored in memory in a hash map or something.</p>
21,766
<p>I have the following two models:</p> <pre><code>class Activity(models.Model): name = models.CharField(max_length=50, help_text='Some help.') entity = models.ForeignKey(CancellationEntity) ... class Cancellation(models.Model): activity = models.ForeignKey(Activity) date = models.DateField(default=datetime.now().date()) description = models.CharField(max_length=250) ... </code></pre> <p>I would like the Activity model to be aware when a Cancellation related to it is saved (both inserted or updated).</p> <p>What is the best way to go about this?</p>
<p>What you want to look into is <a href="http://docs.djangoproject.com/en/dev/ref/signals/" rel="noreferrer">Django's signals</a> (check out <a href="http://docs.djangoproject.com/en/dev/topics/signals/" rel="noreferrer">this page</a> too), specifically the model signals--more specifically, the <strong>post_save</strong> signal. Signals are Django's version of a plugin/hook system. The post_save signal gets sent every time a model is saved, whether it's updated or created (and it'll let you know if it was created). This is how you'd use signals to get notified when an Activity has a Cancellation</p> <pre><code>from django.db.models.signals import post_save class Activity(models.Model): name = models.CharField(max_length=50, help_text='Some help.') entity = models.ForeignKey(CancellationEntity) @classmethod def cancellation_occurred (sender, instance, created, raw): # grab the current instance of Activity self = instance.activity_set.all()[0] # do something ... class Cancellation(models.Model): activity = models.ForeignKey(Activity) date = models.DateField(default=datetime.now().date()) description = models.CharField(max_length=250) ... post_save.connect(Activity.cancellation_occurred, sender=Cancellation)</code></pre>
<p>What's wrong with the following?</p> <pre><code>class Cancellation( models.Model ): blah blah def save( self, **kw ): for a in self.activity_set.all(): a.somethingChanged( self ) super( Cancellation, self ).save( **kw ) </code></pre> <p>It would allow you to to control the notification among models very precisely. In a way, this is the canonical "Why is OO so good?" question. I think OO is good precisely because your collection of Cancellation and Activity objects can cooperate fully.</p>
23,379
<p><code>termios.h</code> defines:</p> <pre><code>#define TIOCM_OUT1 0x2000 #define TIOCM_OUT2 0x4000 </code></pre> <p>But what are the flags good for?</p>
<p>I believe this will produce the right results where it returns anything, but may reject valid integers. I dare say that can be worked around with a bit of effort though... (Oh, and it will also fail for negative numbers at the moment.)</p> <pre><code>static string ConvertToHex(decimal d) { int[] bits = decimal.GetBits(d); if (bits[3] != 0) // Sign and exponent { throw new ArgumentException(); } return string.Format("{0:x8}{1:x8}{2:x8}", (uint)bits[2], (uint)bits[1], (uint)bits[0]); } </code></pre>
<p>I've got to agree with James - do it manually - but don't use base-16. Use base 2^32, and print 8 hex digits at a time.</p>
27,246
<p>Several times, while perusing the Boost library's documentation, I've run across return values that are marked "<a href="http://www.boost.org/doc/libs/1_36_0/libs/utility/Collection.html" rel="noreferrer">convertible to <code>bool</code></a>" (search that page for the phrase "convertible to bool", it's about a third of the way down). I once stumbled across an oblique reference to a paper explaining the reason for that, but have never been able to find said paper (and I can no longer find the page I saw the reference on either).</p> <p>Can anyone explain why (and when) you should return something that's "convertible to <code>bool</code>" rather than simply returning a <code>bool</code>?</p>
<p>“convertible to bool” simply means anything which can meaningfully be used in a boolean context (e.g. in an <code>if</code> condition). This makes sense in implicit conversions. Imagine an object which you want to use in a boolean context, e.g. <code>std::fstream</code>:</p> <pre><code>ifstream ifs("filename"); while (ifs &gt;&gt; token) cout "token " &lt;&lt; token &lt;&lt; " read." &lt;&lt; endl; </code></pre> <p>Here, <code>ifs</code> is convertible to boolean. Well, actually, it isn't. Rather, it is convertible to something that, in turn, is convertible to <code>bool</code>. This is to prevent such statements:</p> <pre><code>int b = ifs; </code></pre> <p>The reasoning is that such a statement is most probably not intended and the compiler should therefore prevent it. By returning a “convertible to bool” rather than a <code>bool</code>, this is achieved because two user-defined implicit conversions can't be chained in one expression.</p> <p>In this context, you might want to look up the <a href="http://www.artima.com/cppsource/safebool.html" rel="noreferrer">safe bool idiom</a>. Chris has already alluded to one possible implementation, using <code>void*</code> as a return type. Usually, the <code>this</code> pointer is then used to represent <code>true</code>. This is what gets used by the STL. However, this is unfortunately still flawed. Several alternatives have been proposed (neatly wrapped up in the article I've linked above) and as far as I know, have also been included into C++0x for consideration. I'm not aware of the current status of these proposals, though.</p>
<p>Maybe for performance? In C/C++ you can do an if statement on numbers (0 is false, anything else is true). Converting to a strict bool is an extra operation, which in many cases wouldn't be required.</p> <p>I haven't actually used boost, so that's just a guess, but it seems like a reasonable one to me.</p>
32,948
<p>I 'm exploring for a browser solution / API that has the following features:</p> <ul> <li>Must support the nowadays default web technologies</li> <li>Must support client side XSLT</li> <li>Must support executing arbitrary Javascript on the pages it loads</li> <li>Must be able to catch events from the web page targeted to the browser or OS (I am specifically interested in window.print())</li> </ul> <p>QtWebkit seemed like the way to go but it still doesn't support XSLT so I had to look for alternatives. SWT Browser is a wrapper around the native browser component of the underlying system and in linux that I 'm interested this would mean the firefox engine that supports the attributes I 'm interested in except that I haven't still found out how to catch window.print() and provide my own implementation instead of the default one that is opening up a print dialog.</p> <p>Any suggestions?</p>
<p>If you know a way how to catch the event in javascript an prevent the native dialog from showing, you can use the method shown in this <a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet303.java?view=co" rel="nofollow noreferrer">snippet</a> to catch the event in your SWT code.</p> <p>The other option might be better though: Use mozilla's classes to register your own print handler. Something similar is shown in this <a href="http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet277.java?view=co" rel="nofollow noreferrer">snippet</a> for the download handler, but I haven't tested if it is possible for the print handler as well.</p> <p>The catch for this second option is stated in the snippet's javadoc:</p> <blockquote> <p>IMPORTANT: For this snippet to work properly all of the requirements for using JavaXPCOM in a stand-alone application must be satisfied (see <a href="http://www.eclipse.org/swt/faq.php#howusejavaxpcom" rel="nofollow noreferrer">http://www.eclipse.org/swt/faq.php#howusejavaxpcom</a>).</p> </blockquote>
<p>FWIW there's another approach for doing this with Mozilla-based SWT Browsers at <a href="http://www.eclipse.org/forums/index.php?t=msg&amp;th=166869&amp;start=0&amp;" rel="nofollow noreferrer">http://www.eclipse.org/forums/index.php?t=msg&amp;th=166869&amp;start=0&amp;</a> .</p>
28,066
<p>I am writing picture editing windows forms application using vb.net/c#. i have a client requirement to capture the photo from digital still camera attached to computer. </p> <p>how can i capture a photo from USB connected digital still camera device in my windows application ?</p>
<p>If you use the Windows Image Acquisition Library, you'll see events there for capturing camera new picture events. I had a similar requirement and wrote a test rig; we went down to the local camera store and tried every camera they had. The only cameras we could find that supported this functionality were the Nikon D-series cameras.</p> <p>We found that with most cameras, you can't even take a picture when they are plugged in. When you plug them in to the USB port, most cameras will switch into a mode where the only thing they'll do is transfer data. The quick way to find out if a camera will work at all is to plug it into a PC, then try to snap a picture. If it lets you do that you have a chance. It also needs to support PTP.</p>
<p>This depends on your camera.</p> <p>Many cameras will simply mount as USB mass storage devices. If this is the case, then you can just copy the file from the visible file system like you would any other file on an external disk.</p> <p>If the camera doesn't make its contents available in this way, you'll need to look at the camera driver documentation to see how they recommend interacting with it.</p>
10,128
<p>I know the so-called textbook definition of unit tests and integration tests. What I am curious about is when it is time to write unit tests... I will write them to cover as many sets of classes as possible.</p> <p>For example, if I have a <code>Word</code> class, I will write some unit tests for the <code>Word</code> class. Then, I begin writing my <code>Sentence</code> class, and when it needs to interact with the <code>Word</code> class, I will often write my unit tests such that they test both <code>Sentence</code> and <code>Word</code>... at least in the places where they interact.</p> <p><em>Have these tests essentially become integration tests because they now test the integration of these 2 classes, or is it just a unit test that spans 2 classes?</em></p> <p>In general, because of this uncertain line, I will rarely actually write integration tests... or is my using the finished product to see if all the pieces work properly the actual integration tests, even though they are manual and rarely repeated beyond the scope of each individual feature?</p> <p>Am I misunderstanding integration tests, or is there really just very little difference between integration and unit tests?</p>
<p>The key difference, to me, is that <strong>integration tests</strong> reveal if a feature is working or is broken, since they stress the code in a scenario close to reality. They invoke one or more software methods or features and test if they act as expected.</p> <p>On the opposite, a <strong>Unit test</strong> testing a single method relies on the (often wrong) assumption that the rest of the software is correctly working, because it explicitly mocks every dependency.</p> <p>Hence, when a unit test for a method implementing some feature is green, it does <b>not</b> mean the feature is working.</p> <p>Say you have a method somewhere like this:</p> <pre><code>public SomeResults DoSomething(someInput) { var someResult = [Do your job with someInput]; Log.TrackTheFactYouDidYourJob(); return someResults; } </code></pre> <p><code>DoSomething</code> is very important to your customer: it's a feature, the only thing that matters. That's why you usually write a Cucumber specification asserting it: you wish to <i>verify</i> and <i>communicate</i> the feature is working or not.</p> <pre><code>Feature: To be able to do something In order to do something As someone I want the system to do this thing Scenario: A sample one Given this situation When I do something Then what I get is what I was expecting for </code></pre> <p>No doubt: if the test passes, you can assert you are delivering a working feature. This is what you can call <b>Business Value</b>.</p> <p>If you want to write a unit test for <code>DoSomething</code> you should pretend (using some mocks) that the rest of the classes and methods are working (that is: that, all dependencies the method is using are correctly working) and assert your method is working.</p> <p>In practice, you do something like:</p> <pre><code>public SomeResults DoSomething(someInput) { var someResult = [Do your job with someInput]; FakeAlwaysWorkingLog.TrackTheFactYouDidYourJob(); // Using a mock Log return someResults; } </code></pre> <p>You can do this with Dependency Injection, or some Factory Method or any Mock Framework or just extending the class under test.</p> <p>Suppose there's a bug in <code>Log.DoSomething()</code>. Fortunately, the Gherkin spec will find it and your end-to-end tests will fail.</p> <p>The feature won't work, because <code>Log</code> is broken, not because <code>[Do your job with someInput]</code> is not doing its job. And, by the way, <code>[Do your job with someInput]</code> is the sole responsibility for that method.</p> <p>Also, suppose <code>Log</code> is used in 100 other features, in 100 other methods of 100 other classes.</p> <p>Yep, 100 features will fail. But, fortunately, 100 end-to-end tests are failing as well and revealing the problem. And, yes: <b>they are telling the truth</b>.</p> <p>It's very useful information: I know I have a broken product. It's also very confusing information: it tells me nothing about where the problem is. It communicates me the symptom, not the root cause.</p> <p>Yet, <code>DoSomething</code>'s unit test is green, because it's using a fake <code>Log</code>, built to never break. And, yes: <b>it's clearly lying</b>. It's communicating a broken feature is working. How can it be useful?</p> <p>(If <code>DoSomething()</code>'s unit test fails, be sure: <code>[Do your job with someInput]</code> has some bugs.)</p> <p>Suppose this is a system with a broken class: <img src="https://i.stack.imgur.com/611ZY.jpg" alt="A system with a broken class"></p> <p>A single bug will break several features, and several integration tests will fail.</p> <p><img src="https://i.stack.imgur.com/rKhSr.jpg" alt="A single bug will break several features, and several integration tests will fail"></p> <p>On the other hand, the same bug will break just one unit test.</p> <p><img src="https://i.stack.imgur.com/M64Vb.jpg" alt="The same bug will break just one unit test"></p> <p>Now, compare the two scenarios.</p> <p>The same bug will break just one unit test.</p> <ul> <li>All your features using the broken <code>Log</code> are red</li> <li>All your unit tests are green, only the unit test for <code>Log</code> is red</li> </ul> <p>Actually, unit tests for all modules using a broken feature are green because, by using mocks, they removed dependencies. In other words, they run in an ideal, completely fictional world. And this is the only way to isolate bugs and seek them. Unit testing means mocking. If you aren't mocking, you aren't unit testing.</p> <h2>The difference</h2> <p>Integration tests tell <b>what</b>'s not working. But they are of no use in <b>guessing where</b> the problem could be.</p> <p>Unit tests are the sole tests that tell you <b>where</b> exactly the bug is. To draw this information, they must run the method in a mocked environment, where all other dependencies are supposed to correctly work.</p> <p>That's why I think that your sentence "Or is it just a unit test that spans 2 classes" is somehow displaced. A unit test should never span 2 classes.</p> <p>This reply is basically a summary of what I wrote here: <a href="http://arialdomartini.wordpress.com/2011/10/21/unit-tests-lie-thats-why-i-love-them/" rel="noreferrer">Unit tests lie, that's why I love them</a>.</p>
<p>If you're a TDD purist, you write the tests before you write production code. Of course, the tests won't compile, so you first make the tests compile, then make the tests pass.</p> <p>You can do this with unit tests, but you can't with integration or acceptance tests. If you tried with an integration test, nothing would ever compile until you've finished!</p>
3,192
<p>I am trying to make a Kiosk application more accessible by increasing the size of fonts.<br> No problem on the main Form.<br> I'm having a problem replacing MessageBoxes (for which I believe there is no way to increase the font size) with small forms with the same message.</p> <p>This is where I'm running into the problem. The main Form can't <em>see</em> the error form and its Label to set the text. I have tried setting a property for the private Label on the error form, but it's still not working.</p> <p>I would be very grateful for any assistance. I have been trying to apply what I've learned in reading several threads from various C# sources.</p> <p>Two strange things I have noticed: </p> <ol> <li>In the MainForm, when I type ErrorForm, Intellisense list of suggested code pops up but the variable <code>LblNotCheckedInBecause</code> does not appear on the list.</li> <li>The compiler error says something about the <code>LBlNotCheckedInBecause</code>.get statement and it seems like to me it should be refering to the set statement since I'm trying to set that value.</li> </ol> <p>Here are the parts of the code that I believe are involved:</p> <p>From <code>ErrorForm.Designer.cs</code>:<br></p> <pre><code>private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label lblNotCheckedInBecause; // property I created to try to be able to change the label public string LblNotCheckedInBecause { get { return this.lblNotCheckedInBecause.Text; } set { this.lblNotCheckedInBecause.Text = value; } } </code></pre> <p>From <code>MainForm.cs</code>:<br></p> <pre><code>// this is what I'm trying to replace MessageBox.Show("You were not checked in because of the following reasons:" + sErrors); // this line is causing a compiler error ErrorForm.LblNotCheckInBecause = "You were not checked in because of the following reasons:" + sErrors; </code></pre> <p>Compiler error:<br></p> <blockquote> <p>Error 1 An object reference is required for the nonstatic field, method, or property 'LogisticsKiosk.ErrorForm.LblNotCheckInBecause.get' C:\Documents and Settings\My Documents\Visual Studio 2005\Projects\LogisticsKiosk\Forms\MainForm.cs 107 17 LogisticsKiosk</p> </blockquote>
<p>You cannot access the ErrorForm as if it was static. That is just the class definition, you need to set the property on an instance of the ErrorForm.</p> <p>Somewhere in your app, you created a new ErrorForm. You need to take that variable and set your LblNotCheckedInBecause property on that.</p> <p>Look for code like this;</p> <pre><code>ErrorForm errorFrm = new ErrorForm(); errorFrm.Show(); </code></pre> <p>Then you can do this if you have a reference to that variable;</p> <pre><code>errorFrm.LblNotCheckedInBecause = "Some Reason"; </code></pre> <p>The following does not work because your Property isn't static (and can't be made static without creating a singleton which you probably don't want to do)</p> <pre><code>// Doesn't work ErrorForm.LblNotCheckedInBecause = "Some Reason"; </code></pre>
<p>One thing to always keep in mind is how easy it is for another developer to read your code and understand. The best option I see is this</p> <p>ErrorForm form = new ErrorForm(); form.SetErrorLableMessageTo("Error Text"); form.Show();</p> <p>this is very readable. Passing the args in constructor doesn't show the intention until we go to see what's going on in constructor. Plus not in all the cases you'd want to do that and if you choose constructor way then you are bound (not a flexible design).</p>
43,411
<p>We use a base entity with properties such as version (datetime needed for NHibernate) and guid (as key).</p> <p>It also has an Id (int) field with two functions. Firstly to relate to legacy application key if there is one. Secondly as a shorthand code: for instance files are sometimes created based on these which would look ugly and long using our guid key. My question is not really about pros and cons of base entities but about up-typing this Id to Int64?</p> <p>It would not affect how it is stored within our MS SQL Server database. Would it have more cost in our cache and memory?. Is this really that much of a worry?</p> <p>I am interested to hear other downsides besides performance. Consider also these values will probably be exposed through web services to third parties in time too.</p> <p>The alternative is to deal with the exceptions of larger integers as they arise and implement them specifically in derived entities. The downside is this would need to be done in code and what would we do when we discover some cases when in production of larger integers? There would of course be input validation to stop actual errors but it may restrict expanding data.</p>
<p>Well, int64 uses 8 byte of memory storage, while int uses 4 byte... however, you pointed out most of the disadvantages already. Of course calculations performed will also be slower on many systems (a 64 bit system running in 64 bit mode can perform operations on 64 bit as fast as on 32 bit, but a 32 bit system needs to perform extra work, that means adding two 64 bit numbers is performed by two 32 bit adds plus some extra code - other math operations will be equally broken down into 32 bit operations). However unless you store millions of these numbers and perform tons of operations with them, I doubt you will see any performance difference, though, neither in CPU time nor in memory.</p>
<p>Portability... though C# isn't really know as lingua franca if you're going for portable, so this might be moot for your perspective?</p>
30,086
<p>My organization has a form to allow users to update their email address with us. It's suggested that we have two input boxes for email: the second as an email confirmation.</p> <p>I always copy/paste my email address when faced with the confirmation. I'm assuming most of our users are not so savvy.</p> <p>Regardless, is this considered a good practice? I can't stand it personally, but I also realize it probably isn't meant for me. If someone screws up their email, they can't login, and they must call to sort things out.</p>
<p>I would just use one input box. The "Confirm" input is a remnant form the "Confirm Password" method. </p> <p>With passwords, this is useful because they are usually typed as little circles. So, you can't just look at it to make sure that you typed it correctly. </p> <p>With a regular text box, you can visually check your input. So, there is no need for a confirmation input box.</p>
<p>I'd say that this is ok but should only be reserved for forms where the email is essential. If you mistype your email for your flight booking then you have severed the two-way link between yourself and the other party and risk not getting the confirmation number, here on StackOverflow it would only mean your Gravatar would not be loaded ...</p> <p>I'd consider myself fairly techie but I always fill in both fields /wo cut-paste if I regard it to be important enough.</p>
2,686
<p>I currently have a print job that is about 50% done, been running for 2 hours with 2 hours remaining. One side is curling/warping pretty bad, and I'm afraid there's no possible way this is going to finish without serious problems if I don't intervene.</p> <p>So what I'm doing is either brilliant or idiotic, I'm not sure which: I've paused the print job, stuck some elmers glue below the curling part (with toothpicks, careful not to budge anything else), added a couple degrees to the heatbed (for pliability hopefully), put a small book on top of it to smash it on the glue and let it rest for a little bit (I'll report back if this was a horrible idea or not).</p> <p><strong>So my main quesiton:</strong> Is there any other techniques that you folks can recommend for a scenario like this? McGuyver'y techniques to repair your in-progress print jobs? Has anyone tried this technique I'm attempting and if so how successful was it?</p> <p>In case it matters, I have an ANET A8 and generally send my print jobs to Octoprint (Raspi) from Cura with a Octoprint plugin (Windows). Printing with PLA filament. I've done quite a few successful prints recently, but this is the first one that goes from corner-to-corner on the heatbed (<a href="https://www.thingiverse.com/thing:2189694" rel="nofollow noreferrer">this specifically</a>). Printing at 207c with 60c heatbed (bumped up to 64 while glue settles). It's in a cooler room of the house, and doesn't have an enclosure so I'm afraid the cool temp is affecting it.</p> <p>Thanks</p> <p>Edit, last maybe significant (or maybe not) details: printing on glass with glue stick applied to it - been doing it for weeks and works quite well for the most part. Also, printing on a raft.</p> <p>Edit, here are a few pics. Both are from the back of the printer looking forward. I have one cam almost exactly level with the glass so I can see the hot-end extrude filament and another one slightly above it. Sorry for the bad lighting. Also included screenshots of my slicer settings for this print. </p> <p>Btw, I've since resumed printing after glueing it down, so far so good - but as you can see in the first pic it may have some possible structural defects and still has a slight curl:</p> <p><a href="https://i.stack.imgur.com/B2sxA.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/B2sxA.jpg" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/3YhXj.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3YhXj.jpg" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/KhMjG.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KhMjG.png" alt="Slicer Settings"></a></p> <p><a href="https://i.stack.imgur.com/wVyqz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wVyqz.png" alt="Slicer Settings (pt2)"></a></p>
<p>Three thoughts:</p> <ol> <li>bed temperature</li> <li>rim width</li> <li>bonding agent</li> </ol> <p>Bed Temperature:</p> <p>Often the edges of a heated bed are not as hot as the center. Making the heat pass through an insulator (the glass) makes the temperature profile on the corners more relatively cool compared to the center than if you were printing directly on the aluminum bed.</p> <p>To offset that, you could:</p> <ol> <li>Increase the overall heated bed temperature.</li> <li>Wrap some insulation (such as ceramic felt) around the edge, keeping it out of the way of the print.</li> <li>Add insulation to the underside corners of the bed, to reduce heat loss.</li> </ol> <p>Rim Thickness:</p> <p>I see that you are using a rim. Since the rim was also pulling up, rather than the print pulling out of the rim, you might benefit from making the rim broader.</p> <p>Bonding Agent:</p> <p>It looks as if you are printing on blue tape, but that might be the picture. IME, gluestick and blue tape aren't often used together. If you are using only blue tape, the condition of the tape is critical. Any grease or rubbing of the tape (such as by resting your hand on the bed when making other prints) can reduce the holding power.</p> <p>If you haven't tried it yet, you might try printing PLA with the PVA (polyvinyl alcohol) gluestick. I use the "purple until dry" Elmers gluesticks with good results.</p>
<p>More glue to hold it down and lower in-fill percentage will reduce the warping. Or adding more cut-outs to the design like you have further up the shaft. </p>
724
<p>Obviously the <a href="http://java.sun.com/j2se/1.5.0/docs/api/" rel="nofollow noreferrer">Java API</a> reference, but what else is there that you all use? </p> <p>I've been doing web development my entire career. Lately I've been messing around a lot with <a href="http://groovy.codehaus.org" rel="nofollow noreferrer">Groovy</a> and I've decided to do a small application in <a href="http://groovy.codehaus.org/griffon" rel="nofollow noreferrer">Griffon</a> just to experiment more with Groovy and also break some ground in desktop development. The only thing is I'm totally green when it comes to desktop apps.</p> <p>So, world, where's a good place to start?</p>
<p><a href="http://java.sun.com/docs/books/tutorial/uiswing/" rel="noreferrer">The Swing Tutorial</a> is very good. Apart from that, the Swing API is obviously <i>the</i> reference, however it's also a treasure trove of fairly good source code! Add the API source to your IDE and you can jump directly to the implementation to all the Swing classes. This is a great way to explore the functionality, see how various Swing components work and learn a good Swing "style". Furthermore, it's great to be able to step through the API classes if things don't seem to work and you have no idea why! Adding the API source to the IDE has the additional benefit that you get all the JavaDocs along with it, although all modern IDEs can also pull them <a href="http://java.sun.com/j2se/1.4.2/docs/" rel="noreferrer">from the net</a> -- you do <b>not</b> want to program desktop Java without the documentation available from within the IDE!</p> <p>NetBeans and other IDEs do make the creation of IDEs very easy, but be aware that there is a lot more to Swing than just containers and layout managers. In fact, containers and layout managers are among the easier things, and I'd recommend learning to use them by hand, too. There is nothing at all wrong with using a GUI builder, but in some cases it's overkill, and then it's nicer to just quickly whip up a GUI from source. In other cases you need to be able to create a GUI dynamically and then GUI builders are no use at all! For creating very complex layouts from source, I recommend <a href="http://www.jgoodies.com/freeware/forms/" rel="noreferrer">FormLayout</a>, which has its own set of quirks, but which does scale (in terms of programming effort) to very big frames and layouts.</p> <p>If you've only done Groovy so far, you'll be surprised how well documented Swing and the rest of the Java API is and how well everything is integrated. It might also take some getting used to a different style of programming, using the debugger more often and println-debugging less, etc. There might also be some "boiler-plate" code that will be very annoying. ;) Enjoy.</p>
<p>When it comes to developing java desktop applications, I would highly recommend using the IDE environment <a href="http://www.netbeans.org" rel="nofollow noreferrer">Netbeans</a>. Especially when it comes to the development of Swing based applications.</p>
12,483
<p>If you are relying on an implementation of Python that has a Global Interpreter Lock (i.e. CPython) and writing multithreaded code, do you really need locks at all?</p> <p>If the GIL doesn't allow multiple instructions to be executed in parallel, wouldn't shared data be unnecessary to protect?</p> <p>sorry if this is a dumb question, but it is something I have always wondered about Python on multi-processor/core machines. </p> <p>same thing would apply to any other language implementation that has a GIL.</p>
<p>You will still need locks if you share state between threads. The GIL only protects the interpreter internally. You can still have inconsistent updates in your own code.</p> <p>For example:</p> <pre><code>#!/usr/bin/env python import threading shared_balance = 0 class Deposit(threading.Thread): def run(self): for _ in xrange(1000000): global shared_balance balance = shared_balance balance += 100 shared_balance = balance class Withdraw(threading.Thread): def run(self): for _ in xrange(1000000): global shared_balance balance = shared_balance balance -= 100 shared_balance = balance threads = [Deposit(), Withdraw()] for thread in threads: thread.start() for thread in threads: thread.join() print shared_balance </code></pre> <p>Here, your code can be interrupted between reading the shared state (<code>balance = shared_balance</code>) and writing the changed result back (<code>shared_balance = balance</code>), causing a lost update. The result is a random value for the shared state.</p> <p>To make the updates consistent, run methods would need to lock the shared state around the read-modify-write sections (inside the loops) or have <a href="http://en.wikipedia.org/wiki/Software_transactional_memory" rel="noreferrer">some way to detect when the shared state had changed since it was read</a>.</p>
<p>A little bit of update from Will Harris's example:</p> <pre><code>class Withdraw(threading.Thread): def run(self): for _ in xrange(1000000): global shared_balance if shared_balance &gt;= 100: balance = shared_balance balance -= 100 shared_balance = balance </code></pre> <p>Put a value check statement in the withdraw and I don't see negative anymore and updates seems consistent. My question is:</p> <p>If GIL prevents only one thread can be executed at any atomic time, then where would be the stale value? If no stale value, why we need lock? (Assuming we only talk about pure python code)</p> <p>If I understand correctly, the above condition check wouldn't work in a <em>real</em> threading environment. When more than one threads are executing concurrently, stale value can be created hence the inconsistency of the share state, then you really need a lock. But if python really only allows just one thread at any time (time slicing threading), then there shouldn't be possible for stale value to exist, right?</p>
13,068
<p>I'm trying to get a case-insensitive search with two strings in JavaScript working.</p> <p>Normally it would be like this:</p> <pre><code>var string="Stackoverflow is the BEST"; var result= string.search(/best/i); alert(result); </code></pre> <p>The <code>/i</code> flag would be for case-insensitive.</p> <p>But I need to search for a second string; without the flag it works perfect:</p> <pre><code>var string="Stackoverflow is the BEST"; var searchstring="best"; var result= string.search(searchstring); alert(result); </code></pre> <p>If I add the <code>/i</code> flag to the above example it would search for searchstring and not for what is in the variable "searchstring" (next example not working):</p> <pre><code>var string="Stackoverflow is the BEST"; var searchstring="best"; var result= string.search(/searchstring/i); alert(result); </code></pre> <p>How can I achieve this?</p>
<p>Yeah, use <code>.match</code>, rather than <code>.search</code>. The result from the <code>.match</code> call will return the actual string that was matched itself, but it can still be used as a boolean value.</p> <pre><code>var string = "Stackoverflow is the BEST"; var result = string.match(/best/i); // result == 'BEST'; if (result){ alert('Matched'); } </code></pre> <p>Using a regular expression like that is probably the tidiest and most obvious way to do that in JavaScript, but bear in mind it <em>is</em> a regular expression, and thus can contain regex metacharacters. If you want to take the string from elsewhere (eg, user input), or if you want to avoid having to escape a lot of metacharacters, then you're probably best using <code>indexOf</code> like this:</p> <pre><code>matchString = 'best'; // If the match string is coming from user input you could do // matchString = userInput.toLowerCase() here. if (string.toLowerCase().indexOf(matchString) != -1){ alert('Matched'); } </code></pre>
<p>I noticed that if the user enters a string of text but leaves the input without selecting any of the autocomplete options no value is set in the hidden input, even if the string coincides with one in the array. So, with help of the other answers I made this:</p> <pre><code>var $local_source = [{ value: 1, label: "c++" }, { value: 2, label: "java" }, { value: 3, label: "php" }, { value: 4, label: "coldfusion" }, { value: 5, label: "javascript" }, { value: 6, label: "asp" }, { value: 7, label: "ruby" }]; $('#search-fld').autocomplete({ source: $local_source, select: function (event, ui) { $("#search-fld").val(ui.item.label); // display the selected text $("#search-fldID").val(ui.item.value); // save selected id to hidden input return false; }, change: function( event, ui ) { var isInArray = false; $local_source.forEach(function(element, index){ if ($("#search-fld").val().toUpperCase() == element.label.toUpperCase()) { isInArray = true; $("#search-fld").val(element.label); // display the selected text $("#search-fldID").val(element.value); // save selected id to hidden input console.log('inarray: '+isInArray+' label: '+element.label+' value: '+element.value); }; }); if(!isInArray){ $("#search-fld").val(''); // display the selected text $( "#search-fldID" ).val( ui.item? ui.item.value : 0 ); } } </code></pre>
21,412
<p>Building a client-side swing application what should be notified on a bus (application-wide message system, similar in concept to JMS but much simpler) and what should be notified using direct listeners?</p> <p>When using a bus, I always have an unescapable feeling of "I have no idea who uses that and where". Also, no set order, hard to veto events, hard to know exactly what's going on at a set time.</p> <p>On the other hand, using listeners means either directly referencing the source object (coupling) or passing the reference through myriad conversions (A--b_listener-->B, B--c_listener-->C only because a needs to know something only C can to tell, but B has no interest in).</p> <p>So, are there any rule of the thumb regarding this? Any suggestion how to balance?</p>
<p>Event buses are very, very useful tools for providing decoupling in certain architectures. Listeners are easy to implement, but they have significant limitations when your object and dependency graph gets large. Listeners tend to run into problems with cyclic dependencies (events can 'bounce' in odd ways, and you wind up having to play games to ensure that you don't get stuck. Most binding frameworks do this for you, but there's something distasteful about knowing that listener events are shooting off into a million places).</p> <p>I make this kind of decision based on project size and scalability. If it's a big app, or there are aspects of the app that can by dynamic (like plugin modules, etc...) then a bus is a good way to keep the architecture clean (OSGI-like module containers are another approach, but heavier weight).</p> <p>If you are considering a bus architecture, I recommend that you take a look at the <a href="https://eventbus.dev.java.net/" rel="nofollow noreferrer">Event Bus</a> project - it works very well with Swing and provides a robust, out of the box solution for what you are asking about.</p>
<p>Well, I can imagine the approach where models are updated using BUS like system and events from models are delegated using listeners. Simple scenario: I got server side which represents producer of data. Then on client side a got consumer interface which consumes all incoming messages and transform them into my internal messages/DTOs and push them into bus which distributes them into application model(s). These model process incoming messages and decide to notify interested components using listeners.</p>
28,158
<p>I have a 3D model that I'd like to print. This is my first project, so I'm trying to decide if I'm getting in over my head. Here's the model rendered with Blender:</p> <p><a href="https://i.stack.imgur.com/N1cVF.png" rel="noreferrer"><img src="https://i.stack.imgur.com/N1cVF.png" alt="enter image description here"></a></p> <p>If I throw it at a commercial printing shoppe, is it going to be fairly straight forward? Or is it unlikely to be able to get the colours fitting together like this to work well?</p>
<p>Here is a set of options you can get:</p> <ol> <li>print the object on multi color printer</li> </ol> <p>Unfortunately we got some limitations here (on the market). Printers have limited set of heads which are in fact printing in one color at a time. So we usually have 2 colors, there are also 4 color heads. If there are more then they are rare, expensive or rare and expensive.</p> <p>here are examples of such color printouts:</p> <p><a href="https://i.stack.imgur.com/yzU5gs.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yzU5gs.jpg" alt="click to go to the project"></a><a href="http://www.thingiverse.com/thing:329436" rel="nofollow noreferrer">project</a> <a href="https://i.stack.imgur.com/wgYj6s.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wgYj6s.jpg" alt="click to go to the project"></a><a href="http://www.thingiverse.com/thing:67503" rel="nofollow noreferrer">project</a></p> <ol start="2"> <li>print object splitted</li> </ol> <p>In this case you can have single color printer. You print parts in one color then you change filament and print other color and so on. The issue here is to have well formed object which is designed for such print method (it's connectable in some way) or you can stick printed parts with the glue.</p> <p>here are examples of such puzzled printouts: </p> <p><a href="https://i.stack.imgur.com/xT33Es.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xT33Es.jpg" alt="click to go to the project"></a><a href="http://www.thingiverse.com/thing:642211" rel="nofollow noreferrer">project</a> <a href="https://i.stack.imgur.com/EEIOks.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/EEIOks.jpg" alt="click to go to the project"></a><a href="http://www.thingiverse.com/thing:1360459" rel="nofollow noreferrer">project</a></p> <ol start="3"> <li>print and paint</li> </ol> <p>here are examples of such painted printouts: </p> <p><a href="https://i.stack.imgur.com/BbzNGs.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/BbzNGs.jpg" alt="click to go to the project"></a><a href="http://www.thingiverse.com/thing:1333103" rel="nofollow noreferrer">project</a> <a href="https://i.stack.imgur.com/oZP7Qs.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oZP7Qs.jpg" alt="click to go to the project"></a><a href="http://www.thingiverse.com/thing:459472" rel="nofollow noreferrer">project</a></p> <p><strong>NOTE:</strong></p> <p>All above assumes that you are gonna print your object in FDM technology. You can also take a look on <a href="http://3dprintingfromscratch.com/common/types-of-3d-printers-or-3d-printing-technologies-overview" rel="nofollow noreferrer">other technologies</a> such as:</p> <ul> <li>Stereolithography(SLA)</li> <li>Digital Light Processing(DLP)</li> <li>Selective Laser Sintering (SLS)</li> <li>Selective laser melting (SLM)</li> <li>Electronic Beam Melting (EBM)</li> <li>Laminated object manufacturing (LOM)</li> </ul>
<p>You would need to ask around shops to see what they think about this 3d file. What I have heard is that colors of prints end up blended together, and that the print resolution is low. How many colors are you using? You could probably get a quality print, but it would come with a high price. Print quality is dependent on the expensiveness of the machine used.</p>
289
<p>Please consider this example class:</p> <pre><code>[Serializable] public class SomeClass { private DateTime _SomeDateTime; public DateTime SomeDateTime { get { return _SomeDateTime; } set { _SomeDateTime = value; } } } </code></pre> <p>I would like to alter the serialization of any DateTime declared in the class according to my own rules. The members of this class will change frequently and I don't want to maintain a custom serializer for every change. Also I would like this behaviour to be inherited by subclasses and not code a custom serializer for every one. The serialization is being output by a web service. Thanks for any help!</p>
<p>look at the OnSerializing and OnDeserializing attributes to call custom methods when your objects are serialized. you can impelment some custom logic in there and decouple the serializing process from the actual datatypes.</p>
<p>Well, you can use a "bool ShouldSerializeSomeDateTime()" method to enable/disable serialization of individual members, but I don't think that is quite what you need. Another common option is to add a member that does the format itself:</p> <p>public string SomeDateTimeFormatted { get { return theField == DateTime.MinValue ? "" : theField.ToString("R");} // or whatever format set { ... opposite ...} }</p> <p>It is nicer to stick with the inbuilt serialization if you can, though - in part to reduce the amount of code you need to write. Josh's suggestion for a nullable DateTime (DateTime?) is a good one, although it might still not be quite empty-string vs formatted-string - I expect it would use the xsi:nil markup.</p>
20,958
<p>In ASP.NET MVC it's possible to choice between having a typed view were you define in the codebehind what kind of data the view can should expect. But it's also possible to not define this and just pass any kind of data to view in a ViewData container.</p> <p>What would the best model here or should I mix depending on what kind of data we're talking about (maybe just make sure to have data that's critical to the functionality of the view typed and other data not typed?)? I don't really understand why there is a option here ...</p>
<p>I would recommend always using the strongly typed ViewData... that way you have compile time checking, intellisense, you don't have to do casting in your view, and the ability to refactor your code much easier.</p>
<p>I had this thought too in the past. In my site, I used to strong-type the view, when the view is almost a 1:1 model of the class you are showing. Like showing a list of all users, I type to List, this way I don't need to cast anytime to have the right datatype.</p> <p>In none specific views, I just strong-type to the most "heavy"/used type.</p> <p>In forms, the form itself is the type of the view when returning View(form); ....</p>
16,692
<p>Earlier I asked this question <a href="https://stackoverflow.com/questions/309708/how-to-correctly-unit-test-my-dal">How to correctly unit test my DAL?</a>, one thing left unanswered for me is if to really test my DAL is to have a Test DB, then what is the role of mocking vs. a testing DB?</p> <p>To add on this, another person suggested to "use transactions and rollback at the end of the unit test, so the db is clean", test db that is. What do you guys think of this testing + test DB + transaction rollback (so db is not really written) approach to test DAL?</p> <p>To be complete, my DAL is built with Entity Framework, there is no stored proc in DB. Since EF is so new, I really need to test DAL to make sure they work correctly.</p>
<p>I think you'll probably want to do some integration testing to check logic that is enforced by your database structure, for example constraints, triggers, autoincrement columns, etc. You should, however, for unit testing mock out whatever framework components that your DAL relies upon as you want (in your unit tests) to test only those components that you have coded. You don't really need to test methods on SqlCommand or SqlConnection (for example). You should assume that the framework components that you use work and create stubs or mocks for them that return known data (good, bad, exceptions) to your methods to make sure that your methods work properly. Without mocking you are responsible for generating the data in the database and making sure that it is correct. You also leave open dependencies on the network, the database itself, etc. that may make your tests brittle.</p> <p>Also, unit testing does not remove the need for other types of testing. Integration tests and acceptance tests are still valid and need to be done. They probably don't need to be done with the same frequency as unit tests and may not need to be as extensive as your code quality improves with unit testing, but unit testing is not a magic bullet.</p>
<p>The problem could very well be in the original question. Some of the more popular examples of MVC use a shortcut by returning a <code>DbSet</code> such as:</p> <pre><code>public class MusicStoreEntities : DbContext { public DbSet&lt;Album&gt; Albums { get; set; } public DbSet&lt;Genre&gt; Genres { get; set; } public DbSet&lt;Artist&gt; Artists { get; set; } public DbSet&lt;Cart&gt; Carts { get; set; } public DbSet&lt;Order&gt; Orders { get; set; } public DbSet&lt;OrderDetail&gt; OrderDetails { get; set; } } </code></pre> <p>To me this tightly couples the implementation of persistence which I believe is a bad thing. It woud be better to return <code>List&lt;t&gt;</code> which could easily be mocked.</p>
39,982
<p>Do programmers like to create deadlines? Im a web developer, and schedules/deadlines are all over the place in my field. But I've worked with some software engineers/programmers who hate deadlines, is there a way around that?</p>
<p>Firstly, you need to distinguish between deadlines and estimates.</p> <ul> <li>Deadlines come from external sources, eg, "Feature X needs to be ready for the trade show".</li> <li>Estimates come from internal sources, eg, "Feature X will take N weeks to complete".</li> </ul> <p>Generally, programmers should create estimates, and sales/marketing will create deadlines.</p> <p>Problems occur when the two cannot be resolved - if the deadline is closer than the estimate.</p> <p>Helpful hints for dev (leads):</p> <ul> <li>Let the person doing the work create the estimate.</li> <li>Ensure estimates are based on tiny tasks, each no longer than a day or two.</li> <li>Use a feedback loop to let developers improve their estimation skills.</li> <li>Accurate estimation skills lets you push harder against deadline demands.</li> </ul> <p>Helpful hints for marketers / deadline creators:</p> <ul> <li>Don't override an estimate with a deadline.</li> <li>If a deadline conflicts with an estimate, the only real options are (a) developers work overtime, (b) the requirements for the deadline are trimmed, or (c) the deadline is missed.</li> <li>Explain why the deadline is important, and what the purpose of the feature deadline is ("customer X will sign a six-figure contract").</li> <li>Understand that people who feel they cannot meet aggressive deadlines will not be motivated.</li> </ul>
<p>Well, I'm quite happy with a deadline <strong>if</strong> that deadline has been determined through well thought-out estimate process with input from both managers and engineers <strong>and</strong> the requirements for what is supposed to be delivered on said deadline are well defined.</p>
49,948
<p>How do you capture the mouse events, move and click over top of a Shockwave Director Object (not flash) in Firefox, via JavaScript. The code works in IE but not in FF. </p> <p>The script works on the document body of both IE and Moz, but mouse events do not fire when mouse is over a shockwave director object embed.</p> <p>Update: </p> <pre><code> function displaycoordIE(){ window.status=event.clientX+" : " + event.clientY; } function displaycoordNS(e){ window.status=e.clientX+" : " + e.clientY; } function displaycoordMoz(e) { window.alert(e.clientX+" : " + e.clientY); } document.onmousemove = displaycoordIE; document.onmousemove = displaycoordNS; document.onclick = displaycoordMoz; </code></pre> <hr> <p>Just a side note, I have also tried using an addEventListener to "mousemove".</p>
<p>You could also catch the mouse event within Director (That never fails) and then call your JS functions from there, using gotoNetPage "javascript:function('" &amp; argument &amp; "')"</p> <p>ej:</p> <pre><code>on mouseDown me gotoNetPage "javascript:function('" &amp; argument &amp; "')" end </code></pre> <p>The mouse move detection is a little bit trickier, as there is no such an event in lingo, but you can use:</p> <pre><code>property pMouseLock on beginsprite pMouseLock = _mouse.mouseLock end on exitFrame if _mouse.mouseLock &lt;&gt; pMouseLock then gotoNetPage "javascript:function('" &amp; argument &amp; "')" pMouseLock = _mouse.mouseLock end if end </code></pre> <p>regards</p>
<p>Just an idea.</p> <p>Try overlaying the shockwave object with a div with opacity 0, then you can capture events on the div itself.</p>
7,341
<p>On my VPS server (Fedora 9), mingetty keeps respawning itself because of a "permission denied" error on tty[1-6], even though:</p> <pre> root# ls -la /dev/tty1 crw------- 1 root root 4, 1 Sep 19 14:22 /dev/tty1 </pre> <p>Even weirder, this doesn't work:</p> <pre> root# cat &lt;/dev/tty1 bash: /dev/tty1: Permission denied </pre> <p>I am guessing this has something to do with the VM host, but both my VPS provider and I are out of ideas, and so is Google... Any clue as to why root cannot access a character device with root rw privileges?</p> <p>Update: I've made sure SELinux has been disabled; yet, the issue is still there....</p> <p>Update: The strace dump:</p> <pre> 32399 rt_sigaction(SIGTSTP, {SIG_DFL}, {SIG_DFL}, 8) = 0 32399 rt_sigaction(SIGTTIN, {SIG_DFL}, {SIG_IGN}, 8) = 0 32399 rt_sigaction(SIGTTOU, {SIG_DFL}, {SIG_IGN}, 8) = 0 32399 rt_sigaction(SIGINT, {SIG_IGN}, {SIG_IGN}, 8) = 0 32399 rt_sigaction(SIGQUIT, {SIG_IGN}, {SIG_IGN}, 8) = 0 32399 rt_sigaction(SIGCHLD, {SIG_DFL}, {0x807b990, [], SA_RESTORER, 0xb7e7b708}, 8) = 0 32399 open("/dev/tty1", O_RDONLY|O_LARGEFILE) = -1 EACCES (Permission denied) 32399 open("/dev/tty1", O_RDONLY|O_LARGEFILE) = -1 EACCES (Permission denied) 32399 fstat64(2, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 1), ...}) = 0 32399 mmap2(NULL, 4096, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0) = 0xb7fe1000 32399 write(2, "bash: /dev/tty1: Permission deni"..., 35) = 35 </pre> <p>Can't say it's making much sense to me... </p>
<p>I suspect that SELinux may be the problem. Try temporarily disabling it to see if it works.</p>
<p>Go into your /etc/inittab and comment out the following lines (or others like it). You may need to reboot to stop the re-spawns</p> <pre><code>c1:12345:respawn:/sbin/agetty 38400 tty1 linux c2:2345:respawn:/sbin/agetty 38400 tty2 linux c3:2345:respawn:/sbin/agetty 38400 tty3 linux c4:2345:respawn:/sbin/agetty 38400 tty4 linux c5:2345:respawn:/sbin/agetty 38400 tty5 linux c6:2345:respawn:/sbin/agetty 38400 tty6 linux </code></pre>
13,361
<p>I need to enumerate all running applications. In particular, all top windows. And for every window I need to add my custom item to the system menu of that window.</p> <p>How can I accomplish that in C++?</p> <p><strong>Update.</strong></p> <p>I would be more than happy to have a solution for Windows, MacOS, and Ubuntu (though, I'm not sure if MacOS and Ubuntu have such thing as 'system menu').</p>
<p>For Windows, another way to get the top-level windows (besides EnumWindows, which uses a callback) is to get the first child of the desktop and then retrieve all its siblings:</p> <pre><code>HWND wnd = GetWindow(GetDesktopWindow(), GW_CHILD); while (wnd) { // handle 'wnd' here // ... wnd = GetNextWindow(wnd, GW_HWNDNEXT); } </code></pre> <p>As for getting the <em>system</em> menu, use the <a href="http://msdn.microsoft.com/en-us/library/ms647985(VS.85).aspx" rel="noreferrer"><code>GetSystemMenu</code></a> function, with FALSE as the second argument. The <a href="http://msdn.microsoft.com/en-us/library/ms647640(VS.85).aspx" rel="noreferrer"><code>GetMenu</code></a> mentioned in the other answers returns the <em>normal</em> window menu.</p> <p>Note, however, that while adding a custom menu item to a foreign process's window is easy, responding to the selection of that item is a bit tricky. You'll either have to inject some code to the process in order to be able to subclass the window, or install a global hook (probably a <code>WH_GETMESSAGE</code> or <code>WH_CBT</code> type) to monitor <code>WM_SYSCOMMAND</code> messages. </p>
<p>You can use <a href="http://msdn.microsoft.com/en-us/library/ms633497(VS.85).aspx" rel="nofollow noreferrer">EnumWindows()</a> to enumerate top level Windows.</p> <p>I don't have a specific answer for the second part of your question, but if you subclass the window, I imagine you can modify the system menu.</p> <p>EDIT: or do what Chris said: call GetMenu()</p>
16,790
<p>Can it be done and if so, how? </p>
<p>You can use Merge Replication. Theres a tutorial here <a href="http://msdn.microsoft.com/en-us/sqlserver/bb219480.aspx" rel="nofollow noreferrer">SQL Server Compact 3.5 How-to Tutorials</a> (Number 5).</p>
<p>Because of budget constraints I think it will have to beta-tester's approch,i tried following the guide and cant seem to get it working. Before I spend time getting it to work, I just confrim, Replicating between SqlServer 2005 and Compact Edition is something that can be done?</p>
2,927
<p>We have an application that generates simulated data for one of our services for testing purposes. Each data item has a unique Guid. However, when we ran a test after some minor code changes to the simulator all of the objects generated by it had the same Guid.</p> <p>There was a single data object created, then a for loop where the properties of the object were modified, including a new unique Guid, and it was sent to the service via remoting (serializable, not marshal-by-ref, if that's what you're thinking), loop and do it again, etc.</p> <p>If we put a small Thread.Sleep( ...) inside of the loop, it generated unique id's. I think that is a red-herring though. I created a test app that just created one guid after another and didn't get a single duplicate.</p> <p>My theory is that the IL was optimized in a way that caused this behavior. But enough about my theories. What do YOU think? I'm open to suggestions and ways to test it.</p> <p>UPDATE: There seems to be a lot of confusion about my question, so let me clarify. I DON'T think that NewGuid() is broken. Clearly it works. Its FINE! There is a bug somewhere though, that causes NewGuid() to either: 1) be called only once in my loop 2) be called everytime in my loop but assigned only once 3) something else I haven't thought of</p> <p>This bug can be in my code (MOST likely) or in optimization somewhere.</p> <p>So to reiterate my question, how should I debug this scenario? </p> <p>(and thank you for the great discussion, this is really helping me clarify the problem in my mind) </p> <p>UPDATE # 2: I'd love to post an example that shows the problem, but that's part of my problem. I can't duplicate it outside of the whole suite of applications (client and servers).</p> <p>Here's a relevant snippet though:</p> <pre><code>OrderTicket ticket = new OrderTicket(... ); for( int i = 0; i &lt; _numOrders; i++ ) { ticket.CacheId = Guid.NewGuid(); Submit( ticket ); // note that this simply makes a remoting call } </code></pre>
<p>Does Submit do an async call, or does the ticket object go into another thread at any stage.</p> <p>In the code example you are reusing the same object. What if Submit sends the ticket in a background thread after a short delay (and does not take a copy). When you change the CacheId you are actually updating all the pending submits. This also explains why a Thread.Sleep fixes the problem. Try this:</p> <pre><code>for( int i = 0; i &lt; _numOrders; i++ ) { OrderTicket ticket = new OrderTicket(... ); ticket.CacheId = Guid.NewGuid(); Submit( ticket ); // note that this simply makes a remoting call } </code></pre> <p>If for some reason this is not possible, try this and see if they are still the same:</p> <pre><code>ticket.CacheId = new Guid("00000000-0000-0000-0000-" + string.Format("{0:000000000000}", i)); </code></pre>
<p>My gut is telling me something along these lines is going on...</p> <pre><code>class OrderTicket { Guid CacheId {set {_guid = new Guid("00000000-0000-0000-0000-");} } </code></pre> <p>Log the value of CacheId into a log file every time its called with a stack trace ... Maybe someone else is setting it. </p>
38,571
<p>I'm on a project which is trying to write what amounts to a Mailing List app in Django, and we're running into a couple of problems/questions.</p> <p>The code we have so far doesn't set various List headers, and re-sets the To header to be the person we're sending it to, instead of the list address.</p> <p>Now, we can work our way through all these fiddly little details, but I was wondering if anyone had any code which already did this sort of thing that we could crib from, so that we don't have to go through all the trial-and-error ourselves. Specific sections of RFCs that showed us what we should be sending would also be useful.</p> <p>Thanks,<br/> Blake.</p>
<p><a href="http://www.apps.ietf.org/rfc/rfc2919.html" rel="nofollow noreferrer">RFC 2919</a> has some info and more references on this.</p>
<p>Did you take a look at <a href="http://www.greatcircle.com/majordomo/" rel="nofollow noreferrer">majordomo</a>, or <a href="http://www.gnu.org/software/mailman/index.html" rel="nofollow noreferrer">mailman</a>?</p>
33,763
<p>I use codeigniter as my main install on the main domain. I have created a subdomain and a folder called live e.g. live.domain.com maps to public/live . However in public I use codeigniter.</p> <p>I now have the dynamic codeigniter url: </p> <pre>http://domain.com/api/</pre> <p>which I want to map to my subdomain: </p> <pre>https://live.domain.com</pre> <p>So going to:</p> <pre>https://live.domain.com/api/functioname</pre> <p>would be using the script: </p> <pre>http://domain.com/api/apifunctioname</pre> <p>and possibly:</p> <pre>http://domain.com/api/apifunctioname/parameter1/parameter</pre> <p>Everything is on the same server so no redirects are needed.</p> <p>Anyone have any ideas on which rewrite rules to use?</p> <pre><code>Options +FollowSymLinks RewriteEngine On RewriteCond %{HTTP_HOST} ^live\.domain\.com [NC] RewriteRule (.+)$ "http://domain.com/api/$1" [L] </code></pre> <p>The above works great as a rewrite but redirects to <a href="http://domain.com/api/functionname" rel="noreferrer">http://domain.com/api/functionname</a> instead I want it to route; so that when going to:</p> <pre>https://live.domain.com/api/functioname</pre> <p>It stays at that url but uses the script of </p> <pre>http://domain.com/api/functionname</pre> <p>Thank you very much,</p> <p>Ice</p>
<p>How about something like the following:</p> <pre> RewriteEngine On RewriteCond %{HTTP_HOST} ^live\.domain\.com$ [NC] RewriteRule (.+)$ "https://domain.com/api/$1" [L,P] </pre>
<p>Just add index.php, see below</p> <pre><code>RewriteEngine On RewriteCond %{HTTP_HOST} ^live\.domain\.com$ [NC] RewriteRule (.+)$ "https://domain.com/index.php/api/$1" [L,P] </code></pre>
47,842
<p>I've been using user controls extensively but never use a HttpHandler and was wondering if I am doing something suboptimal or wrong</p>
<p>Unfortunately your question is a little like "Should I use a sandwich or a cement mixer". HttpHandlers and User controls are completely different things.</p> <p>HttpHandlers are used to process HTTP requests. For example, if you wanted to dynamically create an RSS feed, you could write an HTTP handler that handles all requests for ".rss" files, creates the output and sends it back to the user.</p> <p>User controls are used within ASPX pages to encapsulate units of functionality that you want to re-use accross many pages.</p> <p>Chances are, if you're using user controls successfully, you don't want to use HttpHandlers!</p>
<p>Even an <code>Asp.Net</code> page is an <code>HttpHandler</code>.</p> <pre><code>public class Page : TemplateControl, IHttpHandler </code></pre> <p>A user control actually resides within the asp.net aspx page.</p>
4,216
<p>On the web page, it looks like there is no current development in the old style .doc.</p> <ul> <li>Is it good enough to create complex documents? </li> <li>Can it read all .docs without crashing?</li> <li>What features do (not) work?</li> </ul> <p>I am not currently interested in the XML based formats, as I don't control the client side. </p> <p>The excel support seems to be much better.</p>
<p>If you are looking for programmatically reading or writing doc files, I believe you're better of with remoting OpenOffice or StarOffice. We've done this at a former company, even though it's a pretty heavy solution, it worked quite well. OpenOffice has (right after Word) a very good doc-Support. For remoting it's a lot better than Word itself. At said company we (earlier) used to remotecontrol Word with frequent problems because Word (on saving a document) insisted on displaying a warning dialog from time to time. Bad idea on a server deep down in some datacenter with nobody close to it.</p> <p>As this was a Java shop, the very good OpenOffice support for Java came in handy. In fact, they even used to bundle the commercial version StarOffice and had some very good contacts at and help from Sun.</p> <p>Disclaimer: As andHapp and alepuzio said, POI is very good in Excel support and I'm using it with big success. Last time I've seen the doc support, I didn't dare using it in production (for customers). I haven't looked at doc support for at least two years.</p>
<p>I have used the Apache POI For reading and writing Excel files (.xls) and it works like a charm. There were a few issues but I found easy workarounds so I assume it would be the same for the word documents. The only issue you would have is with reading and writing the .docx (.xlsx in my case) format since Apache POI does not support them yet.</p>
46,975
<p>What are the best practices for modeling inheritance in databases?</p> <p>What are the trade-offs (e.g. queriability)?</p> <p>(I'm most interested in SQL Server and .NET, but I also want to understand how other platforms address this issue.)</p>
<p>There are several ways to model inheritance in a database. Which you choose depends on your needs. Here are a few options:</p> <p><strong>Table-Per-Type (TPT)</strong></p> <p>Each class has its own table. The base class has all the base class elements in it, and each class which derives from it has its own table, with a primary key which is also a foreign key to the base class table; the derived table's class contains only the different elements.</p> <p>So for example:</p> <pre><code>class Person { public int ID; public string FirstName; public string LastName; } class Employee : Person { public DateTime StartDate; } </code></pre> <p>Would result in tables like:</p> <pre><code>table Person ------------ int id (PK) string firstname string lastname table Employee -------------- int id (PK, FK) datetime startdate </code></pre> <p><strong>Table-Per-Hierarchy (TPH)</strong></p> <p>There is a single table which represents all the inheritance hierarchy, which means several of the columns will probably be sparse. A discriminator column is added which tells the system what type of row this is.</p> <p>Given the classes above, you end up with this table:</p> <pre><code>table Person ------------ int id (PK) int rowtype (0 = "Person", 1 = "Employee") string firstname string lastname datetime startdate </code></pre> <p>For any rows which are rowtype 0 (Person), the startdate will always be null.</p> <p><strong>Table-Per-Concrete (TPC)</strong></p> <p>Each class has its own fully formed table with no references off to any other tables.</p> <p>Given the classes above, you end up with these tables:</p> <pre><code>table Person ------------ int id (PK) string firstname string lastname table Employee -------------- int id (PK) string firstname string lastname datetime startdate </code></pre>
<p>You would normalize of your database and that would actually mirror your inheritance. It might have performance degradance, but that's how it is with normalizing. You probably will have to use good common sense to find the balance.</p>
23,094
<p>Could anyone recommend to me a good online guide to PowerPoint VBA? Also, does anyone has advice on how to record a macro in PowerPoint? </p>
<p>To record a powerpoint macro:</p> <ol> <li>In the menu bar, click on Tools</li> <li>Mouse over Macro > and the submenu will be displayed</li> <li>Click the Record button - a new toolbar will be displayed</li> <li>Do your thing</li> <li>Click the stop button on the new macro toolbar</li> </ol> <p>Click on Tools->Macro->Macros. Find the macro you just recorded and click the Edit button. That will show you what was recorded. Make your modifications and click the triangular run button (or push F5) to run your code.</p> <p>As far as an online guide, I usually think of a question and use <a href="http://www.google.com/" rel="nofollow noreferrer">Google</a> or ask a question here on StackOverflow.com. I've been able to answer most of my questions that way, I haven't found a particular main resource for all things Powerpoint VBA.</p> <p>Also, you can find answers that can help you by looking into VBA articles for other MS Office products - a lot of things that are not Powerpoint-specific (general VBA) will be the same as for the other products.</p>
<p>To record a powerpoint macro:</p> <ol> <li>In the menu bar, click on Tools</li> <li>Mouse over Macro > and the submenu will be displayed</li> <li>Click the Record button - a new toolbar will be displayed</li> <li>Do your thing</li> <li>Click the stop button on the new macro toolbar</li> </ol> <p>Click on Tools->Macro->Macros. Find the macro you just recorded and click the Edit button. That will show you what was recorded. Make your modifications and click the triangular run button (or push F5) to run your code.</p> <p>As far as an online guide, I usually think of a question and use <a href="http://www.google.com/" rel="nofollow noreferrer">Google</a> or ask a question here on StackOverflow.com. I've been able to answer most of my questions that way, I haven't found a particular main resource for all things Powerpoint VBA.</p> <p>Also, you can find answers that can help you by looking into VBA articles for other MS Office products - a lot of things that are not Powerpoint-specific (general VBA) will be the same as for the other products.</p>
15,455
<p>Our company has thousands of PDF documents. How do we create a simple search engine using Lucene, Solr or Nutch? We'll provide a basic Java/JSP web page were people can type in words and perform basic and/or queries then show them the document links of all matching PDF's.</p>
<p>I have had good luck with lucene, but it is not click, install and search, it does require a bit of work.<br> If you need something that yo can download and install and be searching within 10 minutes, look at the free Ominifind Yahoo Edition <a href="http://omnifind.ibm.yahoo.net/" rel="nofollow noreferrer">http://omnifind.ibm.yahoo.net/</a>, it uses Lucene, but is packaged such that it is configured and ready to run upon install, a much easier way to try Lucene.</p>
<p>Having the (imho) distinct advantage of being on a Mac, I use <a href="http://www.gravityapps.com/searchlight/overview/" rel="nofollow noreferrer">SearchLight</a> on a somewhat older G5. nice web interface to spotlight, the Mac OS' built-in indexing service.</p>
27,603
<p>I admit that I am not a guru of Visual Studio products at all. I am using Visual Web Developer 2005 Express Edition and I'm trying to load someone else's project.</p> <p>This project happens to be a website with many pages.</p> <p>After loading VWD, it asks for a project to open and I select the solution file. It then proceeds to take an extremely long time to load. The status bar indicates that references are being loaded, many of which are in the System.Web.* area it seems. It seems like it's going back and forth between some different packages. The loading time is upwards of 20 to 30 minutes or more. Some others have stated that their projects open fine when they go to File > Open Website... and choose the project directory from there. Any ideas what the problem could be and how to fix it?</p> <p>Edit: It finally completed loading after an hour approximately.</p>
<p>The fundemental problem is the impact of Response.Codepage on Form Posts.</p> <p>When you send a form to a client specifying that the content is encoded as UTF-8, the browser will assume that the content of form posts should be sent encoded as UTF-8.</p> <p>Now the action page that receives the post will (somewhat counter-intuatively) use the value of <strong><code>Response.Codepage</code></strong> to inform it how the characters in the post are encoded. This isn't obvious because we tend to think its the job of the sender to define the encoding of what its sending. Also it isn't a natural leap to think that a property to do with the encoding of what we want to send in our response would have anything to do with how the initial a request is received. In this case it does.</p> <p>Whats happening is your form is posting a UTF-8 encoded version of the character but the page that receives does not have its Response.Codepage set to 65001 (the UTF-8 codepage). Its probably set to the systems OEM codepage like 1252. Hence the UTF-8 encoding for the character gets interpreted as two individual characters.</p> <p>My recommendations for good character handling in ASP are:-</p> <ul> <li>Save all pages as UTF-8</li> <li>Include &lt;%@ codepage=65001 at the top of all pages</li> <li>Include &lt;% Response.CharSet = "UTF-8" %> at the top all pages</li> <li>Store posted data in a unicode field type such as SQL Servers NVARCHAR type.</li> </ul> <p>The important thing here is that before you read form values in an ASP page you need to make sure that the Response.Codepage is set to a codepage that matches the senders encoding and this doesn't happen automatically.</p>
<p>® is what ® looks like if it's stored as UTF-8, but displayed as ASCII/ISO-8859-1/Windows-1252. Using the <code>meta</code> tag is not enough to make sure your page is being served as UTF-8. You will also need to set the encoding in the Content-Type HTTP header. This header is typically set either with some server-wide setting or programatically.</p> <p>I don't know ASP, but this seems to be how you should set that header:</p> <p><a href="https://stackoverflow.com/questions/250609/htmlencode-utf-8">HtmlEncode UTF-8</a></p> <p>And this might provide some more information:</p> <p><a href="http://technet.microsoft.com/en-us/library/bb742422.aspx#EBAA" rel="nofollow noreferrer">http://technet.microsoft.com/en-us/library/bb742422.aspx#EBAA</a></p> <p>If your data is stored in a database, you'll also need to make sure the data is either stored in UTF-8 as well, or converted when storing and retrieving it.</p>
45,615
<p>What does it mean when it gives a backtrace with the following output?</p> <pre><code>#0 0x00000008009c991c in pthread_testcancel () from /lib/libpthread.so.2 #1 0x00000008009b8120 in sigaction () from /lib/libpthread.so.2 #2 0x00000008009c211a in pthread_mutexattr_init () from /lib/libpthread.so.2 #3 0x0000000000000000 in ?? () </code></pre> <p>The program has crashed with a standard signal 11, segmentation fault. My application is a multi-threaded FastCGI C++ program running on FreeBSD 6.3, using pthread as the threading library.</p> <p>It has been compiled with -g and all the symbol tables for my source are loaded, according to info sources.</p> <p>As is clear, none of my actual code appears in the trace but instead the error seems to originate from standard pthread libraries. In particular, what is ?? () ????</p> <p><b>EDIT</b>: eventually tracked the crash down to a standard invalid memory access in my main code. Doesn't explain why the stack trace was corrupted, but that's a question for another day :)</p>
<p>gdb wasn't able to extract the proper return address from pthread_mutexattr_init; it got an address of 0. The "??" is the result of looking up address 0 in the symbol table. It cannot find a symbolic name, so it prints a default "??"</p> <p>Unfortunately right offhand I don't know why it could not extract the correct return address.</p>
<p>Maybe the bug that caused the crash has broken the stack (overwritten parts of the stack)? In that case, the backtrace might be useless; no idea what to do in that case...</p>
14,760
<p>I'm currently designing a brand new database. In school, we always learned to put a primary key in each table.</p> <p>I read a lot of articles/discussions/newsgroups posts saying that it's better to use unique constraint (aka unique index for some db) instead of PK.</p> <p>What's your point of view?</p>
<p>Can you provide references to these articles?</p> <p>I see no reason to change the tried and true methods. After all, Primary Keys are a fundamental design feature of relational databases.</p> <p>Using UNIQUE to serve the same purpose sounds really hackish to me. What is their rationale?</p> <p>Edit: My attention just got drawn back to this old answer. Perhaps the discussion that you read regarding PK vs. UNIQUE dealt with people making something a PK for the sole purpose of enforcing uniqueness on it. The answer to this is, If it IS a key, then make it key, otherwise make it UNIQUE. </p>
<p>If you plan on using LINQ-to-SQL, your tables will require Primary Keys if you plan on performing updates, and they will require a <code>timestamp</code> column if you plan on working in a disconnected environment (such as passing an object through a WCF service application).</p> <p>If you like .NET, PK's and FK's are your friends.</p>
19,156
<p>I have a few combo-boxes and double spin boxes on my Qt Dialog. Now I need a "ResetToDefault" item on a menu that comes up when you right click on the widget (spin box or combo box).</p> <p>How do i get it. Is there some way I can have a custom menu that comes up on right click or Is there a way i can add items to the menu that comes on right click.</p>
<p>First, for Qt4, the simplest way is to create an action to reset the data, and add it the the widget using the <code>addAction</code> method (or use the designer). Then, set the <code>contextMenuPolicy</code> attribute to <code>Qt::ActionsContextMenu</code>. The context menu will appear and the action will be triggered.</p> <p>Code example:</p> <pre><code>QAction *reset_act = new QAction("Reset to default"); mywidget-&gt;addAction(reset_act); mywidget-&gt;setContextMenuPolicy(Qt::ActionsContextMenu); // here connect the 'triggered' signal to some slot </code></pre> <p>For Qt3, you might have to intercept the context menu event, and thus inherit the QSpinBox and others. Or maybe you can intercept the context menu event from the main window, detect if it occurred above the widget supposed to have a context menu (using the <code>QWidget::childAt</code> method) and show it there. But you'll have to test.</p>
<p>For Qt4, you can do this for an editable QComboBox by using your own QLineEdit. Create a derived QLineEdit class which implements the contextMenuEvent</p> <pre><code>class MyLineEdit : public QLineEdit { Q_OBJECT public: MyLineEdit(QWidget* parent = 0) : QLineEdit(parent){} void contextMenuEvent(QContextMenuEvent *event) { QPointer&lt;QMenu&gt; menu = createStandardContextMenu(); //add your actions here menu-&gt;exec(event-&gt;globalPos()); delete menu; } }; </code></pre> <p>Then, use the setLineEdit function of QComboBox to set the line edit</p> <pre><code>MyLineEdit* edit = new MyLineEdit(); comboBox-&gt;setLineEdit(edit); </code></pre> <p>The combo box will now use your line edit class. The createStandardContextMenu function creates the normal context menu and you can add any new actions to it that you like in the contextMenuEvent handler before it is shown. </p> <p>If the QComboBox is not editable then it doesn't have a default context menu so using the Qt::ActionsContextMenu method is much simpler.</p> <p>QAbstractSpinBox also has a setLineEdit function so you can use a similar technique. Although, for some reason the setLineEdit function is protected on QAbstractSpinBox but public on QLineEdit. </p>
23,173
<p>I'm writing an ASP.Net webform with some DropDownList controls on it. Then user changes selected item in one of dropdowns, ASP.Net doesn't seem to handle SelectedIndexChanged event until form is submitted with a 'Submit' button click. How do I make my dropdowns handle SelectedIndexChanged instantly?</p> <p>P.S. It's a classic question I have answered too many times, but it seems no one asked it before on stackoverflow.</p>
<p>Setting the <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listcontrol.autopostback(VS.71).aspx" rel="noreferrer">AutoPostback</a> property to true will cause it to postback when the selection is changed. Please note that this requires javascript to be enabled.</p>
<p>Set the AutoPostBack property of DropDownList to true.</p>
9,551
<p>I am extremely new at php and I was wondering if someone could help me use either a <code>for()</code> or <code>while()</code> loop to create an array of 10 elements.</p>
<pre><code>$array = array(); $array2 = array(); // for example for ($i = 0; $i &lt; 10; ++$i) { $array[] = 'new element'; } // while example while (count($array2) &lt; 10 ) { $array2[] = 'new element'; } print "For: ".count($array)."&lt;br /&gt;"; print "While: ".count($array2)."&lt;br /&gt;"; </code></pre>
<p>The simplest way is to use <a href="http://www.php.net/array_fill" rel="nofollow noreferrer"><code>array_fill()</code></a>:</p> <pre><code>$array = array_fill(0, 10, 'Hello World'); </code></pre> <p>But you should know that PHP arrays can be resized whenever you want anyway, I've never needed to create an array of a certain size.</p>
35,846
<p>How does Google's API make cross-domain requests back to Google, when it's on your website?</p>
<p>They get around it by dynamically injecting script tags into the head of the document. The javascript that is sent down via this injection has a callback function in it that tells the script running in the page that it has loaded and the payload (data). </p> <p>The script can then remove the dynamically injected script tag and continue.</p>
<p>Another possibility is to use the <code>window.name</code> transport as described for the dojo framework <a href="http://www.sitepen.com/blog/2008/07/22/windowname-transport/" rel="nofollow noreferrer">here</a></p>
15,693
<p>Is there any way to throw errors or warnings in a KornShell (ksh) script to prevent the use of unset variables? Let's assume I have a temporary folder that I want to remove.</p> <pre><code>TEMP_FILES_DIR='/app/myapp/tmp' rm -Rf $TEMP_FILE_DIR #notice the misspelling </code></pre> <p>How to prevent this kind of mistakes before they actually happen?</p> <p>I know the script should check for file existence and empty string before attempting to remove, this is just a silly example to illustrate a mistake that could have been avoided with some warnings. I don't know if this feature exists in ksh. If it does exist, how do you turn it on?</p>
<p>The command</p> <pre>set -u</pre> <p>Will cause POSIX <i>sh</i>(1) and its derivatives to grouse when an attempt to expand an unset variable is made.</p> <p>Example:</p> <pre> $ echo $foo $ set -u $ echo $foo sh: foo: parameter not set </pre>
<p>You could check the variable for having content, ie not being '', and print-out a message like "the variable is empty".</p> <p>However, that's still not going to fix PEBCAK errors like this - all you'd know is that nothing happened.</p>
42,140
<p>I have a <code>MultipleChoiceField</code> on a form holding car makes. I want to filter my database of cars to the makes that were checked but this causes a problem. How do I get all the <code>Q(make=...)</code> statements in dynamically?</p> <p>How I start: <code>['value1', 'value2', ...]</code></p> <p>How I want to end: <code>Q(col='value1') | Q(col='value2') | ...</code></p> <p>I've couple of other methods. I've tried appending querysets for each make and doing it the other way around (doing multiple excludes) but they were both really slow.</p>
<p>Have you tried: <code>Model.objects.filter(make__in=list_of_makes)</code> ?</p> <p>The list_of_makes is what is returned by the <code>MultipleChoiceField</code></p> <p>See <a href="http://docs.djangoproject.com/en/dev/ref/models/querysets/#in" rel="noreferrer">the query set reference</a> about the <code>__in</code> operator.</p>
<p>There was another method provided in #django:</p> <pre><code>reduce(lambda x,y: x | y, [Q1, Q2, Q3, ...]) </code></pre> <p><a href="https://stackoverflow.com/questions/352178/django-dynamic-or-queries#352208">Ber's method</a> is great for this instance but if you need to filter on dynamic columns, mapping looks like the next cleanest way.</p>
45,860
<p>I have a class that looks like this:</p> <pre><code>public class TextField : TextBox { public bool Required { get; set; } RequiredFieldValidator _validator; protected override void CreateChildControls() { base.CreateChildControls(); _validator = new RequiredFieldValidator(); _validator.ControlToValidate = this.ID; if(Required) Controls.Add(_validator); } public override void Render(HtmlTextWriter tw) { base.Render(tw); if(Required) _validator.RenderControl(tw); } } </code></pre> <p>This has been working for a while in a internal application where javascript is always enabled. I recently noticed that an upstream javascript error can prevent the validators from firing, so the server side validation should kick in... right? right?</p> <p>So the Page.IsValid property always returns true (I even tried explicitly calling Page.Validate() before-hand). </p> <p>After some digging, I found that the validator init method should add the validator to the page, but due to the way I'm building it up, I don't think this ever happens. Thus, client side validation works, but server side validation does not.</p> <p>I've tried this:</p> <pre><code>protected override OnInit() { base.OnInit(); Page.Validators.Add(_validator); // &lt;-- validator is null here } </code></pre> <p>But of course the validator is null here (and sometimes it's not required so it shouldn't be added)... but OnInit() is really early for me to make those decisions (the Required property won't have been loaded from ViewState for example).</p> <p>Ideas?</p>
<p>The CreateChildControls is basically for the controls that have childs. RequiredFieldValidator is like a sibling to TextBox. </p> <p>Here is the code that works for me: </p> <pre><code>public class RequiredTextBox : TextBox { private RequiredFieldValidator _req; private string _errorMessage; public string ErrorMessage { get { return _errorMessage; } set { _errorMessage = value; } } protected override void OnInit(EventArgs e) { _req = new RequiredFieldValidator(); _req.ControlToValidate = this.ID; _req.ErrorMessage = _errorMessage; Controls.Add(_req); base.OnInit(e); } protected override void Render(System.Web.UI.HtmlTextWriter writer) { base.Render(writer); _req.RenderControl(writer); } } </code></pre> <p>And here it the ASP.NET page behind: </p> <pre><code> protected void SubmitClick(object sender, EventArgs e) { if(Page.IsValid) { // do something } } </code></pre> <p>And here is the ASPX code: </p> <pre><code> &lt;MyControl:RequiredTextBox runat="server" ErrorMessage="Name is required!" ID="txtName"&gt;&lt;/MyControl:RequiredTextBox&gt; &lt;asp:Button ID="Btn_Submit" runat="server" Text="Submit" OnClick="SubmitClick" /&gt; </code></pre>
<p>Validators have to inherit from BaseValidator.</p>
38,807
<p>I am working on a ASP.net application written in C# with Sql Server 2000 database. We have several PDF reports which clients use for their business needs. The problem is these reports take a while to generate (> 3 minutes). What usually ends up happening is when the user requests the report the request timeout kills the request before the web server has time to finish generating the report, so the user never gets a chance to download the file. Then the user will refresh the page and try again, which starts the entire report generation process over and still ends up timing out. (No we aren't caching reports right now; that is something I am pushing hard for...).</p> <p>How do you handle these scenarios? I have an idea in my head which involves making an aysnchronous request to start the report generating and then have some javascript to periodically check the status. Once the status indicates the report is finished then make a separate request for the actual file.</p> <p>Is there a simpler way that I am not seeing?</p>
<p>Using the filesystem here is probably a good bet. Have a request that immediately returns a url to the report pdf location. Your server can then either kick off an external process or send a request to itself to perform the reporting. The client can poll the server (using http HEAD) for the PDF at the supplied url. If you make the filename of the PDF derive from the report parameters, either by using a hash or directly putting the parameters into the name you will get instant server side caching too.</p>
<p>What about emailing the report to the user. All the asp page should do is send the request to generate the report and return a message that the report will be emailed after is has finished running.</p>
19,059
<p>I need to generate a CTL for use with IIS7.</p> <p>I generated a CTL file using MakeCTL (on Win2k3 SDK) and put only my own RootCA certificate in the CTL.</p> <p>However, when I then use adsutil.vbs to set my website to use this CTL, I get:</p> <p>ErrNumber: -2147023584 (0x80070520) Error Trying To SET the Property: SslCtlIdentifier</p> <p>I'm using adsutil.vbs like this:</p> <p>cscript adsutil.vbs set w3svc/2/SslCtlIdentifier where is the friendly name of the CTL</p> <p>The problem is, I am not able to set a friendly name. At the end of the wizard it says "Friendly Name: ".</p> <p>In IIS6 I can create a CTL with a friendly name (showing in Certificates MMC) but if I export it from there, when I import it, it no longer has a friendly name.</p> <p>Can anyone show me how to do it please?</p>
<p>I'm experiencing exactly the same problem and am having the same trouble finding an answer.</p> <p>There appears to be no documented way to create a friendly name for Certificate Trust Lists using MakeCTL. And the only documented way to add a CTL to IIS7 uses the adsutil script Neil references above, yet it requires a friendly name. I assume we could dig into a programatic way to do this but I'm not looking to get that deep.</p> <p>The core of this problem is that IIS7 seems to have lost favor for CTL's, else it would have some UI support for them. Are people using some alternative to CTL's in combination with Client Side Certificates?</p> <p>I find it odd this isn't a bigger problem for IIS7.</p> <p><strong>Update:</strong> I finally came back to this and have figured out the Friendly Name issue. To get a friendly name assigned you must store the CTL in the Certificate Store rather than to a file (I had always used the file approach previously). So, using MakeCTL in the wizard mode (no arguments) and choosing to 'Certificate Store' on the 'Certificate Trust List Storage' page results in a new page that let's you specify a Friendly Name.</p> <p>So I now have a CTL in the 'Intermediate Certification Authorities' certificate store of LocalMachine. Now I am trying to use 'netsh http add sslcert' to assign the CTL to my site.</p> <p>Before I could use this command I had to remove the existing SSL cert that was assigned to my site for server authentication. Then in my netsh command I specify the thumbprint of that very same SSL cert I removed, plus a made up appid, plus 'sslctlidentifier=MyCTL sslctlstorename=CA'. The resulting command is:</p> <p><strong>netsh http add sslcert ipport=10.10.10.10:443 certhash=adfdffa988bb50736b8e58a54c1eac26ed005050 appid={ffc3e181-e14b-4a21-b022-59fc669b09ff} sslctlidentifier=MyCTL sslctlstorename=CA</strong></p> <p>(the IP addr is munged), but I am getting this error:</p> <p><strong>SSL Certificate add failed, Error: 1312 A specified logon session does not exist. It may already have been terminated.</strong></p> <p>I am sure the error is related to the CTL options because if I remove them it works (though no CTL is assigned of course).</p> <p>Can anyone help me take this last step and make this work?</p> <p><strong>UPDATE 01-07-2010:</strong> I never resolved this with IIS 7.0 and have since migrated our app to IIS 7.5 and am giving this another try. I installed IIS6 Compatibility on my test server and tried the steps documented <a href="http://learn.iis.net/page.aspx/131/compatibility-and-feature-requirements-for-windows-vista/#NoWizard" rel="nofollow noreferrer">here</a> using adsutil.vbs. I immediately ran into this same error that Niel did above:</p> <p>ErrNumber: -2147023584 Error trying to SET the Property: SslCtlIdentifier</p> <p>when running this command:</p> <p>adsutil.vbs set w3svc/1/SslCtlIdentifier MyFriendlyName</p> <p>I then went on to try the next adsutil.vbs command documented and it failed with the same error.</p> <p>I have verified that the CTL I created has a Friendly Name of MyFriendlyName and that it exists in the 'Intermediate Certification Authorities\Certificate Trust List' store of LocalComputer.</p> <p>So once again I am at a dead standstill. I don't know what else to try. Has anyone ever gotten CTL's to work with IIS7 or 7.5? Ever? Am I beating a DEAD horse. Google turns up nothing but my own posts and other similar stories.</p> <p><strong>Update 6/08/10</strong> - I can now confirm that KB981506 resolves this issue. There is a patch associated with this KB that must be applied to Server 2008 R2 machines to enable this functionality. Once that is installed all works flawlessly for me.</p>
<p>The question is about IIS7, but for anyone looking for this information - from <strong>IIS8</strong> you no longer need to use CTLs, but rather use "Client Authentication Issuers" in the certificate store. </p> <p>This is documented in more detail: <a href="http://technet.microsoft.com/en-us/library/hh831771.aspx" rel="nofollow">http://technet.microsoft.com/en-us/library/hh831771.aspx</a></p>
42,206
<p>I'm thinking about trying out MVC later today for a new app we're starting up, but I'm curious if it's an all or nothing thing or if I can still party like it's 2006 with viewstate and other crutches at the same time...</p>
<p>Yes you can have your webforms pages and MVC views mixed in a single web application project. This could be useful if you have an application that is already built and you want to migrate your app from webforms to mvc.</p> <p>You need to make sure that none of your webforms pages go in the 'Views' directory in a standard ASP.NET MVC application though. Pages (or views) in the 'Views' directory can't be requested directly through the url.</p> <p>If you are starting an application from scratch, there would be very little benefit to mixing the two.</p>
<p>If you're mixing MVC with other methodologies you're not really getting the benefit out of it. The point of MVC is to allow you to decrease coupling and increase cohesion, and if only half of your code is doing that, then the other half is inevitably going to restrain your development cycle.</p> <p>So, I guess while it's possible, I don't think it's worth it. Go all the way or don't go at all.</p>
16,085