instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>In particular, wouldn't there have to be some kind of function pointer in place anyway? </p>
<p>Non virtual member functions are really just a syntactic sugar as they are almost like an ordinary function but with access checking and an implicit object parameter.</p> <pre><code>struct A { void foo (); void bar () const; }; </code></pre> <p>is basically the same as:</p> <pre><code>struct A { }; void foo (A * this); void bar (A const * this); </code></pre> <p>The vtable is needed so that we call the right function for our specific object instance. For example, if we have:</p> <pre><code>struct A { virtual void foo (); }; </code></pre> <p>The implementation of 'foo' might approximate to something like:</p> <pre><code>void foo (A * this) { void (*realFoo)(A *) = lookupVtable (this-&gt;vtable, "foo"); (realFoo)(this); // Make the call to the most derived version of 'foo' } </code></pre>
<p>There's no need for function pointers as it cant change during the runtime.</p>
12,678
<p>I have an application that writes information to file. This information is used post-execution to determine pass/failure/correctness of the application. I'd like to be able to read the file as it is being written so that I can do these pass/failure/correctness checks in real time.</p> <p>I assume it is possible to do this, but what are the gotcha's involved when using Java? If the reading catches up to the writing, will it just wait for more writes up until the file is closed, or will the read throw an exception at this point? If the latter, what do I do then? </p> <p>My intuition is currently pushing me towards BufferedStreams. Is this the way to go?</p>
<p>Could not get the example to work using <code>FileChannel.read(ByteBuffer)</code> because it isn't a blocking read. Did however get the code below to work:</p> <pre><code>boolean running = true; BufferedInputStream reader = new BufferedInputStream(new FileInputStream( "out.txt" ) ); public void run() { while( running ) { if( reader.available() &gt; 0 ) { System.out.print( (char)reader.read() ); } else { try { sleep( 500 ); } catch( InterruptedException ex ) { running = false; } } } } </code></pre> <p>Of course the same thing would work as a timer instead of a thread, but I leave that up to the programmer. I'm still looking for a better way, but this works for me for now.</p> <p>Oh, and I'll caveat this with: I'm using 1.4.2. Yes I know I'm in the stone ages still.</p>
<p>I've never tried it, but you should write a test case to see if reading from a stream after you have hit the end will work, regardless of if there is more data written to the file.</p> <p>Is there a reason you can't use a piped input/output stream? Is the data being written and read from the same application (if so, you have the data, why do you need to read from the file)?</p> <p>Otherwise, maybe read till end of file, then monitor for changes and seek to where you left off and continue... though watch out for race conditions.</p>
2,613
<p>I've inherited a ASP/VB6 code base (not my forte... yet) and I'm trying tease it apart to figure out the cause on an error message I'm receiving when running the app.</p> <p>I've traced it back through an event that is being raised in on of my classes. Is there away in windows I can search the bulk of the code base for where it is being consumed? Ctrl-F (and selecting Current Project) has not sufficed.</p> <p>The linux geek in me is saying dump it to a <em>insert distro</em> box and just grep for the sucker. But there's got to be some way in the IDE to do it... right?</p>
<blockquote> <p>But there's got to be some way in the IDE to do it... right?</p> </blockquote> <p>No. There are some plugins for the IDE, such as the <a href="http://www.mztools.com/" rel="nofollow noreferrer">MZ Tools</a> that <em>might</em> help. Otherwise, just use the <code>find</code> tool from the Windows command line. Not nearly as comfortable as using <code>grep</code>, of course.</p>
<p>I have a large legacy code-base in VB6 which needs maintenance from time to time and I have used Microsoft Desktop Search on my local copy to help find variable and method names across the code files.</p> <p>Also <a href="http://www.interlog.com/~tcharron/grep.html" rel="nofollow noreferrer">Grep</a> is available for Windows.</p>
33,013
<p>I noticed that one edge (which is also the starting point of the print) is always bigger than the other three. Additionally, the walls do not have the same thickness as well. The wall thickness (starting from the thick edge) starts very thin and gets thicker till reaching the thick edge again. Does anyone have a clue whats the issue?</p> <p><a href="https://i.stack.imgur.com/oeept.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oeept.png" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/CEvrT.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/CEvrT.jpg" alt="enter image description here"></a> <a href="https://i.stack.imgur.com/eZmxi.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eZmxi.jpg" alt="enter image description here"></a></p>
<p>As Fernando suggests, the problem is likely with your source file. One easy way to verify this is to slice twice, rotating the STL by 90 degrees. If both prints produce fat/thin sides in the same dimension on the print bed, then it's a printer problem. If the fat side rotated with the STL orientation, then the STL is at fault. </p>
<p>As Fernando suggests, the problem is likely with your source file. One easy way to verify this is to slice twice, rotating the STL by 90 degrees. If both prints produce fat/thin sides in the same dimension on the print bed, then it's a printer problem. If the fat side rotated with the STL orientation, then the STL is at fault. </p>
906
<p>Are there any tools available for calculating the <strong>average number of lines of code per method</strong>?</p> <p>I want to know the average size of each method, not just the total number of lines in the project. The per method count will allow me to measure how simple each method is.</p> <p>This will be calculated as part of the build process, and displayed on a dashboard. The idea being that we can see if the average size of each method is increasing. And this will flag the possibility that code complexity is increasing and we may need to think about refactoring.</p>
<p>short fast and dirty : grep for ";", count the number of lines, this will give you an estimate of the number of statements.</p>
<p>I am not sure if it does that, but searching, after your previous post, what is cyclomatic complexity, I went to the related Wikipedia page which pointed to <a href="http://www.geocities.com/sivaram_subr/codeanalyzer/description.htm" rel="nofollow noreferrer" title="Code Analyzer">Code Analyzer</a>. There they say:</p> <blockquote> <p>When counting for HTML or JSP files, it will count LoC correctly for javascript and vbscript code embedded within the &lt;script> tag.</p> </blockquote> <p>I don't know if this count is dispatched per method, but it might be worth taking a look (it is a free tool).</p>
12,594
<p>I have been trying to read a picture saved in Access DB as a OLE object in a PictureBox in a C# windows Application.</p> <p>The code that does this is presented below:</p> <pre><code> string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Rajesh\SampleDB_2003.mdb;"; OleDbConnection oConn = new OleDbConnection(connString); oConn.Open(); string commandString = "select * from employee where id = " + id + ""; OleDbCommand oCmd = new OleDbCommand(commandString, oConn); OleDbDataReader oReader = oCmd.ExecuteReader(CommandBehavior.SequentialAccess); while (oReader.Read()) { txtID.Text = ((int)oReader.GetValue(0)).ToString(); txtName.Text = (string)oReader.GetValue(1); txtAge.Text = ((int)oReader.GetValue(2)).ToString(); txtType.Text = (string)oReader.GetValue(3); byte[] imageBytes = (byte[])oReader.GetValue(4); MemoryStream ms = new MemoryStream(); ms.Write(imageBytes, 0, imageBytes.Length); Bitmap bmp = new Bitmap(ms); pbPassport.Image = bmp; } </code></pre> <p>When I execute the above code, an 'Parameter is not valid' exception is thrown at the line:</p> <pre><code>Bitmap bmp = new Bitmap(ms) </code></pre> <p>From the exception message, it is clear that 'ms' is in a format that is not recognisable. Any suggestion to get past this?</p>
<p>Unfortunately I have no good answer for you, but I can tell you that when I tried, I got the same results. Sometimes skipping the first 78 bytes of the byte array worked, sometimes it didn't.</p> <p>This is because the OLE Object datatype stores some kind of header in the field, so that Access knows what type of OLE Object it is. I could not find a reliable way to work out exactly where this header stopped and real data started, but I also gave up, so good luck :)</p>
<p>Your bytestream is corrupted somehow, becouse I tried the exact method of yours but filled the byte array with PNG data from a file instead.</p> <p>I would suggest creating two streams, one from the database, and one from the file that was the source of the image in the database. Then compare them byte by byte. If there is even one byte of diffrence, the database image data is corrupt.</p>
26,792
<p>When my browser renders the following test case, there's a gap below the image. From my understanding of CSS, the bottom of the blue box should touch the bottom of the red box. But that's not the case. Why?</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"&gt; &lt;head&gt; &lt;title&gt;foo&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div style="border: solid blue 2px; padding: 0px;"&gt; &lt;img alt='' style="border: solid red 2px; margin: 0px;" src="http://stackoverflow.com/Content/Img/stackoverflow-logo-250.png" /&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt;</code></pre> </div> </div> </p>
<p>Inline elements are vertically aligned to the baseline, not the very bottom of the containing box. This is because text needs a small amount of space underneath for descenders - the tails on letters like lowercase 'p'. So there is an imaginary line a short distance above the bottom, called the baseline, and inline elements are vertically aligned with it by default.</p> <p>There's two ways of fixing this problem. You can either specify that the image should be vertically aligned to the bottom, or you can set it to be a block element, in which case it is no longer treated as a part of the text.</p> <p>In addition to this, Internet Explorer has an HTML parsing bug that does not ignore trailing whitespace after a closing element, so removing this whitespace may be necessary if you are having problems with Internet Explorer compatibility.</p>
<p>Remove the line break before the tag, so that it directly follows the tag with no blanks between it.</p> <p>I don't know why, but for the Internet Explorer, this works.</p>
15,736
<p>I have a circular, statically allocated buffer in C, which I'm using as a queue for a <strike>depth</strike> breadth first search. I'd like have the top N elements in the queue sorted. It would be easy to just use a regular qsort() - except it's a circular buffer, and the top N elements might wrap around. I could, of course, write my own sorting implementation that uses modular arithmetic and knows how to wrap around the array, but I've always thought that writing sorting functions is a good exercise, but something better left to libraries.</p> <p>I thought of several approaches:</p> <ol> <li>Use a separate linear buffer - first copy the elements from the circular buffer, then apply qsort, then copy them back. Using an additional buffer means an additional O(N) space requirement, which brings me to <ul> <li>Sort the "top" and "bottom" halve using qsort, and then merge them using the additional buffer</li> <li>Same as 2. but do the final merge in-place (I haven't found much on in-place merging, but the implementations I've seen don't seem worth the reduced space complexity)</li> </ul></li> </ol> <p>On the other hand, spending an hour contemplating how to elegantly avoid writing my own quicksort, instead of adding those 25 (or so) lines might not be the most productive either...</p> <p><strong>Correction:</strong> Made a stupid mistake of switching DFS and BFS (I prefer writing a DFS, but in this particular case I have to use a BFS), sorry for the confusion.</p> <p><strong>Further description of the original problem:</strong></p> <p>I'm implementing a <strong>breadth</strong> first search (for something not unlike the <a href="http://en.wikipedia.org/wiki/Fifteen_puzzle" rel="nofollow noreferrer">fifteen</a> puzzle, just more complicated, with about O(n^2) possible expansions in each state, instead of 4). The "bruteforce" algorithm is done, but it's "stupid" - at each point, it expands all valid states, in a hard-coded order. The queue is implemented as a circular buffer (unsigned queue[MAXLENGTH]), and it stores integer indices into a table of states. Apart from two simple functions to queue and dequeue an index, it has no encapsulation - it's just a simple, statically allocated array of unsigned's.</p> <p>Now I want to add some heuristics. The first thing I want to try is to sort the expanded child states after expansion ("expand them in a better order") - just like I would if I were programming a simple best-first DFS. For this, I want to take part of the queue (representing the most recent expanded states), and sort them using some kind of heuristic. I could also expand the states in a different order (so in this case, it's not really important if I break the FIFO properties of the queue).</p> <p>My goal is not to implement <a href="http://en.wikipedia.org/wiki/A*_search_algorithm" rel="nofollow noreferrer">A*</a>, or a depth first search based algorithm (I can't afford to expand all states, but if I don't, I'll start having problems with infinite cycles in the state space, so I'd have to use something like <a href="http://en.wikipedia.org/wiki/Iterative_deepening_depth-first_search" rel="nofollow noreferrer">iterative deepening</a>).</p>
<p>I think you need to take a big step back from the problem and try to solve it as a whole - chances are good that the semi-sorted circular buffer is not the best way to store your data. If it is, then you're already committed and you will have to write the buffer to sort the elements - whether that means performing an occasional sort with an outside library, or doing it when elements are inserted I don't know. <strong>But at the end of the day it's going to be ugly because a FIFO and sorted buffer are fundamentally different.</strong></p> <hr> <p><em>Previous answer, which assumes your sort library has a robust and feature filled API (as requested in your question, this does not require you to write your own mod sort or anything - it depends on the library supporting arbitrary located data, usually through a callback function. If your sort doesn't support linked lists, it can't handle this):</em></p> <p>The circular buffer has already solved this problem using % (mod) arithmetic. QSort, etc don't care about the locations in memory - they just need a scheme to address the data in a linear manner.</p> <p>They work as well for linked lists (which are not linear in memory) as they do for 'real' linear non circular arrays.</p> <p>So if you have a circular array with 100 entries, and you find you need to sort the top 10, and the top ten happen to wrap in half at the top, then you feed the sort the following two bits of information:</p> <ul> <li>The function to locate an array item is (x % 100)</li> <li>The items to be sorted are at locations 95 to 105 </li> </ul> <p>The function will convert the addresses the sort uses into an index used in the real array, and the fact that the array wraps around is hidden, although it may look weird to sort an array past its bounds, a circular array, by definition, has no bounds. The % operator handles that for you, and you might as well be referring to the part of the array as 1295 to 1305 for all it cares.</p> <p>Bonus points for having an array with 2^n elements.</p> <hr> <h2>Additional points of consideration:</h2> <p>It sounds to me that you're using a sorting library which is incapable of sorting anything other than a linear array - so it can't sort linked lists, or arrays with anything other than simple ordering. You really only have three choices:</p> <ul> <li>You can re-write the library to be more flexible (ie, when you call it you give it a set of function pointers for comparison operations, and data access operations)</li> <li>You can re-write your array so it somehow fits your existing libraries</li> <li>You can write custom sorts for your particular solution.</li> </ul> <p>Now, for my part I'd re-write the sort code so it was more flexible (or duplicate it and edit the new copy so you have sorts which are fast for linear arrays, and sorts which are flexible for non-linear arrays)</p> <p>But the reality is that right now your sort library is so simple you can't even tell it how to access data that is non linearly stored. </p> <p>If it's that simple, there should be no hesitation to adapting the library itself to your particular needs, or adapting your buffer to the library.</p> <p>Trying an ugly kludge, like somehow turning your buffer into a linear array, sorting it, and then putting it back in is just that - an ugly kludge that you're going to have to understand and maintain later. You're going to 'break' into your FIFO and fiddle with the innards.</p> <p>-Adam</p>
<p>How about somthing like this example here. This example easely sorts a part or whatever you want without having to redefine a lot of extra memory. It takes inly two pointers a status bit and a counter for the for loop.</p> <pre><code>#define _PRINT_PROGRESS #define N 10 BYTE buff[N]={4,5,2,1,3,5,8,6,4,3}; BYTE *a = buff; BYTE *b = buff; BYTE changed = 0; int main(void) { BYTE n=0; do { b++; changed = 0; for(n=0;n&lt;(N-1);n++) { if(*a &gt; *b) { *a ^= *b; *b ^= *a; *a ^= *b; changed = 1; } a++; b++; } a = buff; b = buff; #ifdef _PRINT_PROGRESS for(n=0;n&lt;N;n++) printf("%d",buff[n]); printf("\n"); } #endif while(changed); system( "pause" ); } </code></pre>
35,616
<p>On a Use Case diagram can you show things that an actor <strong>cannot</strong> do, for example because they won't have permissions to do it?</p> <p>Or is it just implied due to the fact that they won't have a line joining them to the particular use case?</p>
<p>If the Use Case you are diagramming is the case where an actor attempts to do something that is not permitted and is then denied, then yes, I would show it.</p> <p>Otherwise, I would stick to only including things that are actually part of the use case.</p>
<p>You might model Role actors that can do the task. You could then have another use case that has the original actor attempting to acquire the given Role.</p>
23,323
<p>Using reflection, I need to load 2 different versions of the same assembly. Can I load the 2 versions in 2 different AppDomains in the same process? </p> <p>I need to do some data migration from the old version of the app to the new version. Please let me know if this is possible or should I use 2 separate processes.</p>
<p>If you are doing it at design time (which you indicate you are not) this should help you: </p> <p><a href="http://blogs.msdn.com/abhinaba/archive/2005/11/30/498278.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/abhinaba/archive/2005/11/30/498278.aspx</a></p> <p>If you are doing it dynamically through reflection (looks like the case here) this might help you:</p> <p><a href="https://www.infosysblogs.com/microsoft/2007/04/loading_multiple_versions_of_s.html" rel="nofollow noreferrer">https://www.infosysblogs.com/microsoft/2007/04/loading_multiple_versions_of_s.html</a></p>
<p>If you are doing it at design time (which you indicate you are not) this should help you: </p> <p><a href="http://blogs.msdn.com/abhinaba/archive/2005/11/30/498278.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/abhinaba/archive/2005/11/30/498278.aspx</a></p> <p>If you are doing it dynamically through reflection (looks like the case here) this might help you:</p> <p><a href="https://www.infosysblogs.com/microsoft/2007/04/loading_multiple_versions_of_s.html" rel="nofollow noreferrer">https://www.infosysblogs.com/microsoft/2007/04/loading_multiple_versions_of_s.html</a></p>
8,248
<p>What is the functional equivalent of <a href="http://msdn.microsoft.com/en-us/netframework/aa663324.aspx" rel="noreferrer">Windows Communication Foundation</a> in Java 6?</p>
<p>WCF offers several communication options. A nice presentation is <a href="http://www.davidchappell.com/articles/white_papers/WCF_Diversity_v1.0.docx" rel="noreferrer">this white paper</a> by David Chappel. There the following options are described:</p> <ul> <li>Interoperable Communication using SOAP and WS-*</li> <li>Binary Communication Between WCF Applications</li> <li>RESTful Communication</li> <li>Communication using POX, RSS, and ATOM</li> <li>Communication with Line-of-Business Applications using Adapters</li> <li>Communication via Message Queues</li> <li>Communication via Windows Peer-to-Peer Networking</li> <li>Communication Between Processes on the Same Machine</li> <li>Custom Communication</li> </ul> <p>Although some options are not relevant to Java (e.g. the second one), it may help you to identify the corresponding functional equivalents in Java.</p>
<p><a href="http://ws.apache.org/axis/" rel="nofollow noreferrer">Apache Axis</a> is a good start for the web service part. If you need the messaging queue check out <a href="http://qpid.apache.org/" rel="nofollow noreferrer">Apache Qpid</a> other then that you will probably need to ask about the exact problem you are trying to solve in Java.</p>
35,083
<p>Given the following, how could I insert rows in my db? (Or what should I correct in my schema?)</p> <p>Models:</p> <pre><code>class Item &lt; ActiveRecord::Base has_many :tran_items has_many :transactions, :through =&gt; :tran_items end class TranItem &lt; ActiveRecord::Base belongs_to :item belongs_to :transaction end class Transaction &lt; ActiveRecord::Base #answer: rename Transaction has_many :tran_items has_many :items, :through =&gt; :tran_items end </code></pre> <p>Schema:</p> <pre><code>create_table :items do |t| t.references :tran_items #answer: remove this line t.string :name end create_table :tran_items do |t| t.belongs_to :items, :transactions, :null =&gt; false #answer: unpluralize t.integer :quantity end create_table :transactions do |t| t.references :tran_items #answer: remove this line t.decimal :profit end </code></pre> <p>I lost a few hours trying to insert records, using the rails console to test things out.</p>
<p>(edit: the model name "Transaction" may cause you some problems due to ActiveRecord::Transactions. <a href="https://rails.lighthouseapp.com/projects/8994/tickets/993-having-column-named-transaction-in-a-model-leads-to-weird-behavior" rel="nofollow noreferrer">There is a lighthouse ticket</a>.)</p> <p>Your schema is not set up correctly. "references" is an alias to "belongs_to". Item and Transaction don't <strong>belong_to</strong> trans_items, they each <strong>has_many</strong> trans_items (according to your models)</p> <pre><code>create_table :items do |t| t.string :name end create_table :tran_items do |t| t.belongs_to :item, :transaction, :null =&gt; false t.integer :quantity end create_table :transactions do |t| t.decimal :profit, :default =&gt; 0 end </code></pre> <p>(edit: make belongs_to singular)</p> <p>Did you drop the db and re-run the migrations to build the new schema? </p> <p>rake db:drop &amp;&amp; rake db:create &amp;&amp; rake db:migrate</p> <p>Here is what I get in the console:</p> <pre><code>&gt;&gt; i = Item.create(:name =&gt; 'My Item') =&gt; #&lt;Item id: 2, name: "My Item"&gt; &gt;&gt; t = Transaction.create(:profit =&gt; 100) =&gt; #&lt;Transaction id: 2, profit: #&lt;BigDecimal:2411d2c,'0.1E3',4(8)&gt;&gt; &gt;&gt; t.tran_items.create(:item =&gt; i) =&gt; #&lt;TranItem id: nil, item_id: 2, transaction_id: 2, quantity: nil&gt; </code></pre>
<p>If I understood correctly.</p> <pre><code>item = Item.new(:name =&gt; "item") item.transactions.build(:name =&gt; "transaction") item.save! </code></pre>
36,237
<p>I've seen this syntax a couple times now, and it's beginning to worry me,</p> <p>For example:</p> <pre><code>iCalendar iCal = new iCalendar(); Event evt = iCal.Create&lt;Event&gt;(); </code></pre>
<p>It's a Generic Method, Create is declared with type parameters, and check this links for more information:</p> <ul> <li><a href="http://msdn.microsoft.com/en-us/library/ms379564(vs.80).aspx" rel="nofollow noreferrer">An Introduction to C# Generics</a></li> <li><a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/" rel="nofollow noreferrer">Generics (C# Programming Guide)</a></li> <li><a href="https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/generic-methods" rel="nofollow noreferrer">Generic Methods</a></li> </ul>
<p>This syntax is just applying generics to a method. It's typically used for scenarios where you want to control the return type of the method. You will find this kind of syntax a lot in code that uses a IoC framework.</p>
39,321
<p>How do I rewrite a URL in ASP.NET?</p> <p>I would like users to be able to go to</p> <pre><code>http://www.website.com/users/smith </code></pre> <p>instead of</p> <pre><code>http://www.website.com/?user=smith </code></pre>
<p>Try the Managed Fusion Url Rewriter and Reverse Proxy:</p> <p><a href="http://urlrewriter.codeplex.com" rel="noreferrer">http://urlrewriter.codeplex.com</a></p> <p>The rule for rewriting this would be:</p> <pre><code># clean up old rules and forward to new URL RewriteRule ^/?user=(.*) /users/$1 [NC,R=301] # rewrite the rule internally RewriteRule ^/users/(.*) /?user=$1 [NC,L] </code></pre>
<p>I have used an httpmodule for url rewriting from <a href="http://www.urlrewriting.net/" rel="nofollow noreferrer">www.urlrewriting.net</a> with great success (albeit I believe a much earlier, simpler version)</p> <p>If you have very few actual rewriting rules then url mappings built in to .NET 2.0 are probably an easier option, there are a few write ups of these on the web, the <a href="https://web.archive.org/web/20210513223749/http://aspnet.4guysfromrolla.com/articles/011007-1.aspx" rel="nofollow noreferrer">4guysfromrolla</a> one seems fairly exhaustive but as you can see they don't support regular expression mappings are are as such rendered fairly useless in a dynamic environment (assuming "smith" in your example is not a special case then these would be of no use)</p>
2,444
<p>I want to use a signals/slots library in a project that doesn't use QT. I have pretty basic requirements: </p> <ol> <li>Connect two functions with any number of parameters.</li> <li>Signals can be connected to multiple slots.</li> <li>Manual disconnection of signal/slot connection.</li> <li>Decent performance - the application is frame-based (i.e. not event-based) and I want to use the connections in each frame.</li> </ol> <p>I've read a <a href="https://web.archive.org/web/20130626010123/http://www.3sinc.com/opensource/boost.bind-vs-sigc2.html" rel="noreferrer">comparison between libsigc++ and Boost.Signals</a>. I've also read that Boost.Signals suffers from poor performance. However, I know there are other libraries and I'm still not sure which library should I choose.</p> <p>Are there any recommendations for a signals/slots library?</p>
<p>First, try with boost::signal anyway. Don't assume it will not be fast enough until you try in your specific case that is your application</p> <p>If it's not efficient enough, maybe something like <a href="http://www.codeproject.com/KB/cpp/FastDelegate.aspx" rel="nofollow noreferrer">FastDelegate</a> will suit your needs? (i did'nt try it but heard it was a nice solution in some cases where boost::signal don't seem to suit).</p> <p>Anyway, if in your application use the signal each frame, it may be worth to replace the signal system by something more simple, like a container that hold objects/functors that will be called each frame. Signal is more made to allow immediate "events" management than to make a loop cycle dynamic (allowing changing the functions called each frame). (I have <a href="https://github.com/Klaim/gamecore/blob/master/GCore/GC_TaskManager.h" rel="nofollow noreferrer">my own solution</a> (UPDATE: it's very old and archaic now) that i heavily use in a game and for instance i've no problem with the performance, so maybe something similar could help).</p>
<p>An another option can be <a href="https://github.com/yigityuce/YSignalSlot" rel="nofollow">YSignalSlot</a>. I used it. I think it is pretty good.</p>
46,967
<p>I have an <a href="https://en.wikipedia.org/wiki/Microsoft_Office#Windows_versions" rel="nofollow noreferrer">Office 2007</a> (specifically <a href="https://en.wikipedia.org/wiki/Microsoft_Outlook#Outlook_2007" rel="nofollow noreferrer">Outlook 2007</a>) add in created in Visual&nbsp;Studio&nbsp;2008.</p> <p>When I uncheck the "Sign the ClickOnce manifests" option, and then publish, it rechecks that option automatically.</p> <p>I have a regular <a href="http://en.wikipedia.org/wiki/Windows_Forms" rel="nofollow noreferrer">Windows Forms</a> project in the same solution that allows me to publish with this unchecked.</p> <p>Why isn't it allowing me to uncheck the sign option?</p>
<p>You are not required to sign EXE files, but you need to sign DLL files for deployment. Your Office add-in is in the form of a DLL file, so it must be signed. Your Windows Forms project is linked into an EXE file, hence it does not need to be signed.</p> <p>See the relevant MSDN page, <a href="http://msdn.microsoft.com/en-us/library/aa730868(VS.80).aspx#rsvssign_topic3" rel="noreferrer"><em>ClickOnce Manifest Signing and Strong-Name Assembly Signing Using Visual Studio Project Designer's Signing Page</em>, sub section <em>Signing Assemblies</em></a>.</p>
<p>While you don't have to sign the manifest any more with Windows Forms, <a href="http://en.wikipedia.org/wiki/Windows_Presentation_Foundation" rel="nofollow noreferrer">WPF</a> and console applications, <a href="http://en.wikipedia.org/wiki/Visual_Studio_Tools_for_Office" rel="nofollow noreferrer">VSTO</a> solutions still require that the manifests be signed when using ClickOnce deployment. </p> <p>Most VSTO scenarios are in the enterprise where best practices require signing of applications. Also since VSTO solutions always run full trust there is a higher risk associated with making signing optional. This is completely separate from signing a DLL file; you don't need to sign the assembly with a ClickOnce-deployed VSTO application, you have to sign the manifests; they handle the hashing and verification of the files at install time.</p>
28,392
<p>I'm inserting multiple records into a table A from another table B. Is there a way to get the identity value of table A record and update table b record with out doing a cursor?</p> <pre><code>Create Table A (id int identity, Fname nvarchar(50), Lname nvarchar(50)) Create Table B (Fname nvarchar(50), Lname nvarchar(50), NewId int) Insert into A(fname, lname) SELECT fname, lname FROM B </code></pre> <p>I'm using MS SQL Server 2005.</p>
<p>Use the ouput clause from 2005:</p> <pre><code>DECLARE @output TABLE (id int) Insert into A (fname, lname) OUTPUT inserted.ID INTO @output SELECT fname, lname FROM B select * from @output </code></pre> <p>now your table variable has the identity values of all the rows you insert.</p>
<p>MBelly is right on the money - But then the trigger will always try and update table B even if that's not required (Because you're also inserting from table C?).</p> <p>Darren is also correct here, you can't get multiple identities back as a result set. Your options are using a cursor and taking the identity for each row you insert, or using Darren's approach of storing the identity before and after. So long as you know the increment of the identity this should work, so long as you make sure the table is locked for all three events.</p> <p>If it was me, and it wasn't time critical I'd go with a cursor.</p>
12,155
<p>I'm an old (but not too old) Java programmer, that decided to learn C++. But I have seen that much of C++ programming style, is... well, just damn ugly!</p> <p>All that stuff of putting the class definition in a header file, and the methods in a different source file- Calling functions out of nowhere, instead of using methods <strong>inside classes</strong>. All that just seems... wrong!</p> <p>So finally, is there any reason for me to continue with this massacre to the OOP, and anything that is good and righteous in programming, or can I just ignore that old-fashioned C++ conventions, and use my good Java programing style?</p> <p>By the way I'm learning C++, because I want to do game programing.</p> <p>Here is an example:</p> <p>In an C++ website I found a Windows implementation:</p> <pre><code>class WinClass { public: WinClass (WNDPROC wndProc, char const * className, HINSTANCE hInst); void Register () { ::RegisterClass (&amp;_class); } private: WNDCLASS _class; }; </code></pre> <p>That class is located in a header file and the constructor:</p> <pre><code>WinClass::WinClass (WNDPROC wndProc, char const * className, HINSTANCE hInst) { _class.style = 0; _class.lpfnWndProc = wndProc; // Window Procedure: mandatory _class.cbClsExtra = 0; _class.cbWndExtra = 0; _class.hInstance = hInst; // Owner of the class: mandatory _class.hIcon = 0; _class.hCursor = ::LoadCursor (0, IDC_ARROW); // Optional _class.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1); // Optional _class.lpszMenuName = 0; _class.lpszClassName = className; // Mandatory } </code></pre> <p>Is located at a .cpp source file.</p> <p>What I could just do is:</p> <pre><code>class WinClass { public: WinClass (WNDPROC wndProc, char const * className, HINSTANCE hInst) { _class.style = 0; _class.lpfnWndProc = wndProc; // Window Procedure: mandatory _class.cbClsExtra = 0; _class.cbWndExtra = 0; _class.hInstance = hInst; // Owner of the class: mandatory _class.hIcon = 0; _class.hCursor = ::LoadCursor (0, IDC_ARROW); // Optional _class.hbrBackground = (HBRUSH) (COLOR_WINDOW + 1); // Optional _class.lpszMenuName = 0; _class.lpszClassName = className; // Mandatory } void Register () { ::RegisterClass (&amp;_class); } private: WNDCLASS _class; }; </code></pre> <p>And now the constructor is inside its class.</p>
<p>In addition to what others have said here, there are even more important problems:</p> <p>1) Large translation units lead to longer compile times and larger object file sizes.</p> <p>2) Circular dependencies! And this is the big one. And it can almost always be fixed by splitting up headers and source:</p> <pre><code>// Vehicle.h class Wheel { private: Car&amp; m_parent; public: Wheel( Car&amp; p ) : m_parent( p ) { std::cout &lt;&lt; "Car has " &lt;&lt; m_parent.numWheels() &lt;&lt; " wheels." &lt;&lt; std::endl; } }; class Car { private: std::vector&lt; Wheel &gt; m_wheels; public: Car() { for( int i=0; i&lt;4; ++i ) m_wheels.push_back( Wheel( *this ) ); } int numWheels() { return m_wheels.size(); } } </code></pre> <p>No matter what order you put these in, one will always be lacking the definition of the other, even using forward declarations it won't work, since in the function bodies are using specifics about each class's symbol.</p> <p>But if you split them up into proper .h and .cpp files and use forward declarations it will satisfy the compiler:</p> <pre><code>//Wheel.h //------- class Car; class Wheel { private: Car&amp; m_parent; public: Wheel( Car&amp; p ); }; //Wheel.cpp //--------- #include "Wheel.h" #include "Car.h" Wheel::Wheel( Car&amp; p ) : m_parent( p ) { std::cout &lt;&lt; "Car has " &lt;&lt; m_parent.numWheels() &lt;&lt; " wheels." &lt;&lt; std::endl; } //Car.h //----- class Wheel; class Car { private: std::vector&lt; Wheel &gt; m_wheels; public: Car(); int numWheels(); } //Car.cpp //------- #include "Car.h" #include "Wheel.h" Car::Car() { for( int i=0; i&lt;4; ++i ) m_wheels.push_back( Wheel( *this ) ); } int Car::numWheels() { return m_wheels.size(); } </code></pre> <p>Now the code that actually has to know specifics about the second class can just include the header file which doesn't need to know specifics about the first class.</p> <p>Headers just provide the <em>declarations</em> while source files provide the <em>definitions</em>. Or another way to say it: Headers tell you what is there (<em>what symbols are valid to use</em>) and source tells the compiler what the symbols actually do. In C++ you don't need anything more than a valid symbol to begin using whatever it is.</p> <p>Trust that C++ has a reason for this idiom, because if you don't you will make a lot of headaches for yourself down the line. I know :/</p>
<p>I worry from the tone of your question that you may be reading some bad C++ code in learning C++. Well-written code is usually not ugly in any language. As a starting point, you might try the <a href="http://www.parashift.com/c++-faq-lite/index.html" rel="nofollow noreferrer">online C++ FAQ</a>, especially the chapter on learning C++.</p>
48,745
<p>I have two STL containers that I want to merge, removing any elements that appear more than once. For example:</p> <pre><code>typedef std::list&lt;int&gt; container; container c1; container c2; c1.push_back(1); c1.push_back(2); c1.push_back(3); c2.push_back(2); c2.push_back(3); c2.push_back(4); container c3 = unique_merge(c1, c2); // c3 now contains the following 4 elements: // 1, 2, 3, 4 </code></pre> <p>std::unique seems to be for adjacent elements only, and in my case the containers could be in any order. I could do some <strong>std::set</strong> trickery I guess:</p> <pre><code>container unique_merge(const container&amp; c1, const container&amp; c2) { std::set&lt;container::value_type&gt; s; BOOST_FOREACH(const container::value_type&amp; val, c1) s.insert(val); BOOST_FOREACH(const container::value_type&amp; val, c2) s.insert(val); return container(s.begin(), s.end()); } </code></pre> <p>Is there a better way or have I missed something bleeding obvious?</p>
<p>For an unordered lists, your set trick is probably one of the best. It each insert should be O(log n), with N inserts required, and traversing will be O(n), giving you O(N*log n). The other option is to run std::sort on each list individually and then walk through them in parallel using <a href="http://msdn.microsoft.com/en-us/library/a20tb7e2.aspx" rel="noreferrer">std::set_union</a>, which removes duplicates for you. This will also be O(n*log n), so if you're worried about performance, you'll have to profile. If you're not, do whichever makes more sense to you.</p> <p>Edit: <code>set_union</code> will only work if there are no duplicates in the original lists, otherwise you'll have to go with <code>sort</code>, <code>merge</code>, <code>unique</code> and <code>erase</code>. The big O performance is still the same, with the same caveats about profiling.</p> <pre><code>template &lt;typename container&gt; container unique_merge(container c1, container c2) { std::sort(c1.begin(), c1.end()); std::sort(c2.begin(), c2.end()); container mergeTarget; std::merge(c1.begin(), c1.end(), c2.begin(), c2.end(), std::insert_iterator(mergeTarget, mergeTarget.end()) ); std::erase( std::unique(mergeTarget.begin(), mergeTarget.end()), mergeTarget.end() ); return mergeTarget; } </code></pre>
<p>Use the <a href="https://en.cppreference.com/w/cpp/algorithm/set_union" rel="nofollow noreferrer">std::set_union algorithm</a> from the STL. You'll need to sort your input lists first though -- or create copies of your input lists, sort them, then use std::set_union.</p>
35,585
<p>What is Lazy Loading?</p> <p>[Edit after reading a few answers] Why do people use this term so often? </p> <p>Say you just use a ASP/ADO recordset and load it with data or ADO.NET Datasource for a gridview.</p> <p>I guess I should have asked why people use the term Lazy Loading, what "other" types are their?</p>
<p>It's called lazy loading because, like a lazy person, you are putting off doing something you don't want to. The opposite is Eager Loading, where you load something right away, long before you need it.</p> <p>If you are curious why people might use lazy loading, consider an application that takes a LOOOOONG time to start. This application is probably doing a lot of eager loading... loading things from disk, and doing calculations and whatnot long before it is ever needed.</p> <p>Compare this to lazy loading, the application would start much faster, but then the first time you need to do something that requires some long running load, there may be a slight pause while it is loaded for the first time. Thus, with lazy loading, you are amortizing the load time throughout the course of running your application... and you may actually save from loading things that the user may never intend to use.</p>
<p>According to geeksforgeeks, Lazy loading is a software design pattern where the initialization of an object occurs only when it is actually needed and not before to preserve the simplicity of usage and improve performance.</p> <p><a href="https://www.geeksforgeeks.org/lazy-loading-design-pattern/" rel="nofollow noreferrer">https://www.geeksforgeeks.org/lazy-loading-design-pattern/</a></p>
5,693
<p>Yesterday I tried to get started with Java RMI. I found this sun tutorial (<a href="http://java.sun.com/docs/books/tutorial/rmi/index.html" rel="nofollow noreferrer">http://java.sun.com/docs/books/tutorial/rmi/index.html</a>) and started with the server implemantation. But everytime I start the pogram (the rmiregistry is running) I get an AccessControlException with the following StackTrace:</p> <pre><code>LoginImpl exception: java.security.AccessControlException: access denied (java.io.FilePermission \\\C\ProjX\server\serverProj\bin\usermanager read) at java.security.AccessControlContext.checkPermission(AccessControlContext.java:264) at java.security.AccessController.checkPermission(AccessController.java:427) at java.lang.SecurityManager.checkPermission(SecurityManager.java:532) at java.lang.SecurityManager.checkRead(SecurityManager.java:871) at java.io.File.exists(File.java:700) at sun.net.www.protocol.file.Handler.openConnection(Handler.java:80) at sun.net.www.protocol.file.Handler.openConnection(Handler.java:55) at java.net.URL.openConnection(URL.java:943) at sun.rmi.server.LoaderHandler.addPermissionsForURLs(LoaderHandler.java:1020) at sun.rmi.server.LoaderHandler.access$300(LoaderHandler.java:52) at sun.rmi.server.LoaderHandler$Loader.&lt;init&gt;(LoaderHandler.java:1108) at sun.rmi.server.LoaderHandler$Loader.&lt;init&gt;(LoaderHandler.java:1089) at sun.rmi.server.LoaderHandler$1.run(LoaderHandler.java:861) at java.security.AccessController.doPrivileged(Native Method) at sun.rmi.server.LoaderHandler.lookupLoader(LoaderHandler.java:858) at sun.rmi.server.LoaderHandler.loadProxyClass(LoaderHandler.java:541) at java.rmi.server.RMIClassLoader$2.loadProxyClass(RMIClassLoader.java:628) at java.rmi.server.RMIClassLoader.loadProxyClass(RMIClassLoader.java:294) at sun.rmi.server.MarshalInputStream.resolveProxyClass(MarshalInputStream.java:238) at java.io.ObjectInputStream.readProxyDesc(ObjectInputStream.java:1494) at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1457) at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1693) at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1299) at java.io.ObjectInputStream.readObject(ObjectInputStream.java:339) at sun.rmi.registry.RegistryImpl_Skel.dispatch(Unknown Source) at sun.rmi.server.UnicastServerRef.oldDispatch(UnicastServerRef.java:375) at sun.rmi.server.UnicastServerRef.dispatch(UnicastServerRef.java:240) at sun.rmi.transport.Transport$1.run(Transport.java:153) at java.security.AccessController.doPrivileged(Native Method) at sun.rmi.transport.Transport.serviceCall(Transport.java:149) at sun.rmi.transport.tcp.TCPTransport.handleMessages(TCPTransport.java:460) at sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run(TCPTransport.java:701) at java.lang.Thread.run(Thread.java:595) at sun.rmi.transport.StreamRemoteCall.exceptionReceivedFromServer(Unknown Source) at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source) at sun.rmi.server.UnicastRef.invoke(Unknown Source) at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source) at startserver.StartServer.main(StartServer.java:22) </code></pre> <p>My <code>server.policy</code> file looks like this:</p> <pre><code>grant { permission java.security.AllPermission; }; </code></pre> <p>But I have also tried this one:</p> <pre><code>grant { permission java.security.AllPermission; permission java.io.FilePermission &quot;file://C:/ProjX/server/serverProj/bin/usermanager&quot;, &quot;read&quot;; }; </code></pre> <p>... and this one (and several others :-():</p> <pre><code>grant codeBase &quot;file:///-&quot; { permission java.security.AllPermission; }; </code></pre> <p>But in every case the result is the same. And yes, the policy file is in path (I see a Parse Exception, when I write wrong statments into the policy-file). I tried out several other &quot;/&quot; and &quot;&quot; constellations but it has no effect.</p> <p>I use Eclipse and my VM-Parameters are like this:</p> <pre><code>-cp C:\ProjX\server\serverProj\bin\usermanager\ -Djava.rmi.server.codebase=file://C:/ProjX/server/serverProj/bin/usermanager/ -Djava.rmi.server.hostname=XYZ (anonymized) -Djava.security.policy=server.policy </code></pre> <p>The compiled Remote-Interface and the interface-implementation class (LoginImpl) classes are in this path: &quot;C:/ProjX/server/serverProj/bin/usermanager/&quot;. The main method, where I instanciate and rebind the stub to the registry is in another package and looks like this:</p> <pre><code>public static void main(String[] args) { if (System.getSecurityManager() == null) { System.setSecurityManager(new SecurityManager()); } try { String name = &quot;Login&quot;; Login login = new LoginImpl(); Login stub = (Login) UnicastRemoteObject.exportObject(login, 0); Registry registry = LocateRegistry.getRegistry(); registry.rebind(name, stub); System.out.println(&quot;LoginImpl bound&quot;); } catch (Exception e) { System.err.println(&quot;LoginImpl exception:&quot;); e.printStackTrace(); } } </code></pre> <p>Does anybody have an advice for me?</p> <hr /> <p>So the question is the same (the <code>java.rmi.UnmarshalException</code> shows that changing the codebase is not the solution of my AccessControlException). And no: I don't want to buy a plugin &quot;G B&quot;.</p>
<p>Grant of all permissions to all code is a really bad. Any RMI client could do what it wanted as logged in user. In general try to restrict permissions as much as reasonable, particularly when you don't know where the code has come from.</p> <p>Back to the question...</p> <pre><code>-Djava.rmi.server.codebase=file://C:/ProjX/server/serverProj/bin/usermanager/ </code></pre> <p>That should be either <code>"file:///C:/..."</code> or <code>"file:/C:/..."</code>. Think of http. <code>"http://C:/..."</code> refers to a host named <code>C</code>. Note that the exception message has dropped the colon, because that's just syntax for port number.</p> <p>The reason why you get a security exception even if you grant permissions to all code, is that RMI is restricting permissions to that appropriate given the URLs involved (using AccessController doPrivileged two argument form).</p>
<p>I think the exception is actually coming out of rmiregistry. This part of the stack trace is what makes me think so. The stub for rmiregistry is receiving the exception and passing it back up as the result of the attempt to rebind.</p> <pre> at sun.rmi.transport.StreamRemoteCall.<b>exceptionReceivedFromServer</b>(Unknown Source) at sun.rmi.transport.StreamRemoteCall.executeCall(Unknown Source) at sun.rmi.server.UnicastRef.invoke(Unknown Source) at sun.rmi.registry.RegistryImpl_Stub.rebind(Unknown Source) </pre> <p>Try running rmiregistry with <code>-J-Djava.security.policy=all.policy</code>, where the policy file grants all permissions (at least to get things going).</p> <p>Eventually you may also wish to switch to an HTTP codebase URL, just so that you can run clients on a machine separate from your server's.</p>
21,696
<p>Just found this out the hard way. I wanted to pop up a FontDialog to allow the user to choose a font.. one of those familiar dialogs..</p>
<p><strong>Not all of them have equivalents.</strong><br> The FontDialog for instance doesnt.. (grumble grumble). This page has the complete lowdown.. posting since it may be useful just as a mental note. <a href="http://msdn.microsoft.com/en-us/library/ms750559.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms750559.aspx</a></p> <p><strong><em>Update:</em></strong> The Programming WPF book had this covered. Apparently some of the dialogs didn't make the RTM bus. The FontDialog that will included into the next update is available here.. as is the ColorPicker dialog. Also you shuoldn't blindly use Win32 dialogs, because the corresponding types in WPF (e.g. Font and Color are "bigger and better" now.)</p> <p><a href="http://blogs.msdn.com/wpfsdk/archive/2006/10/26/Uncommon-Dialogs--Font-Chooser-and-Color-Picker-Dialogs.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/wpfsdk/archive/2006/10/26/Uncommon-Dialogs--Font-Chooser-and-Color-Picker-Dialogs.aspx</a></p>
<p>I know a team working on a WPF application for a couple of years by now, and their feedback is that WPF is still a no match to WinForms when it comes to complicated controls (advanced data grids, tree views and the like). Basic controls are ok though.</p>
14,598
<p>Just looking at ways of getting named constants in python.</p> <pre><code>class constant_list: (A_CONSTANT, B_CONSTANT, C_CONSTANT) = range(3) </code></pre> <p>Then of course you can refer to it like so: </p> <pre><code>constant_list.A_CONSTANT </code></pre> <p>I suppose you could use a dictionary, using strings: </p> <pre><code>constant_dic = { "A_CONSTANT" : 1, "B_CONSTANT" : 2, "C_CONSTANT" : 3,} </code></pre> <p>and refer to it like this:</p> <pre><code>constant_dic["A_CONSTANT"] </code></pre> <hr> <p>My question, then, is simple. Is there any better ways of doing this? Not saying that these are inadequate or anything, just curious - any other common idioms that I've missed?</p> <p>Thanks in advance.</p>
<p>For 2.3 or after:</p> <pre><code>class Enumerate(object): def __init__(self, names): for number, name in enumerate(names.split()): setattr(self, name, number) </code></pre> <p>To use:</p> <pre><code> codes = Enumerate('FOO BAR BAZ') </code></pre> <p><code>codes.BAZ</code> will be 2 and so on. </p> <p>If you only have 2.2, precede this with:</p> <pre><code> from __future__ import generators def enumerate(iterable): number = 0 for name in iterable: yield number, name number += 1 </code></pre> <p>(<em>This was taken from <a href="http://www.velocityreviews.com/forums/t322211-enum-in-python.html" rel="noreferrer">here</a></em>)</p>
<p>In Python, strings are immutable and so they are better for constants than numbers. The best approach, in my opinion, is to make an object that keeps constants as strings:</p> <pre><code>class Enumeration(object): def __init__(self, possibilities): self.possibilities = set(possibilities.split()) def all(self): return sorted(self.possibilities) def __getattr__(self, name): if name in self.possibilities: return name raise AttributeError("Invalid constant: %s" % name) </code></pre> <p>You could then use it like this:</p> <pre><code>&gt;&gt;&gt; enum = Enumeration("FOO BAR") &gt;&gt;&gt; print enum.all() ['BAR', 'FOO'] &gt;&gt;&gt; print enum.FOO FOO &gt;&gt;&gt; print enum.FOOBAR Traceback (most recent call last): File "enum.py", line 17, in &lt;module&gt; print enum.FOOBAR File "enum.py", line 11, in __getattr__ raise AttributeError("Invalid constant: %s" % name) AttributeError: Invalid constant: FOOBAR </code></pre>
23,924
<p>When uninstalling my application, I'd like to configure the <a href="http://en.wikipedia.org/wiki/WiX" rel="noreferrer">Wix</a> setup to remove all the files that were added <strong>after the original installation</strong>. It seems like the uninstaller removes only the directories and files that were originally installed from the MSI file and it leaves everything else that was added later in the application folder. In another words, I'd like to purge the directory when uninstalling. How do I do that?</p>
<p>Use <a href="http://wixtoolset.org/documentation/manual/v3/xsd/wix/removefile.html" rel="noreferrer">RemoveFile element</a> with On="<strong>uninstall</strong>". Here's an example: </p> <pre><code>&lt;Directory Id="CommonAppDataFolder" Name="CommonAppDataFolder"&gt; &lt;Directory Id="MyAppFolder" Name="My"&gt; &lt;Component Id="MyAppFolder" Guid="*"&gt; &lt;CreateFolder /&gt; &lt;RemoveFile Id="PurgeAppFolder" Name="*.*" On="uninstall" /&gt; &lt;/Component&gt; &lt;/Directory&gt; &lt;/Directory&gt; </code></pre> <p><strong>Update</strong></p> <blockquote> <p>It didn't work 100%. It removed the files, however none of the additional directories - the ones created after the installation - were removed. Any thoughts on that? – pribeiro</p> </blockquote> <p>Unfortunately Windows Installer doesn't support deleting directories with subdirectories. In this case you have to resort to custom action. Or, if you know what subfolders are, create a bunch of RemoveFolder and RemoveFile elements.</p>
<p>Not an WIX expert, but could a possible (simpler?) solution to this be to run the <a href="http://wix.sourceforge.net/manual-wix3/qtexec.htm" rel="noreferrer">Quiet Execution Custom Action</a> which is part of the built in extensions of WIX?</p> <p>Could run the <a href="http://www.computerhope.com/rmdirhlp.htm" rel="noreferrer">rmdir</a> MS DOS command with the /S and /Q options. </p> <pre><code>&lt;Binary Id="CommandPrompt" SourceFile="C:\Windows\System32\cmd.exe" /&gt; </code></pre> <p>And the custom action doing the job is simple: </p> <pre><code>&lt;CustomAction Id="DeleteFolder" BinaryKey="CommandPrompt" ExeCommand='/c rmdir /S /Q "[CommonAppDataFolder]MyAppFolder\PurgeAppFolder"' Execute="immediate" Return="check" /&gt; </code></pre> <p>Then you'll have to modify the InstallExecuteSequence as documented many places.</p> <p><strong>Update:</strong> Had issues with this approach. Ended up making a custom task instead, but still considers this a viable solution, but without getting the details to work.</p>
23,809
<p>I have an asp.net ascx control file and I have put the control on an aspx page. The aspx page has a button in which when I press enter on the keyboard, I want it to fire the event handler for the button. Is there a way to set this?</p> <p>I am using a master page with a button already on it, so now when I press the enter key, the event handler for that button fires.</p>
<p>DefaultButton also works in panels, so you can set a default button in each panel and have the Enter key click the button in whichever panel currently has focus.</p>
<p>Just a small note: You cannot use the 'defaultButton' attribute if your button is a LinkButton, it doesn't work for that, taken from here: <a href="http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlform.defaultbutton.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.web.ui.htmlcontrols.htmlform.defaultbutton.aspx</a></p>
45,649
<p>I have a big list of global variables that each have their own setup function. My goal is to go through this list, call each item's setup function, and generate some stats on the data loaded in the matching variable. However, what I'm trying now isn't working and I need help to make my program call the setup functions. </p> <p>The global variables and their setup functions are case-sensitive since this came from XML and is necessary for uniqueness.</p> <p>The data looks something like this:</p> <pre><code>'(ABCD ABC\d AB\c\d ...) </code></pre> <p>and the setup functions look like this:</p> <pre><code>(defun setup_ABCD... (defun setup_ABC\d... </code></pre> <p>I've tried concatenating them together and turning the resulting string into a function, but this interferes with the namespace of the previously loaded setup function. Here's how I tried to implement that:</p> <pre><code>(make-symbol (concatenate 'string "setup_" (symbol-name(first '(abc\d))))) </code></pre> <p>But using <code>funcall</code> on this doesn't work. How can I get a callable function from this?</p>
<p>It's because MAKE-SYMBOL returns an uninterned symbol. You should use INTERN instead.</p>
<p>I'd either use INTERN or (possibly, you'd have to profile to be 100% sure it's helpful) a helper function that does the string concatenation and the initial find, then caches the result in a hashtable (keyed off the original symbol). That may be faster than a pure INTERN/CONCATENATE solution, would potentially generate less transient garbage, but would probalby end up using more long-term storage.</p> <p>Something along the lines of:</p> <pre> (defvar *symbol-function-map* (make-hash-table)) (defun lookup-symbol (symbol) (or (gethash symbol *symbol-function-map*) (let ((function-name (intern (concatenate 'string "setup_" (symbol-name symbol))))) (setf (gethash symbol *symbol-function-map*) (symbol-function function-name))))) </pre> <p>If you require the name of the function, rather than the function itself, leave out the call to SYMBOL-FUNCTION.</p>
37,633
<p>I am trying to figure out how to wire up Auto Bed Leveling (ABL) on my Ender 3 using the optocoupler and inductive proximity sensor below. </p> <p>I cannot figure out how to wire it all together, all the tutorials I have found are for 2 and 3 wire per side of the optocoupler.</p> <p><a href="https://i.stack.imgur.com/VL6Ix.jpg" rel="nofollow noreferrer" title="NOYITO Optocoupler Isolation MOS FET 10A DC 2.7-27V High-Power Field Effect Tube Driver Module 0-20Khz PWM Switch Control Board Development Board Module"><img src="https://i.stack.imgur.com/VL6Ix.jpg" alt="NOYITO Optocoupler Isolation MOS FET 10A DC 2.7-27V High-Power Field Effect Tube Driver Module 0-20Khz PWM Switch Control Board Development Board Module" title="NOYITO Optocoupler Isolation MOS FET 10A DC 2.7-27V High-Power Field Effect Tube Driver Module 0-20Khz PWM Switch Control Board Development Board Module"></a></p> <p><a href="https://i.stack.imgur.com/t5FWj.jpg" rel="nofollow noreferrer" title="uxcell 4mm Inductive Proximity Approach Sensor Switch Detector NPN NO DC 6-36V 300mA 3-Wire LJ12A3-4-Z/BX"><img src="https://i.stack.imgur.com/t5FWj.jpg" alt="uxcell 4mm Inductive Proximity Approach Sensor Switch Detector NPN NO DC 6-36V 300mA 3-Wire LJ12A3-4-Z/BX" title="uxcell 4mm Inductive Proximity Approach Sensor Switch Detector NPN NO DC 6-36V 300mA 3-Wire LJ12A3-4-Z/BX"></a></p>
<p>Connecting is pretty straightforward like the other modules, difference is an extra input lead.</p> <p>From e.g. <a href="https://www.desertcart.ae/products/92694483-noyito-optocoupler-isolation-mos-fet-10-a-dc-2-7-27-v-high-power-field-effect-tube-driver-module-0-20-khz-pwm-switch-control-board-development-board-module" rel="nofollow noreferrer">here</a>: Module interface description: </p> <ol> <li>DC+: Positive DC power supply. </li> <li>DC- : Negative DC power supply. </li> <li>PWM: Signal input (connect MCU port, PLC interface, DC power supply, etc.) </li> <li>GND: The negative terminal of the signal </li> <li>OUT+: Positive output terminal (connected to the device positive) </li> <li>OUT-: Negative output terminal (connected to device negative)</li> </ol> <p>So, 1 and 2 connect to your power supply that matches the voltage of the logic of your microprocessor (5&nbsp;V) as this must be linked to 5 and 6 which are connected to the endstop signal and ground respectively.</p> <p>As for the sensor, blue is GND, black is signal (PWM) and brown is power as seen in e.g. <a href="/a/6359">this answer</a>.</p>
<p>This is a bit of an <em>addendum</em> to 0scar's answer, as I didn't want to edit it in to his post.</p> <p>For completion, the sensor's internal schematic is on the side of the sensor itself<sup>1</sup>:</p> <p><a href="https://i.stack.imgur.com/DbsjD.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DbsjD.png" alt="Sensor schematic" /></a></p> <p>where:</p> <ul> <li>PNP - 1 BN - Brown - V<sub>SUPPLY</sub></li> <li>N/O - 4 BK - Black - Sensor output</li> <li>4 mm - 3 BU - Blue - GND</li> </ul> <p>However, the complete diagram, taken from <a href="https://www.instructables.com/id/Enable-Auto-Leveling-for-your-3D-Printer-Marlin-Fi/" rel="nofollow noreferrer">Instructables - Enable Auto Leveling for Your 3D Printer With an Inductive Sensor (Marlin Firmware)</a>, can be seen here:</p> <p><a href="https://i.stack.imgur.com/2O66A.jpg" rel="nofollow noreferrer" title="Complete schematic"><img src="https://i.stack.imgur.com/2O66A.jpg" alt="Complete schematic" title="Complete schematic" /></a></p> <hr /> <h3>Footnotes</h3> <p><sup>1</sup> Taken from <a href="https://www.picclickimg.com/d/w1600/pict/273297496840_/4mm-Inductive-Proximity-Approach-Sensor-Switch-PNP-NO.jpg" rel="nofollow noreferrer">this image</a>, which was on this product page, <a href="https://picclick.com/4mm-Inductive-Proximity-Approach-Sensor-Switch-PNP-NO-273297496840.html" rel="nofollow noreferrer">4mm Inductive Proximity Approach Sensor Switch PNP NO DC 6-36V 200mA Cylinder</a>:</p> <p><a href="https://i.stack.imgur.com/nSWyh.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nSWyh.jpg" alt="Sensor image#1" /></a></p> <p>There is a bit more to the schematic, which can be glimpsed here (on the left hand side):</p> <p><a href="https://i.stack.imgur.com/2EVa0.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/2EVa0.jpg" alt="Sensor image#2" /></a></p> <p>A fuller, but blurry, view of the left hand side can be seen <a href="https://images-na.ssl-images-amazon.com/images/I/41kMRIsIl4L.jpg" rel="nofollow noreferrer">here</a>, from this <a href="https://weshop.co.id/amazon/item/uxcell-4mm-inductive-proximity-approach-sensor-switch-pnp-nc-dc-6-36v-200ma-3-wire-lj12a3-4-zay-cylinder-class-B07CWRHG4S.html" rel="nofollow noreferrer">product page</a>:</p> <p><a href="https://i.stack.imgur.com/27t1t.png" rel="nofollow noreferrer" title="Left hand side of sticker on sensor"><img src="https://i.stack.imgur.com/27t1t.png" alt="Left hand side of sticker on sensor" title="Left hand side of sticker on sensor" /></a></p>
1,290
<p>I'm building a .NET client application (C#, WinForms) that uses a web service for interaction with the database. The client will be run from remote locations using a WAN or VPN, hence the idea of using a web service rather than direct database access.</p> <p>The issue I'm grappling with right now is how to handle database concurrency. That is, if two people from different locations update the same data, how do I deal with it? I'm considering using timestamps on each database record and having that as part of the update where clauses, but that means that the timestamps have to move back and forth through the web service interface, which seems kind of ugly.</p> <p>What is the best way to approach this?</p>
<p>I don't think you want your web service to talk directly to the database. You probably want your service to interact with some type of business components who in turn interact with a data access layer. Any concurrency exceptions can be passed from the DAL up to the business layer where they can be handled so that the web service never has to see the timestamps.</p> <p>But if you are passing something like a data table up to the client and you want to avoid timestamps, you can do concurrency checking by comparing field by field. The Table Adapter wizards generate this type of concurrency checking by default if you ask for optimistic concurrency checking.</p>
<p>If your collisions occur infrequently enough that they can be resolved manually, a simple solution is to add an update trigger that copies a row's pre-update values to an audit table. This way the most recent write is the "winner", but no data is ever lost to an overwrite, and an administrator can restore an earlier row state or even combine them.</p> <p>This technique has its downsides, and is not a very good solution where frequent overwrites are common.</p>
23,463
<p>Where is a good place to get started learning how to use jQuery? It seems to be all the rage nowadays. I know some basics of JavaScript but I'm by no means an expert.</p>
<p>Officially from jQuery <a href="http://docs.jquery.com/Tutorials" rel="noreferrer">http://docs.jquery.com/Tutorials</a></p> <p>Or try anything on this site that compiles a bunch of jQuery learning material:</p> <p><a href="http://www.noupe.com/tutorial/51-best-of-jquery-tutorials-and-examples.html" rel="noreferrer">http://www.noupe.com/tutorial/51-best-of-jquery-tutorials-and-examples.html</a></p>
<p>There are a lot of them out there, google it, and the jQuery official site itself has a huge list of tutorials and excellent documentation with working examples. If that's not enough, try <a href="http://jqueryfordesigner.com" rel="nofollow noreferrer">http://jqueryfordesigner.com</a>, <a href="http://bassistance.de" rel="nofollow noreferrer">http://bassistance.de</a>. I have also written some at my blog, <a href="http://www.chazzuka.com/blog" rel="nofollow noreferrer">http://www.chazzuka.com/blog</a>.</p>
20,376
<p>My main browsers (FF and Chrome) are both configured for a 12 pixel font. In both browsers the font picker shows a font preview, and in both they are the same size and a comfortable size for reading web sites. My IE doesn't allow me to set font size, but seems to default to something a little bit larger than Chrome.</p> <p>On my personal website, I use XHTML &amp; CSS and have designated the page font as "medium", and use that font size for all of the principle text (the "content" text). When I view the site in IE 7, FF 3 and Chrome 0.4 the font displays as expected and matches the font pickers (except in IE where it's a little larger).</p> <p><strong>BUT</strong>, I go to nearly any other website (Google, StackOverflow, The DailyWTF, CodingHorror, Microsoft, Sourceforge, even W3C, etc) and they <em>all</em> display in tiny little microscopic fonts - what I estimate is 5 - 7 pixels.</p> <p>This is true on 3 different computers, with 2 different O/S (Vista and XP) and 4 different monitors (laptop, CRT, and brand new WS LCD).</p> <p>What's up with that? Am I overlooking something fundamental about web site design that I need to know? Or is it just that all these web sites do dumb things like setting the font to 50%, or 0.5 em, or x-small??? Why can't web site designers honor my font selection for the content text (I understand that side-bars, and footers and such might reasonably be small or x-small).</p> <p>I would be tempted to think it's just uninformed web site designers, but, heck!, these are some big name sites!!</p> <p>EDIT: To be clear I am not saying using em or % is dumb, I am wondering why many sites seem to use about 50% of my configured size. Surely my configured size is the size I would like to see text in.</p> <p>EDIT: From W3C's CSS spec: "The following table provides user agent guidelines for the absolute-size mapping to HTML heading and absolute font-sizes. <strong><em>The 'medium' value is the user's preferred font size and is used as the reference middle value.</em></strong>" - emphasis mine.</p> <hr> <p>There's a consensus coming through that web sites base relative font sizes on the typical browser default of 16px, which is unfortunate but "that's life". But what about other systems - can we expect all browsers to so default?</p> <p>At least I understand the problem now.</p> <p>I want to leave this question open for a while to see if others have differing views, before I select a final answer.</p> <hr> <p>Conclusion: I have reset all my browsers to 16px (18px on my 125 DPI machines), and set my website to use font-size: 90%. This is giving a good display size and, of course, all my favorite sites are now readable. Thanks for all the constructive answers and the lively to and fro.</p> <p>This is a great community.</p>
<p>Most browsers - if not all of them - set the default font size to 16px. Many websites use relative font sizing too. This will cause you a problem if your browser's font size is lower than this.</p> <p>Consider the case where you have a default font size of 16px in your browser. When the website font is 1.0em, it will display as 16px. Some other text maybe be 0.7em though, so that'll be smaller. However, if your default browser font size is 12px, 1.0em will be 12px and 0.7em will be unreadable because it will be so small.</p> <p>The solution is to keep your default browser font size to 16px, which will give you a realistic view of what others see when they view your site. Oh, and using relative font sizing is best-practice, not a mistake.</p>
<p>Setting a font to a % or an em measurement is <strong>not</strong> a dumb thing, in fact it is W3C recommended!</p>
43,654
<p>I have an internal enterprise app that currently consumes 10 different web services. They're consumed via old style "Web References" instead of using WCF.</p> <p>The problem I'm having is trying to work with the other teams in the company who are authoring the services I'm consuming. I found I needed to capture the exact SOAP messages that I'm sending and receiving. I did this by creating a new attribute that extends SoapExtensionAttribute. I then just add that attribute to the service method in the generated Reference.cs file. This works, but is painful for two reasons. First, it's a generated file so anything I do in there can be overwritten. Second, I have to remember to remove the attribute before checking in the file.</p> <p><strong>Is There a better way to capture the exact SOAP messages that I am sending and receiving?</strong></p>
<p>This seems to be a common question, as I just asked it and was told to look <a href="https://stackoverflow.com/questions/300674/getting-raw-soap-data-from-a-web-reference-client-running-in-aspnet">here</a>.</p> <p>You don't have to edit the generated <code>Reference.cs</code>. You can reference the extension in your application's <code>app.config</code>.</p>
<p>I used the following code is an example of how I captured SOAP requests in a application written a while back.</p> <pre><code>&lt;System.Diagnostics.Conditional("DEBUG")&gt; _ Private Sub CheckHTTPRequest(ByVal functionName As String) Dim e As New UTF8Encoding() Dim bytes As Long = Me.Context.Request.InputStream.Length Dim stream(bytes) As Byte Me.Context.Request.InputStream.Seek(0, IO.SeekOrigin.Begin) Me.Context.Request.InputStream.Read(stream, 0, CInt(bytes)) Dim thishttpRequest As String = e.GetString(stream) My.Computer.FileSystem.WriteAllText("D:\SoapRequests\" &amp; functionName &amp; ".xml", thishttpRequest, False) End Sub </code></pre> <p>Setting the conditional attribute like I did makes the compiler ignore the method call for all build types other than debug.</p> <p>Sorry for the VB, it is forced upon me.</p>
7,782
<p>Hello I was writing a Regular Expression (first time in my life I might add) but I just can't figure out how to do what I want. So far, so good since I already allow only Letters and spaces (as long as it's not the first character) now what I'm missing is that I don't want to allow any numbers in between the characters...could anybody help me please?</p> <pre><code>/^[^\s][\sa-zA-Z]+[^\d\W]/ </code></pre>
<p>OK, what you need is:</p> <pre><code>/^[a-zA-Z][\sa-zA-Z]*$/ </code></pre> <p>This matches:</p> <pre><code>^ - start of line [a-zA-Z] - any letter [\sa-zA-Z]* - zero or more letters or spaces $ - the end of the line </code></pre> <p>If you want to ensure that it also ends in a letter then put another</p> <pre><code>[a-zA-Z] </code></pre> <p>before the <code>$</code>. Note however that the string will then have to contain at least two letters (one at each end) to match.</p>
<p>If you only want to allow letters and spaces, then what you have is almost correct:</p> <pre><code>/^[a-zA-Z][\sa-zA-Z]*$/ </code></pre> <p>The <code>$</code> at the end signifies the end of the string.</p> <p><em>Edited to correct answer, thanks to @Alnitak</em></p>
37,020
<p>I am creating an application which displays some messages and its directions in the DataGridView. I would like to replace some columns content with pictures. For example I would like to replace number 0 which represents the incoming call with a green arrow (some .jpg image).</p> <p>Does anyone know how this could be achieved?</p> <p>Thanks!</p>
<p>We stored the images in the resource file as BMP files. Then, we handle the CellFormatting event in the DataGridView like this:</p> <pre><code> private void messageInfoDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { // Is this the correct column? (It's actually a DataGridViewImageColumn) if (messageInfoDataGridView.Columns[e.ColumnIndex] == messageSeverityDataGridViewTextBoxColumn) { // Get the row we're formatting DataGridViewRow row = messageInfoDataGridView.Rows[e.RowIndex]; // Get the enum from the row. MessageSeverity severity = ((MessageInfo)row.DataBoundItem).MessageSeverity; Bitmap cellValueImage; // Map the enumerated type to an image... // SeverityImageMap is a Dictionary&lt;MessageSeverity,Bitmap&gt;. if (ReferenceTables.SeverityImageMap.ContainsKey(severity)) cellValueImage = ReferenceTables.SeverityImageMap[severity]; else cellValueImage = Resources.NoAction; // Set the event args. e.Value = cellValueImage; e.FormattingApplied = true; } } </code></pre>
<p>GridViews have the ability to use an image field as opposed to a data bound field. This sounds like it would do the trick.</p>
32,788
<p>I'm not sure how "tests first" works and I'd like to hear arguments about when and why one would take this approach.</p> <p>I hear that it's often recommended to write tests and mock things before writing a single line of implementation. However, I can't help but think that it doesn't fit every situation. For instance, say I'm making a prototype and I'm not sure how everything is going to work yet. So I just start finding examples of each step that I think I need and throwing them into my code. At the end I have a proof of my theory and it didn't take that long. This is essentially "my test". It's not a unit test, but it is a test (most likely it's a console app).</p> <p>This is pretty much how I work. I think about what I want to do and try to do it. If it works then I eventually go back and write unit tests so that I can trap regression. Is this different than what you're "supposed to do"?</p>
<p>The over-arching rule is: Do the riskiest items first.</p> <p>Doing the test-cases first is, implicitly, arguing that the riskiest part of the coding is miscommunications and misunderstandings of the interfaces and behaviour of the objects that are being created.</p> <p>For many projects, that may well be true, and TDD is very appropriate in those cases.</p> <p>However, in many projects that is not the case, and applying TDD in those cases is a poor choice.</p> <p>If your highest risk is usability, stop futzing about with unit tests and do some UI prototyping.</p> <p>If your highest risk is performance, do some performance prototypes first, and don't worry about interfaces.</p> <p>This list goes on.</p> <p>Doing the risky items first has many advantages:</p> <ul> <li><p>Projects that are inevitably doomed die early, before many resources are wasted.</p></li> <li><p>Projects that are in trouble but are salvageable get the project management focus early, when it can do some good.</p></li> <li><p>The business side of your organization will value a project higher when it has a low risk of failure; there's less chance that it will be cancelled early unnecessarily.</p></li> </ul>
<p>I find that writing tests first does not work so well when I'm still construction the "story" of my code. It is hard to write tests when I'm unsure what the interfaces look like. I might write stub code to flesh out the classes and interfaces without thinking about tests. But I try to get to tests as quick as possible. I find it helps if I make notes of things I would test as I build the design, and then when my design is more solidified I go back to my notes and I make those tests firsts. That usually means the implementation and unit test code grow together, neither one before the other.</p>
41,312
<p>The interop library is slow and needs MS Office installed. Many times you don't want to install MS Office on servers.</p> <p>I'd like to use <a href="http://en.wikipedia.org/wiki/Apache_POI" rel="nofollow noreferrer">Apache POI</a>, but I'm on .NET.</p> <p>I need only to extract the text portion of the files, not creating nor "storing information" in Office files.</p> <p>I need to tell you that I've got a very large document library, and I can't convert it to newer XML files.</p> <p>I don't want to write a parser for the binaries files. A library like Apache POI does this for us. Unfortunately, it is only for the Java platform. Maybe I should consider writing this application in Java.</p> <p>I am still not finding an open source alternative to POI in .NET, I think I'll write my own application in Java.</p>
<p>For all MS Office versions:</p> <ul> <li>You could use the third-party components like <a href="http://www.textcontrol.com/" rel="nofollow noreferrer">TX Text Controls</a> for Word and <a href="http://www.tmssoftware.com/site/flexcelnet.asp" rel="nofollow noreferrer">TMS Flexcel Studio</a> for Excel</li> </ul> <p>For the new Office (2007):</p> <ul> <li>You could do some basic stuff using .net functionality from <code>system.io.packaging</code>. See how at <a href="http://msdn.microsoft.com/en-us/library/bb332058.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/bb332058.aspx</a></li> </ul> <p>For the old Office (before 2007):</p> <ul> <li>The old Office formats are now documented: <a href="http://www.microsoft.com/interop/docs/officebinaryformats.mspx" rel="nofollow noreferrer">http://www.microsoft.com/interop/docs/officebinaryformats.mspx</a>. If you want to do something really easy you might consider trying it. But be aware that these formats are VERY complex.</li> </ul>
<p>OpenOffice.</p> <p>You can program against it and have it do a lot for you, without spending the money on a license for the server, or have the vulnerability associated with it on your server.</p>
18,476
<p>I'm looking for something that will monitor Windows directories for size and file count over time. I'm talking about a handful of servers and a few thousand folders (millions of files).</p> <p>Requirements:</p> <ul> <li>Notification on X increase in size over Y time</li> <li>Notification on X increase in file count over Y time</li> <li>Historical graphing (or at least saving snapshot data over time) of size and file count</li> <li>All of this on a set of directories and their child directories</li> </ul> <p>I'd prefer a free solution but would also appreciate getting pointed in the right direction. If we were to write our own, how would we go about doing that? Available languages being Ruby, Groovy, Java, Perl, or PowerShell (since I'd be writing it).</p>
<p>You might want to take a look at <a href="http://www.codeplex.com/polymon" rel="nofollow noreferrer">PolyMon</a>, which is an open source systems monitoring solution. It allows you to write custom monitors in any .NET language, and allows you to create custom PowerShell monitors. </p> <p>It stores data on a SQL Server back end and provides graphing. For your purpose, you would just need a script that would get the directory size and file count. Something like:</p> <pre><code>$size = 0 $count = 0 $path = '\\unc\path\to\directory\to\monitor' get-childitem -path $path -recurse | Where-Object {$_ -is [System.IO.FileInfo]} | ForEach-Object {$size += $_.length; $count += 1} </code></pre> <p>In reply to Scott's comment: Sure. you could wrap it in a while loop </p> <pre><code>$ESCkey = 27 Write-Host "Press the ESC key to stop sniffing" -foregroundcolor "CYAN" $Running=$true While ($Running) { if ($host.ui.RawUi.KeyAvailable) { $key = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyUp,IncludeKeyDown") if ($key.VirtualKeyCode -eq $ESCkey) { $Running=$False } #rest of function here } </code></pre> <p>I would not do that for a PowerShell monitor, which you can schedule to run periodically, but for a script to run in the background, the above would work. You could even add some database access code to log the results to a database, or log it to a file.. what ever you want.</p>
<p><a href="http://sourceforge.net/projects/dirviewer/" rel="nofollow noreferrer">http://sourceforge.net/projects/dirviewer/</a> -- DirViewer is a light pure java application for directory tree view and recursive disk usage statistics, using JGoodies-Looks look and feel similar to windows XP.</p>
22,161
<p>Building a 3-D printer is obviously a huge undertaking.</p> <p>Does anyone know of any reasonably cheap guides to build my own 3-D printer?</p>
<p>Building a 3-D printer is actually very easy, assuming that you are electronically and mechanically competent, and there are a whole bunch of websites devoted to doing just that. The principal of which would be the <a href="http://reprap.org/wiki/Main_Page" rel="noreferrer">RepRapWiki</a>.</p> <p>There are a number of different designs, mostly from a few basic designs:</p> <ul> <li>Cartesian</li> <li>Delta</li> <li>Polar</li> <li>Scara</li> </ul> <p>Take a look at <a href="https://all3dp.com/know-your-fdm-3d-printers-cartesian-delta-polar-and-scara/" rel="noreferrer">3D Printers Explained: Delta, Cartesian, Polar, Scara</a>, for further details.</p> <p>I, personally, would suggest looking at the following 3D printer designs (although there are many more out there):</p> <ul> <li><a href="http://reprap.org/wiki/Prusa_i3" rel="noreferrer">Prusa i3</a> (arguably the most common/popular), or its derivative the <a href="http://reprap.org/wiki/P3Steel" rel="noreferrer">P3Steel</a></li> <li><a href="http://reprap.org/wiki/Category:Wilson_II" rel="noreferrer">Wilson II</a></li> <li><a href="http://reprap.org/wiki/Kossel" rel="noreferrer">Kossel</a></li> </ul> <p>On the web, i.e. eBay/Amazon, there are plenty of ready assembled versions, DIY kits, or you can source all of the individual parts yourself. I seriously recommend reading this question <a href="https://3dprinting.stackexchange.com/questions/409/what-are-the-pros-and-cons-of-collecting-parts-yourself-versus-getting-a-diy-ki">What are the pros and cons of collecting parts yourself, versus getting a DIY kit and then modifying it?</a></p> <p>I would strongly suggest that you do a <em>lot</em> of googling, and read around the subject for a couple of weeks: </p> <ul> <li>Reading other peoples blogs;</li> <li>Watching construction videos on YouTube to get a better understanding, and;</li> <li>Going through the issues that other people have experienced whilst building there own printers</li> </ul> <p>Doing this will help you glean a greater understanding of what is required, and what to expect when building yours - as well as getting an understanding of the individual parts required and how they all fit together.</p> <p>Spending a fair bit of time on this site, SE 3D Printing, and slowly going through the questions and answers is also strongly recommended.</p> <p>Building your own printer is, ultimately, more rewarding that purchasing a ready built one. This is because, due to its nascent nature of 3D printing, the printer that you purchase <em>will</em>, most likely, go wrong, and you will need to fix it. If you have built it yourself then you <em>should</em> be able to easily understand what is wrong, and then be capable of repairing it yourself. It is somewhat similar to the situation when the automobile first became popular, back in the 20's/30's (?) - the driver was, usually, also a mechanically competent engineer (unless they were filthy rich and were able to afford to pay a dedicated mechanic to accompany them - which was also the case, in those days). </p>
<p>If you just want to build your own, get a kit. There are several out there. Most kits take from 1-5 days to complete depending on the kit.</p> <p>If you want to design your own is quite a different story. The effort is totally dependent on how much you want to do yourself. My guess is the statement that you don't know the amount of effort indicates that you are probably not ready to design your own.</p>
638
<p>Is it possible to use a converter within a style? For instance I am trying to create a styled <code>TextBlock</code> whose text resizes based on the <code>ActualHeight</code> property of the <code>TextBlock</code>. The resizing would be done via a converter.</p>
<p>Yes, this is possible. For example:</p> <pre><code>&lt;Style TargetType="TextBlock"&gt; &lt;Setter Property="FontSize"&gt; &lt;Setter.Value&gt; &lt;Binding Path="ActualHeight" RelativeSource="{RelativeSource Self}"&gt; &lt;Binding.Converter&gt; &lt;MyConverter/&gt; &lt;/Binding.Converter&gt; &lt;/Binding&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; &lt;/Style&gt; </code></pre> <p>Depending on your exact scenario, you might also be able to use the more succinct:</p> <pre><code>&lt;Style TargetType="TextBlock"&gt; &lt;Setter Property="FontSize" Value="{Binding ActualHeight, RelativeSource={RelativeSource Self}, Converter={StaticResource MyConverter}}"/&gt; &lt;/Style&gt; </code></pre>
<p>I managed to get something similar to work by using:</p> <pre><code>&lt;Setter Property="Text"&gt; &lt;Setter.Value&gt; &lt;Binding Path="CompanyName"&gt; &lt;Binding.Converter&gt; &lt;conv:UppercaseConverter/&gt; &lt;/Binding.Converter&gt; &lt;/Binding&gt; &lt;/Setter.Value&gt; &lt;/Setter&gt; </code></pre> <p>Hope it works for you too.</p> <p>Yann</p> <p>PS - CompanyName is the name of the actual ViewModel property I was binding the textblock to</p>
49,647
<p>I can reset FPU's CTRL registers with this:</p> <p><a href="http://support.microsoft.com/kb/326219" rel="nofollow noreferrer">http://support.microsoft.com/kb/326219</a></p> <p>But how can I save current registers, and restore them later?</p> <p>It's from .net code..</p> <p>What I'm doing, is from Delphi calling an .net dll as an COM module. Checking the <kbd>Ctrl</kbd> registers in delphi yield one value, checking with controlfp in the .net code gives another value. What I need, is in essential is to do this:</p> <pre><code>_controlfp(_CW_DEFAULT, 0xfffff); </code></pre> <p>So my floatingpoint calculations in the .net code does not crash, but I want to restore the <kbd>Ctrl</kbd> registers when returning.</p> <p>Maybe I don't? Maybe Delphi is resetting them when needed? I blogged about this problem <a href="http://blog.neslekkim.net/2008/10/fpu-issues-when-interoping-delphi-and.html" rel="nofollow noreferrer">here</a>.</p>
<pre><code>uses SysUtils; var SavedCW: Word; begin SavedCW := Get8087CW; try Set8087CW($027f); // Call .NET code here finally Set8087CW(SavedCW); end; end; </code></pre>
<p>Same function you use to change them: <code>_controlfp()</code>. If you pass in a mask of 0, the current value won't be altered, but it <em>will</em> be returned - save it, and use a second call to <code>_controlfp()</code> to restore it later.</p>
23,239
<p>If I create an application on my Mac, is there any way I can get it to run on an iPhone without going through the app store?</p> <p>It doesn't matter if the iPhone has to be jailbroken, as long as I can still run an application created using the official SDK. For reasons I won't get into, I can't have this program going through the app store.</p>
<h1>Official Developer Program</h1> <p>For a standard iPhone you'll need to pay the US$99/yr to be a member of the developer program. You can then use the adhoc system to install your application onto up to 100 devices. The developer program has the details but it involves adding UUIDs for each of the devices to your application package. UUIDs can be easiest retrieved using <a href="http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=285691333&amp;mt=8" rel="noreferrer">Ad Hoc Helper</a> available from the App Store. For further details on this method, see Craig Hockenberry's <a href="http://furbo.org/2008/08/06/beta-testing-on-iphone-20/" rel="noreferrer">Beta testing on iPhone 2.0</a> article</p> <h1>Jailbroken iPhone</h1> <p>For jailbroken iPhones, you can use the following method which I have personally tested using the <a href="http://developer.apple.com/iphone/library/samplecode/AccelerometerGraph/index.html" rel="noreferrer">AccelerometerGraph</a> sample app on iPhone OS 3.0.</p> <h2>Create Self-Signed Certificate</h2> <p>First you'll need to create a self signed certificate and patch your iPhone SDK to allow the use of this certificate:</p> <ol> <li><p>Launch Keychain Access.app. With no items selected, from the Keychain menu select Certificate Assistant, then Create a Certificate.</p> <p>Name: iPhone Developer<br> Certificate Type: Code Signing<br> Let me override defaults: Yes </p></li> <li><p>Click Continue</p> <p>Validity: 3650 days</p></li> <li><p>Click Continue</p></li> <li><p>Blank out the Email address field.</p></li> <li><p>Click Continue until complete.</p> <p>You should see "This root certificate is not trusted". This is expected.</p></li> <li><p>Set the iPhone SDK to allow the self-signed certificate to be used:</p> <blockquote> <p>sudo /usr/bin/sed -i .bak 's/XCiPhoneOSCodeSignContext/XCCodeSignContext/' /Developer/Platforms/iPhoneOS.platform/Info.plist</p> </blockquote> <p>If you have Xcode open, restart it for this change to take effect.</p></li> </ol> <h2>Manual Deployment over WiFi</h2> <p>The following steps require <code>openssh</code>, and <code>uikittools</code> to be installed first. Replace <code>jasoniphone.local</code> with the hostname of the target device. Be sure to set your own password on both the <code>mobile</code> and <code>root</code> users after installing SSH.</p> <p>To manually compile and install your application on the phone as a system app (bypassing Apple's installation system):</p> <ol> <li><p>Project, Set Active SDK, Device and Set Active Build Configuration, Release.</p></li> <li><p>Compile your project normally (using Build, not Build &amp; Go).</p></li> <li><p>In the <code>build/Release-iphoneos</code> directory you will have an app bundle. Use your preferred method to transfer this to /Applications on the device.</p> <blockquote> <p><code>scp -r AccelerometerGraph.app root@jasoniphone:/Applications/</code></p> </blockquote></li> <li><p>Let SpringBoard know the new application has been installed:</p> <blockquote> <p><code>ssh mobile@jasoniphone.local uicache</code></p> </blockquote> <p>This only has to be done when you add or remove applications. Updated applications just need to be relaunched.</p></li> </ol> <p>To make life easier for yourself during development, you can setup SSH key authentication and add these extra steps as a custom build step in your project.</p> <p>Note that if you wish to remove the application later you cannot do so via the standard SpringBoard interface and you'll need to use SSH and update the SpringBoard:</p> <pre><code>ssh root@jasoniphone.local rm -r /Applications/AccelerometerGraph.app &amp;&amp; ssh mobile@jasoniphone.local uicache </code></pre>
<p>*Changes/Notes to make this work for <strong>Xcode 3.2.1</strong> and <strong>iPhone SDK 3.1.2</strong></p> <p>Manual Deployment over WiFi</p> <p>2) Be sure to restart Xcode after modifying the Info.plist</p> <p>3) The "uicache" command is not found, using killall -HUP SpringBoard worked fine for me.</p> <p>Other then that, I can confirm this works fine.</p> <p>Mac users, using PwnageTool 3.1.4 worked great for Jailbreaking (DL via torrent).</p>
5,813
<p>This is a little confusing to explain, so bear with me here...</p> <p>I want to set up a system where a user can send templated emails via my website, except it's not actually sent using my server - it instead just opens up their own local mail client with an email ready to go. The application would fill out the body of the email with predefined variables, to save the user having to type it themselves. They can then edit the message as desired, should it not exactly suit their purposes.</p> <p>There's a number of reasons I want it to go via the user's local mail client, so getting the server to send the email is not an option: it has to be 100% client-side.</p> <p>I already have a mostly-working solution running, and I'll post the details of that as an answer, I'm wondering if there's any better way?</p>
<p>The way I'm doing it now is basically like this:</p> <p>The HTML:</p> <pre><code>&lt;textarea id=&quot;myText&quot;&gt; Lorem ipsum... &lt;/textarea&gt; &lt;button onclick=&quot;sendMail(); return false&quot;&gt;Send&lt;/button&gt; </code></pre> <p>The Javascript:</p> <pre><code>function sendMail() { var link = &quot;mailto:me@example.com&quot; + &quot;?cc=myCCaddress@example.com&quot; + &quot;&amp;subject=&quot; + encodeURIComponent(&quot;This is my subject&quot;) + &quot;&amp;body=&quot; + encodeURIComponent(document.getElementById('myText').value) ; window.location.href = link; } </code></pre> <p>This, surprisingly, works rather well. The only problem is that if the body is particularly long (somewhere over 2000 characters), then it just opens a new email but there's no information in it. I suspect that it'd be to do with the maximum length of the URL being exceeded.</p>
<p>Send request to <a href="http://mandrillapp.com" rel="nofollow">mandrillapp.com</a>:</p> <pre><code>var xhttp = new XMLHttpRequest(); xhttp.onreadystatechange = function() { if (xhttp.readyState == 4 &amp;&amp; xhttp.status == 200) { console.log(xhttp.responseText); } } xhttp.open('GET', 'https://mandrillapp.com/api/1.0/messages/send.json?message[from_email]=mail@7995.by&amp;message[to][0][email]=zdanevich.vitaly@yaa.ru&amp;message[subject]=Заявка%20с%207995.by&amp;message[html]=xxxxxx&amp;key=oxddROOvCpKCp6InvVDqiGw', true); xhttp.send(); </code></pre>
34,097
<p>I'm trying to create a css reset that targets only my control. So the HTML will look something like this:</p> <pre><code>&lt;body&gt; &lt;img class="outterImg" src="sadkitty.gif" /&gt; &lt;div id="container" class="container"&gt; &lt;img class="innerImg" src="sadkitty.gif" /&gt; &lt;div class="subContainer"&gt; &lt;img class="innerImg" src="sadkitty.gif" /&gt; &lt;/div&gt; &lt;/div&gt; &lt;img class="outterImg" src="sadkitty.gif" /&gt; &lt;/body&gt; </code></pre> <p>The CSS is what I'm having trouble with, but I'm currently working with this:</p> <pre><code>img { // Bad style declarations for the entire page border: solid 3px red; width: 50px; } .container img, .container div, .container etc. { // Style reset for specific elements within my control "container" border: solid 3px blue; width: 100px; } .innerImg img { // The target style for the specific class/element within the control border: solid 3px green; width: 200px; } </code></pre> <p>The problem is that ".innerImg img" does not override ".container img" as I would expect. So, what would be the best method for resetting the style of all elements within the "container" element, and then placing styles on classes within that element?</p>
<p>The selector <code>.innerImg img</code> refers to an img element <em>inside</em> an element with the class innerImg. There's nothing like that in your document.</p> <p>What you probably want there is <code>img.innerImg</code> .</p> <p>Beyond that, there is a short calculation for <a href="http://www.w3.org/TR/css3-selectors/#specificity" rel="nofollow noreferrer">selector specificity</a> that determine which rule is followed. (That link contains my new favorite qualifier in any document: "in a number system with a large base")</p>
<p>I suspect this results in close to what you wanted. </p> <pre><code>img { border: solid 3px red; width: 50px; } .container .innerImg, .container div { border: solid 3px blue; width: 100px; } .container .subContainer { border: none; } .subContainer .innerImg { border: solid 3px green; width: 200px; } </code></pre>
43,401
<p>I am looking for a CMS that would be incredibly user-friendly and would have the following features:</p> <ul> <li>really simple message board (no login required)</li> <li>family tree</li> <li>story telling area</li> <li>photo section</li> <li>news section</li> </ul> <p>Is there anything out there like this that is really easily configurable? I've already messed around with Mambo and Family Connects, but I didnt like either of those. In the past I've just programmed my own websites, for lack of easily implementable features. However, I've assuming there's something I need out there just like this, that I can't find. Thanks.</p> <hr> <p>I don't want anyone to have to login, for one. The is for a family website, and much of my family really don't know what a website is, let alone how to use one. I want a super simple website with huge buttons and not a whole lot of distractions. Family Connects is a good example of what I want, except the photo album is horrible. I want people to post messages without logging in or signing up, and haven't seen that ability in mambo sites I've looked at.</p>
<p>I can understand your stipulation that your users (family) shouldn't have to sign up - but without a sign-in, your site will be a free-for-all for spammers, hackers and other bored Internet denizens. </p> <p>That said, my suggestion is to use WordPress for a front end - register your family members yourself, and use a very basic template - or better yet, create one.</p>
<p>I've setup <a href="http://www.cmsmadesimple.org/" rel="nofollow noreferrer">CMS Made Simple</a> a couple times now. It's all PHP and you can edit it to your heart's content. Give it a try.</p>
4,504
<p>I'm looking for best practices for performing strict (whitelist) validation/filtering of user-submitted HTML.</p> <p>Main purpose is to filter out XSS and similar nasties that may be entered via web forms. Secondary purpose is to limit breakage of HTML content entered by non-technical users e.g. via WYSIWYG editor that has an HTML view.</p> <p>I'm considering using <a href="http://htmlpurifier.org" rel="noreferrer">HTML Purifier</a>, or rolling my own by using an HTML DOM parser to go through a process like HTML(dirty)->DOM(dirty)->filter->DOM(clean)->HTML(clean).</p> <p>Can you describe successes with these or any easier strategies that are also effective? Any pitfalls to watch out for?</p>
<p>I've tested all exploits I know on HTML Purifier and it did very well. It filters not only HTML, but also CSS and URLs.</p> <p>Once you narrow elements and attributes to innocent ones, the pitfalls are in attribute content – <code>javascript:</code> pseudo-URLs (IE allows tab characters in protocol name - <code>java&amp;#09;script:</code> still works) and CSS properties that trigger JS.</p> <p>Parsing of URLs may be tricky, e.g. these are valid: <code>http://spoof.com:xxx@evil.com</code> or <code>//evil.com</code>. Internationalized domains (IDN) can be written in two ways – Unicode and punycode.</p> <p>Go with <a href="http://htmlpurifier.org" rel="nofollow noreferrer">HTML Purifier</a> – it has most of these worked out. If you just want to fix broken HTML, then use HTML Tidy (it's available as PHP extension).</p>
<p>The W3C has a big open-source package for validating HTML available here:</p> <p><a href="http://validator.w3.org/" rel="nofollow noreferrer">http://validator.w3.org/</a></p> <p>You can download the package for yourself and probably implement whatever they're doing. Unfortunately, it seems like a lot of DOM parsers seem to be willing to bend the rules to allot for HTML code "in the wild" as it were, so it's a good idea to let the masters tell you what's wrong and not leave it to a more practical tool--there are a lot of websites out there that <em>aren't</em> perfect, compliant HTML but that we still use every day.</p>
24,257
<p>I'm trying to create Excel 2007 Documents programmatically. Now, there are two ways I've found:</p> <ul> <li>Manually creating the XML, as outlined in <a href="https://stackoverflow.com/questions/150339/generating-an-excel-file-in-aspnet#150368">this post</a></li> <li>Using a Third Party Library like <a href="http://www.codeplex.com/ExcelPackage" rel="nofollow noreferrer">ExcelPackage</a>.</li> </ul> <p>Currently, I use ExcelPackage, which has some really serious drawbacks and issues. As I do not need to create overly complex Excel sheets (the most "complicated" thing is that I explicitely need to set a cell type to numeric or text), I 'm looking towards Option 1 next, but I just wonder if there are any other good and supported ways to generate Excel 2007 Sheets? Bonus Points if they can be created without having to save them to the harddrive, i.e. generate and directly output them into a stream.</p> <p>.net 3.0 is the target here, no 3.5 goodness :(</p> <p><strong>Edit:</strong> Thanks so far. The XML SDK is indeed 3.5 only, but Russian Roulet... erm... COM Interop is also something I want to avoid whenever possible, especially since Excel 2007 has a somewhat complicated but still rather easy to create document format. I'll have a look at the various links and hints posted.</p>
<p>You could try using the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=c6e744e5-36e9-45f5-8d8c-331df206e0d0&amp;DisplayLang=en" rel="noreferrer">Office Open XML SDK</a>. This will allow you to create Excel files in memory using say a <code>MemoryStream</code> and much more easily than generating all the XML by hand.</p> <p>As Brian Kim pointed out, version 2.0 of the SDK requires .NET 3.5 which you stated wasn't available. <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=AD0B72FB-4A1D-4C52-BDB5-7DD7E816D046&amp;displaylang=en" rel="noreferrer">Version 1</a> of the SDK is also available which supports .NET 3.0. It isn't as complete, but will at least help you manage the XML parts of the document and the relationships between them.</p>
<p>I used to generate <a href="http://msdn.microsoft.com/en-us/library/aa223586(office.11).aspx" rel="nofollow noreferrer">Wordprocessing Markup</a> documents using a library of functions for creating the correct XML for tables and paragraphs.</p> <p>I then just changed the MIME type for the Response header to be a word document and sent the XML as the response to the client. It either opens in their browser or saves as a file.</p> <p>There doesn't seem to be the same 2003 SDK for Excel although there is <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=AD0B72FB-4A1D-4C52-BDB5-7DD7E816D046&amp;displaylang=en" rel="nofollow noreferrer">MS Open XML SDK</a></p>
18,493
<p>How can I programmatically generate keypress events from Javascript code running in Safari? It looks like WebKit is using the DOM level 3 model for creating keyboard events from Javascript, and the DOM level 3 keyboard event model does not support the keypress event. Is there another way that I can use?</p> <p>I'm looking for as pure a Safari/WebKit DOM solution as possible. I'd really prefer not to modify the web page, and I'd also rather not add dependencies on external libraries. I need to activate any existing keypress handlers, so it won't work to add a new handler and directly call it.</p> <p>It looks like WebKit has the keyCode and charCode properties of the keypress event defined in its UIEvent class, but they are read-only. Is there any way to set those properties? The following does not work:</p> <pre><code>var evt = document.createEvent('UIEvents'); evt.initUIEvent('keypress', true, true, window, 0); evt.keyCode = 114; // 'r' evt.charCode = 114; alert("keyCode = " + evt.keyCode + ", charCode = " + evt.charCode); // both 0 </code></pre> <p>Setting the detail property in the call to initUIEvent also seems to have no effect.</p>
<p>Use the TextEvent (introduced by DOM3). Since you're looking to generate keypress events, I'm guessing you're working with characters. In the code below, textToInsert is a string, and textarea the element I'm dispatching the event to.</p> <pre><code>var eventObject = document.createEvent('TextEvent'); eventObject.initTextEvent('textInput', true, true, null, textToInsert); textarea.dispatchEvent(eventObject); </code></pre> <p>This works on Safari 3.1.2 (consequently on Chrome).</p>
<p><a href="http://docs.jquery.com/Events/keypress#fn" rel="nofollow noreferrer">http://docs.jquery.com/Events/keypress#fn</a></p> <p>In other words, you attach a keypress event to some element. Using an element with the ID of "someid", for example:</p> <pre><code>&lt;script language="text/javascript" src="jquery.js"&gt;&lt;/script&gt; &lt;script language="text/javascript"&gt; $(function() { // add a keypress handler $("#someid").keypress(function(e){ alert('you just pressed ' + e.which); }); // imitate the keypress $("#someid").keypress(); }); &lt;/script&gt; </code></pre>
44,949
<p>Like most developers, I'm a business developer, which in essence consists of slapping a UI onto some back-end data store. (We all know there's a lot more to it than that, but that's usually what it boils down to.)</p> <p>I understand that game development is very different from business development, but I'm having a hard time explaining it to a friend of mine. I was hoping the SO community could help me out here.</p> <p>To me, modern game developers deal a lot with manipulating 3-dimensional graphics. In gaming code (and I'm guessing here), you're assembling polygons (or something like that), rotating 'em, etc. This involves a different way of thinking from manipulating relational data (for instance). I don't know, really. I just know it's different.</p> <p><strong>EDIT:</strong></p> <p>I should stress that by "development" I mean "programming," not all of the aspects that go into creating a game or piece of business software. I'm sorry I didn't make that clear originally.</p> <p>Thanks!</p>
<p>I'm in game development but came from business development long ago. Game development is very rigorous in mathematics if you work on the physics or graphics side. Even AI can need quite a bit of mathematics for the low-level stuff. The hardware usually takes care of a lot of the polygon manipulation math as far as drawing on the screen goes. There is also a lot of involvement with generating the in-game data with (often) many tools that are run in a pre-processing step, and that too can be math-intensive if you are generating visibility data.</p>
<p>Performance is really the difference, from what I can tell. </p> <p>Technologywise, games are usually Windows/C++ driven.</p>
25,757
<p>I'm writing a report view of an audit trail, and I need to display this in a .jsp. What's the "best" way to get the data from the database to the screen?</p> <p>We're using Spring for dependency injection, Data Access Objects, and Hibernate. I can use hibernate or straight jdbc for this report.</p> <p>If I load all the records into memory I run out of memory.</p> <p>Any ideas that don't involve running the query in the jsp?</p>
<p>It seems like this is a natural place to use pagination of your Hibernate results -- run the query at the Servlet level, and paginate results in a way similar to how this person describes:</p> <p><a href="http://blog.hibernate.org/Bloggers/Everyone/Year/2004/Month/08/Day/14#pagination" rel="nofollow noreferrer">http://blog.hibernate.org/Bloggers/Everyone/Year/2004/Month/08/Day/14#pagination</a></p> <p>This is the easiest method of implementing Hibernate pagination I've seen...</p>
<p>Just use paging and only load a certain number of rows on the page at a time.</p>
12,144
<p>Why must <code>Type.Equals(t1, t2)</code> be used to determine equivalent types, and not the equality operator (e.g. for VB.NET, <code>t1 = t2</code>)? </p> <p>It seems inconsistent with other parts of the .NET API.</p> <p>Example in VB.NET:</p> <p><code>If GetType(String) = GetType(String) Then Debug.Print("The same, of course") End If</code></p> <p>causes a compile-time error of "<code>Operator '=' is not defined for types 'System.Type' and 'System.Type'.</code>"</p>
<p>Given the way types are loaded, that surprises me. Where did you hear this from?</p> <p>The <a href="http://msdn.microsoft.com/en-us/library/3ahwab82.aspx" rel="nofollow noreferrer">docs for System.Type.Equals(Type)</a> suggest that it's comparing via the <a href="http://msdn.microsoft.com/en-us/library/system.type.underlyingsystemtype.aspx" rel="nofollow noreferrer">UnderlyingSystemType</a> property, but I'm not sure under what circumstances two different Type objects would have the same underlying system type.</p> <p>I'd be really interested to see an example where this mattered... my <em>guess</em> is that from anywhere in "user code" they'll be the same thing, but there may be some cunning BCL code where it matters.</p>
<p>Looking at the source code in Reflector, I can't see how Type.Equals(t1,t2) would be handled any differently than t1 = t2. (There is actually no Type.Equals; it will actually call Object.Equals).</p> <p>In C#, T1 == T2 works just fine.</p>
36,931
<p>I'm not sure if the title is very clear, but basically what I have to do is read a line of text from a file and split it up into 8 different string variables. Each line will have the same 8 chunks in the same order (title, author, price, etc). So for each line of text, I want to end up with 8 strings.</p> <p>The first problem is that the last two fields in the line may or may not be present, so I need to do something with stringTokenizer.hasMoreTokens, otherwise it will die messily when fields 7 and 8 are not present.</p> <p>I would ideally like to do it in one while of for loop, but I'm not sure how to tell that loop what the order of the fields is going to be so it can fill all 8 (or 6) strings correctly. Please tell me there's a better way that using 8 nested if statements! </p> <p>EDIT: The String.split solution seems definitely part of it, so I will use that instead of stringTokenizer. However, I'm still not sure what the best way of feeding the individual strings into the constructor. Would the best way be to have the class expecting an array, and then just do something like this in the constructor:</p> <pre><code>line[1] = isbn; line[2] = title; </code></pre>
<p>The best way is to not use a StringTokenizer at all, but use String's <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/lang/String.html#split(java.lang.String)" rel="nofollow noreferrer">split</a> method. It returns an array of Strings, and you can get the length from that.</p> <p>For each line in your file you can do the following:</p> <pre><code>String[] tokens = line.split("#"); </code></pre> <p><code>tokens</code> will now have 6 - 8 Strings. Use <code>tokens.length()</code> to find out how many, then create your object from the array.</p>
<p>Is this a CSV or similar file by any chance? If so, there are libraries to help you, for example <a href="http://commons.apache.org/sandbox/csv/" rel="nofollow noreferrer">Apache Commons CSV</a> (link to alternatives on their page too). It will get you a String[] for each line in the file. Just check the array size to know what optional fields are present.</p>
29,255
<p>If I write Java software for a BlackBerry, can it be decompiled using freely available tools similar to <a href="http://www.red-gate.com/products/reflector/" rel="nofollow noreferrer">.NET Reflector</a>, or is it a more elaborate process?</p>
<p>Software you write for any language, any platform, can be decompiled. It doesn't matter what code mangling (obfuscation) tools you use, it can be decompiled.</p> <p>Any attempt to worry about this is going to be a waste of time. Just like DRM ;p</p> <p>But the real point is, and I wish I had the link to the discussion I am thinking of because it was very good. But the point is this. Some one can decompile it, and if they just straight recompile it and try and resell it, what has been the point? It's still easy peasy to take them to court and win.</p> <p>But you say "They can look at my code and figure out how I did it and redo it!". And to this I say: Don't flatter your self.</p> <p>Think if you could get your hands on the source code to Windows. There would be a lot of "WTF are they doing here"? And "boy I would have done things differently". A few moments where you scratch your chin and go "Wow, nice". But over all, it's nothing you wouldn't have come to on your own. The real value is the time they spent to truly wrap their heads around the issue and come up with a solution.</p> <p>Anyone who rips off your code won't be doing that. What is harder? writing new software or maintaining software? I think most developers would prefer the former.</p> <p>So someone decompiles your software and either sells it in such an obvious way that you can easily prosecute, or they take the time to fully wrap their mind around the problems and design their own which in the end (years later?) will probably be completely different from yours.</p> <p>It's just such a ridiculous scenario, I really wounder if anyone has ripped off a product by decompiling a competing product.</p> <p>Don't worry about some one "stealing" your code. It CAN be done and there is nothing you can do to prevent it, but it won't be done, because it's ridiculous.</p>
<p>Pretty much all software can be decompiled. The question is only the amount of involvement and resources required to pull it off.</p>
49,603
<p>What exactly are the advantages and disadvantages to using a register-based virtual machine versus using a stack-based virtual machine?</p> <p>To me, it would seem as though a register based machine would be more straight-forward to program and more efficient. So why is it that the JVM, the CLR, and the Python VM are all stack-based?</p>
<p>Implemented in hardware, a register-based machine is going to be more efficient simply because there are fewer accesses to the slower RAM. In software, however, even a register based architecture will most likely have the "registers" in RAM. A stack based machine is going to be just as efficient in that case.</p> <p>In addition a stack-based VM is going to make it a lot easier to write compilers. You don't have to deal with register allocation strategies. You have, essentially, an unlimited number of registers to work with.</p> <p><strong>Update:</strong> I wrote this answer assuming an interpreted VM. It may not hold true for a JIT compiled VM. I ran across <a href="http://static.usenix.org/events/vee05/full_papers/p153-yunhe.pdf" rel="noreferrer">this paper</a> which seems to indicate that a JIT compiled VM may be more efficient using a register architecture.</p>
<p>Stack based VMs are easier to generate code for.</p> <p>Register based VMs are easier to create fast implementations for, and easier to generate highly optimized code for.</p> <p>For your first attempt, I recommend starting with a stack based VM.</p>
19,840
<p>For a requirement i was asked to export information into a custom entity that was created in MS CRM 4.0. I am trying to do this programmatically and I have not found a single code that actually accomplishes this. I wrote code to check if a certain value for a field exists in the entity but creating a new entity seems to be a little bit of puzzle for me. Any help on this would be appreciated.</p>
<p>To create a custom entity from code, you need to use the MetadataService web service. The 'CreateEntity' method is used to create custom entities.</p> <p>The CRM SDK for v4.0 shows you how:</p> <p><a href="http://msdn.microsoft.com/en-us/library/cc156288.aspx" rel="nofollow noreferrer">CreateEntity Message (MetadataService)</a></p>
<p>Whats wrong with using the import from CSV function within MSCRM 4.0? It caters for custom entities (3.0 didn't) and allows good mapping functions and saving of the mappings?</p>
31,932
<p>To do the equivalent of Python list comprehensions, I'm doing the following:</p> <pre><code>some_array.select{|x| x % 2 == 0 }.collect{|x| x * 3} </code></pre> <p>Is there a better way to do this...perhaps with one method call?</p>
<p>If you really want to, you can create an Array#comprehend method like this:</p> <pre><code>class Array def comprehend(&amp;block) return self if block.nil? self.collect(&amp;block).compact end end some_array = [1, 2, 3, 4, 5, 6] new_array = some_array.comprehend {|x| x * 3 if x % 2 == 0} puts new_array </code></pre> <p>Prints:</p> <pre><code>6 12 18 </code></pre> <p>I would probably just do it the way you did though.</p>
<p>I think the most list comprehension-esque would be the following:</p> <pre><code>some_array.select{ |x| x * 3 if x % 2 == 0 } </code></pre> <p>Since Ruby allows us to place the conditional after the expression, we get syntax similar to the Python version of the list comprehension. Also, since the <code>select</code> method does not include anything that equates to <code>false</code>, all nil values are removed from the resultant list and no call to compact is necessary as would be the case if we had used <code>map</code> or <code>collect</code> instead.</p>
39,994
<p>I am using URLDownloadToFile to retrieve a file from a website. Subsequent calls return the original file rather than an updated version. I assume it is retrieving a cached version.</p>
<p>Call DeleteUrlCacheEntry with the same URL just prior to calling URLDownloadToFile. You will need to link against Wininet.lib</p>
<p>Could you add a harmless query parameter to the end of your URL?</p> <p><a href="https://stackoverflow.com/?CacheBuster=1020am">https://stackoverflow.com/?CacheBuster=1020am</a></p>
10,104
<p><strong>Background</strong></p> <p>I am capturing video using the video4linux 2 spec. It is captured using a C program in real-time. I also have a Java frontend that can run both locally and remotely. The remote side was easy, I just compress the images to JPEG and ship them over a mini-http server to the client that decompresses them and shows them on the screen.</p> <p>When we run locally, I would like some way IPC to connect directly to that memory and access the images from Java. Then, blit those to the screen using as little CPU power as possible. This is a "surveillance" type system so I could have 8-16 camera feeds running at a time.</p> <p><strong>Question</strong></p> <p>What is the most efficient way to move the image data (YUV420P) from the v4l2 mmap buffer to my Java app to display it on the screen? Please show code or point me to some api/specs if any are available.</p> <p><strong>Answer</strong></p> <p>In the interest of time, I decided to just use plain Sockets and send the data in RGB. I was able to drastically improve performance when the Java client is running on the same machine. I'm still sending JPEGs over the network if the client is running remotely. Next, I'll need to find an optimized JPEG decoder.</p> <p>By the way, this is not 2 clients, just my CameraStream widget reads and parses both types.</p>
<p>Unless you use a <code>Socket</code>, you're going to have to use JNI to hook into a more primitive IPC mechanism.</p> <p>Given that you've got a memory buffer containing the video data, you may be able to use the "shared memory" APIs to get access to that memory from within your JVM. Have a look at the man page for <code>shmat</code>.</p> <p>You'll also need some sort of signal to tell the Java client that new video data is available.</p>
<p>You could look into using JNI to expose the native memory. See the JNI APIs around Direct Byte Buffers.</p> <p>Once you expose your native memory like this in Java, copy the bytes from the DirectByteBuffer into Java byte[] arrays, and it should be much faster than your socket approach.</p>
35,154
<p>I have inherited an old crusty <code>PHP application</code>, and I'd like to refactor it into something a little nicer to deal with, but in a gradual manner. In perl's CPAN, there is a series of classes around Class::DBI that allow you to use database rows as the basis for objects in your code, with the library generating <code>accessor methods</code> etc as appropriate, but also allowing you to add additional methods.</p> <p>Does anyone know of something like this for PHP? Especially something that doesn't require wholesale adoption of a "framework"... bonus points if it works in PHP4 too, but to be honest, I'd love to have another reason to ditch that. :-)</p>
<p>It's now defunct but <a href="http://phpdbi.sourceforge.net/web/" rel="nofollow noreferrer">phpdbi</a> is possibly worth a look. If you're willing to let go of some of your caveats (the framework one), I've found that <a href="http://www.phpdoctrine.org/" rel="nofollow noreferrer">Doctrine</a> is a pretty neat way of accessing DBs in PHP. Worth investigating anyway.</p>
<p>The right thing to is to access the database via an abstraction layer in a way such if you change your RDBMS or how you implemented that access, you only have to modify this layer while all the rest of your application remains untouched. </p> <p>To do this, to free your application from knowing how to deal with the database, your abstraction layer for DB access must be implemented by a framework such as <a href="http://adodb.sourceforge.net/" rel="nofollow noreferrer">ADODB</a>. </p> <p>All the files related to this layer must be located in a sub directory:</p> <ul> <li>/ado</li> </ul> <p>In this directories you'll put all of your .php.inc files which contains general methods to access the database.</p>
2,973
<p>What tools are available for creating in process COM servers in Java?</p>
<p><a href="http://j-integra.intrinsyc.com/" rel="nofollow noreferrer">J-Integra</a> is the most comprehensive, complete solution you will probably find for using COM and Java together. The software has been used by many commercial products, big and small, to integrate COM and Java (both directions).</p>
<p>Another alternative is <a href="http://www.teamdev.com/comfyj/index.jsf" rel="nofollow noreferrer">JNI Wrapper/ComfyJ</a> - it allows you to either generate Java proxy classes or use IDispatch. You can also trap and broadcast events (IConnectionPoint) and implement COM servers.</p>
22,908
<p>Stack Overflow has a subversion version number at the bottom:</p> <blockquote> <p>svn revision: 679</p> </blockquote> <p>I want to use such automatic versioning with my <code>.NET Web Site/Application</code>, Windows Forms, WPD projects/solutions.</p> <p>How do I implement this?</p>
<p>Looks like Jeff is using <a href="https://web.archive.org/web/20090130045625/http://confluence.public.thoughtworks.org/display/CCNET/What+is+CruiseControl.NET" rel="nofollow noreferrer">CruiseControl.NET</a> based on some leafing through the podcast transcripts. This seems to have automated deployment capabilities from source control to production. Might this be where the insertion is happening?</p>
<p><code>$rev</code> and others like it are revisions for the individual files, so they won't change unless the file changes. The number on the webpage is (most likely, I'm assuming here) the svn revision number for the whole project. That is different than the file revisions, which others have been pointing to.</p> <p>In this case I assume that CCNET is pulling the revision number of the project and rewriting a part of the webpage with that number. Any CI solution should be able to do this, set this up myself with CCNET and Teamcity (although not webpages, but automatic versioning of deployment/assembly versions).</p> <p>In order for you to do this, use a CI solution that supports it, or use your build process (MSbuild/Nant) to store that version and write it to the files before "deploying" it.</p>
2,262
<p>I'd like to have a link in my ASP.NET web site that authenticated users click to download a windows app that is already pre-configured with their client ID and some site config data. My goal is no typing required for the user during the client app install, both for the user friendliness, and to avoid config errors from mis-typed technical bits. Ideally I'd like the web server-side code to run as part of the ASP.NET app. </p> <p>FogBugz seems to do something like this. There is a menu option within the web app to download a screenshot tool, and when you download and run the installer, it knows your particular FogBugz web address so it can send screenshots there. (Hey Joel, looking for a question to answer? <em>hint—hint</em>)</p>
<p>The way the FogBugz screenshot setup tool does this is that it appends a 256 byte block at the end of the setup program at the moment it is downloaded. In other words, the download script spits out all the bytes from setup.exe and then an extra 256 with the url for the FogBugz server, plus any padding.</p> <p>Windows ignores these extra bytes when the .exe is run (provided you turned off the CRC check for your setup installer - we're using <a href="http://www.innosetup.com" rel="nofollow noreferrer">InnoSetup</a>).</p> <p>After installation, we run the Screenshot program with a command line switch that tells it where the setup installer is. It looks at the end of the setup.exe and finds it's info, and then writes that to the registry so the user doesn't have to know it.</p>
<p>If it helps RegexBuddy does this also.</p>
5,634
<p>I need a way to determine whether the computer running my program is joined to any domain. It doesn't matter what specific domain it is part of, just whether it is connected to anything. I'm coding in vc++ against the Win32 API.</p>
<p>Straight from Microsoft: </p> <p><a href="http://support.microsoft.com/kb/179891" rel="noreferrer">How To Determine If a Windows NT/Windows 2000 Computer Is a Domain Member</a></p> <p>This approach uses the Windows API. From the article summary:</p> <blockquote> <p>This article describes how to determine if a computer that is running Windows NT 4.0 or Windows 2000 is a member of a domain, is a member of a workgroup, or is a stand-alone computer using the Local Security Authority APIs.</p> </blockquote> <p>The article also provides sample code for a small program that outputs whether the computer the program is running on is part of a domain, part of a workgroup, or a standalone computer.</p>
<p>what about from the name of the computer?</p> <p><strong>edit:</strong> this was a crapy 'answer' from way back. What I meant was cheching for the form <code>domain\name</code> in the computer name. That of course implies that you do know the name of the domain, it does not solves the issue of just knowing if the computer is in any domain.</p>
25,260
<p>In visual studio 2008, when we press Ctrl+F5, the ASP.NET Development Server is launched to simulate a Web Server. I'm wondering what server does it simulate? IIS6 or IIS7? Is it possible to customize what server it simulate?</p>
<p>It doesn't simulate a server as such, it runs on a server based on cassini that is written in .net and has source code available. I suppose it's more similar to IIS6 in that it does not support the IIS7 integrated pipeline feature. You can always choose to have VS use II6 or IIS7 if it's installed (depending on whether you have XP or Vista on your DEV PC).</p>
<p>Sorry, a question, not an answer: What are the server differences between IIS6 and II7 that matter to your code?</p> <p>For ASP.NET development, the web server itself is somewhat ASP.NET neutral. It forwards the request to the .NET framework, so THAT's the part that matters.</p> <p>More info here: <a href="http://msdn.microsoft.com/en-us/library/58wxa9w5.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/58wxa9w5.aspx</a></p> <p>Adding Morgan Cheng's comment into the answer: There is some difference between IIS6 and IIS7 on how to explain web.config. For example, to customize UrlRouteHandler, according to MSDN. IIS6 and IIS7 are different. Details in <a href="http://msdn.microsoft.com/en-us/library/system.web.routing.urlroutinghandler.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.web.routing.urlroutinghandler.aspx</a></p>
35,827
<p>How can I transform a website to be able to handle multi language (example : english, french, spanish)?</p> <p>I do not like the resource file because I feel limited and it's pretty long to build the list. Do you have any suggestion?</p> <h2>Update</h2> <p>For the moment the best way we found is to use an XML file and with some Xpath et get values.</p>
<p>Implicit localization (on the Visual Studio - Tools menu - Generate Local Resources) is about as easy as it can be. Write your pages in your default language, pick the menu option, and your resource files are created and can be sent to someone to translate. </p> <p>The resx file is just xml, so if the translation company wants you can transform it into (and out of) spreadsheets easily. </p> <p>Using a databases instead of resx as your backing store is not difficult. Rick Strahl has a good explanation and example code for a database-driven localization provider <a href="http://www.west-wind.com/presentations/wwDbResourceProvider/default.aspx" rel="noreferrer">here</a> - there's a nice built in localization editor too with interface to Google translations and Babelfish.</p>
<p>Another solution I am using is to create the language folders which contain the aspx pages containing all the required text in that particular language. </p> <p>The only problem here is how can you inject as little code as possible into those replicating pages. I am using a controller pattern here to do this, and then a object data source to get the data and bind it to the controls in all pages. </p> <p>In this way I have achieved the goal of getting rid of the resource files and I can keep the code behind in one place without replicating it (unless necessary). </p> <p>Edit: I would recommend a good CMS framework as well. </p>
22,845
<p>Lately I've been working on applications that are relatively data-oriented. In general, they tend to be editors for data represented by classes that are related in odd ways. I've been handling it by having a <code>UserControl</code> for each type of object and as the selection changes the program displays the appropriate editor for the object.</p> <p>The "framework" I have made for this feels clunky and messy. In general, I have a two-pane interface with an "item selection" control on the left and the "work area" on the right. The UI has to do most of the work of responding to item selections by determining what <code>UserControl</code> to display, and implementing behaviors like undo and asking if the user wants to save data before changing items can get messy. The inspiration for this post is a nice "make our build process easier" application I'm working on with a colleague but it's really out of hand to the extent that a well-designed rewrite will probably arrive faster than the current code will be completed.</p> <p>I've got a passing familiarity with the document/view architecture from reading a little bit of some C++ books. I understand the more modern counterpart to it in .NET might be the Composite UI Application block. The problem is I've never seen anything but quick walkthroughs or howtos on these topics. It's never from the viewpoint of "how you should design an application for this" but more from the viewpoint of "paste this into the application and you'll understand!" I've spent an hour or two digging through the CAB documentation but it's somewhat confusing to me. I don't like the CAB mainly because I'm curious how things work under the hood and I think I'd appreciate it more if I were able to implement a simple version of a similar pattern before I dive into using a framework.</p> <p>What I really think I need is a website or book focused on this issue. The big part I don't seem to get is how to separate concerns into the appropriate places; I'm used to designing my data classes with several methods to work with the data, and it seems like maybe that's the job of a controller object? What sources do you find useful for an introduction to this subject? I've seen lots of articles that draw nice diagrams like <a href="http://upload.wikimedia.org/wikipedia/commons/2/2e/ModelViewControllerDiagram.svg" rel="nofollow noreferrer">this</a> and I get the high-level idea of how these architectures work. I don't think I've ever found the right source to teach me the low-level "how to implement it" part.</p>
<p>I find <a href="http://www.martinfowler.com/eaaDev/uiArchs.html" rel="nofollow noreferrer">this article</a> by Martin Fowler to be an excellent overview of a variety of UI architectures. Hope it helps :)</p>
<p>I accepted @Luke H's answer because it ultimately led me to several resources that are pretty decent.</p> <ul> <li>Martin Fowler's books look top-notch and are in my queue.</li> <li><a href="http://codebetter.com/blogs/jeremy.miller/archive/2007/07/25/the-build-your-own-cab-series-table-of-contents.aspx" rel="nofollow noreferrer">The Build Your Own CAB Series</a> by Jeremy Miller does a really good job.</li> <li>It looks like I'm a little too ignorant of design patterns to continue, so I'm reading Head-First Design Patterns followed by the Gang of Four book to help there; after that I plan on digesting Fowler's works.</li> </ul>
14,226
<p>3/10/2008 = 1822556159</p> <p>2/10/2008 = 1822523391</p> <p>1/10/2008 = 1822490623</p> <p>30/09/2008 = 1822392319</p> <p>29/09/2008 = 1822359551</p> <p>This is all the information that I know at the current time. </p> <p>Dates increment by 32768 except when changing month when the increment is 32768 x 2 (65536).</p> <p>Has anyone seen this binary date format and how can I extract the correct date?</p> <hr> <p>It is possible that the remaining portion of the date is for time (hours, minutes, seconds)</p>
<p>September 30th 2008</p> <pre><code>1822392319 = 0x6c9f7fff 0x6c = 108 = 2008 (based on 1900 start date) 0x9 = 9 = September 0xf7fff - take top 5 bits = 0x1e = 30 </code></pre> <p>October 1st 2008</p> <pre><code>1822490623 = 0x6ca0ffff 0x6c = 108 = 2008 0xa = 10 = October 0x0ffff - take top 5 bits = 0x01 = 1 </code></pre> <p>It's anyone's guess what the remaining 15 one-bits are for, if anything.</p> <p>EDIT: by take top 5 bits I mean:</p> <pre><code>day_of_month = (value &gt;&gt; 15) &amp; 0x1f </code></pre> <p>Similarly:</p> <pre><code>year = (value &gt;&gt; 24) &amp; 0xff + 1900 month = (value &gt;&gt; 20) &amp; 0x0f </code></pre>
<p>32768 is 2^15; they're reserving 15 bits for the days, which I don't think divides evenly into any useful combination of hours, minutes, and/or seconds.</p>
35,046
<p>This is a tricky one and I've always relied on techniques, such as permission-based emails (i.e. only sending to people you have permission to send to) and not using blatantly <em>spamish</em> terminology.</p> <p>Of late, some of the emails I send out programmatically have started being shuffled into people's spam folder automatically and I'm wondering what I can do about it.</p> <p>This is despite the fact that these particular emails are not ones that humans would mark as spam, specifically, they are emails that contain license keys that people have paid good money for, so I don't think they're going to consider them spam</p> <p>I figure this is a big topic in which I am essentially an ignorant simpleton.</p>
<p>Use email authentication methods, such as <a href="http://en.wikipedia.org/wiki/Sender_Policy_Framework" rel="nofollow noreferrer">SPF</a>, and <a href="https://help.ubuntu.com/community/Postfix/DKIM" rel="nofollow noreferrer">DKIM</a> to prove that your emails and your domain name belong together, and to prevent spoofing of your domain name. The SPF website includes a wizard to generate the DNS information for your site.</p> <p><a href="http://remote.12dt.com/" rel="nofollow noreferrer">Check</a> your <a href="http://en.wikipedia.org/wiki/Reverse_DNS_lookup" rel="nofollow noreferrer">reverse DNS</a> to make sure the IP address of your mail server points to the domain name that you use for sending mail.</p> <p>Make sure that the IP-address that you're using is <a href="http://www.spamhaus.org/lookup.lasso" rel="nofollow noreferrer">not on a blacklist</a></p> <p>Make sure that the reply-to address is a valid, existing address.</p> <p>Use the full, real name of the addressee in the To field, not just the email-address (e.g. <code>&quot;John Smith&quot; &lt;john@blacksmiths-international.com&gt;</code> ).</p> <p>Monitor your abuse accounts, such as <code>abuse@yourdomain.example</code> and <code>postmaster@yourdomain.example</code>. That means - make sure that these accounts exist, read what's sent to them, and act on complaints.</p> <p>Finally, make it <strong>really</strong> easy to unsubscribe. Otherwise, your users will unsubscribe by pressing the <strong>spam</strong> button, and that will affect your reputation.</p> <p>That said, getting Hotmail to accept your emails remains a black art.</p>
<p>To allow <strong>DMARC</strong> checks for SPF to pass and also be <strong>aligned</strong> when using sendmail, make sure you are setting the envelope sender address (<code>-f</code> or <code>-r</code> parameter) to something that matches the domain in the <code>From:</code> header address.</p> <h2>With PHP:</h2> <p>Using PHP's built-in <code>mail()</code> function without setting the 5th paramater will cause DMARC SPF checks to be unaligned if not done correctly. By default, sendmail will send the email with the webserver's user as the <a href="https://www.rfc-editor.org/rfc/rfc5321" rel="nofollow noreferrer">RFC5321</a>.MailFrom / Return Path header.</p> <p>For example, say you are hosting your website <code>domain.com</code> on the <code>host.com</code> web server. If you do not set the additional parameters parameter:</p> <pre class="lang-php prettyprint-override"><code>mail($to,$subject,$message,$headers); // Wrong way </code></pre> <p>The email recipient will receive an email with the following mail headers:</p> <pre><code>Return-Path: &lt;your-website-user@server.host.com&gt; From: &lt;your-website-user@domain.com&gt; </code></pre> <p>Even though this passes SPF checks, it will be unaligned (since domain.com and host.com do not match), which means that DMARC SPF check will fail as unaligned.</p> <p>Instead, you <strong>must</strong> pass the envelope sender address to sendmail by including the 5th parameter in the PHP <code>mail()</code> function, for example:</p> <pre class="lang-php prettyprint-override"><code>mail($to,$subject,$message,$headers, '-r bounce_email@domain.com'); // Right way </code></pre> <p>In this case, the email recipient will receive an email with the following mail headers:</p> <pre><code>Return-Path: &lt;bounce_email@domain.com&gt; From: &lt;your-website-user@domain.com&gt; </code></pre> <p>Since both of these headers contain addresses from <code>domain.com</code>, SPF will pass and also be aligned, which means that DMARC will also pass the SPF check.</p>
2,286
<p>I like putting shortcuts of the form "g - google.lnk" in my start menu so google is two keystrokes away. Win, g.</p> <p>My eight or so most frequent applications go there.</p> <p>I also make links to my solution files I am always opening "x - Popular Project.lnk"</p> <p>Are there any better ways to automate opening frequently used applications?</p>
<p><a href="http://www.autohotkey.com/" rel="nofollow noreferrer">AutoHotkey</a> is a reasonably good program for implementing windows key shortcuts. You might instead define WIN + G to be "open browser to google" which gives you a better response time (don't have to wait for start menu to popup, etc)</p> <p>There are macro programs that change the macros used based on the window that's in focus. I've never needed that much control, but you might want to look into that.</p> <p>-Adam</p>
<p>For shortcuts I use <strong>Launchy</strong></p> <p>For macros I use <strong>AutoHotKey</strong></p> <p>Others will suggest <strong>SlickRun</strong> for shortcuts also.</p>
6,608
<p>I have this ListBox which is bound to an ObservableCollection. Each object in the list implements an interface called ISelectable </p> <pre><code>public interface ISelectable : INotifyPropertyChanged { event EventHandler IsSelected; bool Selected { get; set; } string DisplayText { get; } } </code></pre> <p>I want to keep track of which object is selected regardless of how it is selected. The user could click on the representation of the object in the ListBox but it could also be that an object is selected via code. If the user selects an object via the ListBox I cast the the selected item to an ISelectable and set the Selected property to true.</p> <pre><code>ISelectable selectable = (ISelectable)e.AddedItems[0]; selectable.Selected = true; </code></pre> <p>My problem is that when I select the object using code I can't get ListBox to change the selected item. I'm using a DataTemplate to show the selected object in a different color which means everything is displayed correctly. But the ListBox has the last object the user clicked as the SelectedItem which means that item can't be clicked without first selecting another object in the list.</p> <p>Anyone got any idea on how to solve this? I pretty sure I can accomplish what I want by writing some custom code to handle the Mouse and Keyboard events but I rather not. I have tried adding a SelectedItem property to the collection and bind it to the ListBox's SelectItemProperty but no luck. </p>
<p>You could also accomplish this by data binding ListBoxItem.IsSelected to your Selected property. The idea is to set the binding for each of the ListBoxItems as they are created. This can be done using a style that targets each of the ListBoxItems generated for the ListBox.</p> <p>This way when an item in the ListBox is selected/unselected, the corresponding Selected property will be updated. Likewise setting the Selected property in code will be reflected in the ListBox</p> <p>For this to work the Selected property must raise the PropertyChanged event.</p> <pre><code>&lt;List.Resources&gt; &lt;Style TargetType="ListBoxItem"&gt; &lt;Setter Property="IsSelected" Value="{Binding Path=DataContext.Selected, RelativeSource={RelativeSource Self}}" /&gt; &lt;/Style&gt; &lt;/List.Resources&gt; </code></pre>
<p>I think you should fire the propertyChanged event when the select has changed. Add this code to the object that implements ISelectable. You'll end up with something like: </p> <pre><code>private bool _Selected; public bool Selected { get { return _Selected; } set { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs("Selected")); _Selected = value; } } </code></pre> <p>I've tried the folowing code: </p> <pre><code>public ObservableCollection&lt;testClass&gt; tests = new ObservableCollection&lt;testClass&gt;(); public Window1() { InitializeComponent(); tests.Add(new testClass("Row 1")); tests.Add(new testClass("Row 2")); tests.Add(new testClass("Row 3")); tests.Add(new testClass("Row 4")); tests.Add(new testClass("Row 5")); tests.Add(new testClass("Row 6")); TheList.ItemsSource = tests; } private void Button_Click(object sender, RoutedEventArgs e) { tests[3].Selected = true; TheList.SelectedItem = tests[3]; } </code></pre> <p>where testClass implements ISelectable. </p> <p>The is a piece of xaml, nothing fancy:</p> <pre><code>&lt;ListBox Grid.Row="0" x:Name="TheList"&gt;&lt;/ListBox&gt; &lt;Button Grid.Row="1" Click="Button_Click"&gt;Select 4th&lt;/Button&gt; </code></pre> <p>I hope this helps. </p>
33,725
<p>I'm building a auto updater and I need to know what kind of upload speeds people get on a 56K modem?</p>
<p>Theoretically 33.6 kbit/s upload = 4.2 kB/s[1].</p> <p>From own experience, I would say half of that :)</p> <p>[1] <a href="http://en.wikipedia.org/wiki/ITU-T_V-Series_Recommendations#Simultaneous_transmission_of_data_and_other_signals" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/ITU-T_V-Series_Recommendations#Simultaneous_transmission_of_data_and_other_signals</a></p>
<p>According to <a href="http://en.wikipedia.org/wiki/Modem" rel="nofollow noreferrer">Wikipedia</a>, the top (theoretical) speed is 48kbit/s. This is assuming v.92, which a large percentage of users will not have.</p>
31,141
<p>I'm trying to install the Python Imaging Library 1.1.6 for Python 2.6. After downloading the installation executable (Win XP), I receive the following error message:</p> <p>"Application failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem"</p> <p>Any thoughts on what I have done / not done? The application has not been installed, and I can't import the module through the IDLE session. Thoughts?</p>
<p>It looks like an SxS ("side-by-side") issue. Probably the runtime libraries PIL is linked against are missing. Try installing a redistributable package of a compiler which was used to build PIL.</p> <p><a href="http://www.microsoft.com/downloads/details.aspx?familyid=200B2FD9-AE1A-4A14-984D-389C36F85647&amp;displaylang=en" rel="nofollow noreferrer">MSVC 2005 redist</a></p> <p><a href="http://www.microsoft.com/downloads/details.aspx?familyid=D5692CE4-ADAD-4000-ABFE-64628A267EF0&amp;displaylang=en" rel="nofollow noreferrer">MSVC 2008 redist</a></p>
<p>I am shooting in the dark: could it be <a href="http://effbot.org/zone/python-register.htm" rel="nofollow noreferrer">this</a>?</p>
41,639
<p>When adding an EditItemTemplate of some complexity (mulitple fields in one template), and then parsing the controls from the RowUpdating event, the controls that were manually entered by the user have no values. My guess is there is something going on with when the data is bound, but I've had instances where simply adding and attribute to a control in codebehind started the behavior and removing that code made the code work. As a work-around, I can Request(controlname.UniqueId) to get it's value, but that is rather a hack.</p> <p><strong>Edit</strong> When I access the value like so</p> <pre><code>TextBox txtValue = gvwSettings.SelectedRow.FindControl("txtValue") as TextBox; </code></pre> <p>the text box is found, but the .Text is not the user input.</p>
<p>Did you turn off ViewState? Did you add control programmatically in the template? If so, did you create them at the correct stage?</p>
<p>You should be able to use the GridViewUpdateEventArgs to retrieve the inputted value, for example: </p> <pre><code>TextBox txtValue = gvwSettings.SelectedRow.FindControl("txtValue") as TextBox; </code></pre> <p>I have used that syntax before and it works like a charm.</p>
17,995
<p>I've <code>rm</code>'ed a 2.5gb log file - but it doesn't seemed to have freed any space.</p> <p>I did:</p> <pre><code>rm /opt/tomcat/logs/catalina.out </code></pre> <p>then this:</p> <pre><code>df -hT </code></pre> <p>and <code>df</code> reported my <code>/opt</code> mount still at 100% used.</p> <p>Any suggestions?</p>
<p>Restart tomcat, if the file is in use and you remove it, the space becomes available when that process finishes.</p>
<p>Is the rm journaled/scheduled? Try a 'sync' command for force the write.</p>
43,096
<p>Is there a way to install all versions of all browsers on one machine?</p>
<p>I use virtual machines to do different browser version configurations. I'm assuming you want to test different version of IE, Firefox etc.</p> <p>If you automate your testing at any point the virtual machines are also handy for having a way to store many different configurations for testing on one machine.</p>
<p>Yes. I have IE8 Beta2, FF3, Chrome Beta, and Safari 3.1.2 with the applicable developer plugins.</p>
34,457
<p>How do I check to see if a variable is a number, or contains a number, in UNIX shell?</p>
<pre><code>if echo $var | egrep -q '^[0-9]+$'; then # $var is a number else # $var is not a number fi </code></pre>
<pre><code>a=123 if [ `echo $a | tr -d [:digit:] | wc -w` -eq 0 ] then echo numeric else echo ng fi </code></pre> <blockquote> <p>numeric</p> </blockquote> <pre><code>a=12s3 if [ `echo $a | tr -d [:digit:] | wc -w` -eq 0 ] then echo numeric else echo ng fi </code></pre> <blockquote> <p>ng</p> </blockquote>
39,909
<p>Does anybody here have positive experience of working with MS SQL Server 2005 from Rails 2.x?</p> <p>Our developers use Mac OS X, and our production runs on Linux. For legacy reasons we should use MS SQL Server 2005.</p> <p>We're using ruby-odbc and are running into various problems, too depressing to list here. I get an impression that we're doing something wrong. </p> <p>I'm talking about the no-compromise usage, that is, with migrations and all.</p> <p>Thank you,</p>
<p>Have you considered using JRuby? Microsoft has a <a href="http://msdn.microsoft.com/en-us/data/aa937724.aspx" rel="nofollow noreferrer">JDBC driver for SQL Server</a> that can be run on UNIX variants (it's pure Java AFAIK). I was able to get the 2.0 technology preview working with JRuby and Rails 2.1 today. I haven't tried migrations yet, but so far the driver seems to be working quite well.</p> <p>Here's a rough sketch of how to get it working:</p> <ol> <li>Make sure Java 6 is installed</li> <li>Install JRuby using the instructions on the <a href="http://www.jruby.org/" rel="nofollow noreferrer">JRuby website</a></li> <li>Install Rails using gem (<code>jruby -S gem install rails</code>)</li> <li>Download the UNIX package of <a href="http://msdn.microsoft.com/en-us/data/aa937724.aspx" rel="nofollow noreferrer">Microsoft's SQL Server JDBC driver</a> (Version 2.0)</li> <li>Unpack Microsoft's SQL Server driver</li> <li>Find sqljdbc4.jar and copy it to JRuby's lib directory</li> <li><code>jruby -S gem install activerecord-jdbcmssql-adapter</code></li> <li>Create a rails project (<code>jruby -S rails hello</code>)</li> <li>Put the proper settings in database.yml (example below)</li> <li>You're all set! Try running <code>jruby script/console</code> and creating a model.</li> </ol> <pre> development: host: localhost adapter: jdbc username: sa password: kitteh driver: com.microsoft.sqlserver.jdbc.SQLServerDriver url: jdbc:sqlserver://localhost;databaseName=mydb timeout: 5000 </pre> <p>Note: I'm not sure you can use Windows Authentication with the JDBC driver. You may need to use SQL Server Authentication.</p> <p>Best of luck to you!</p> <p>Ben</p>
<p>I would strongly suggest you weigh up migrating from the legacy database. You'll probably find yourself in a world of pain pretty quickly. From experience, Rails and legacy schemas don't go too well together either.</p> <p>I don't think there's a "nice solution" to this one, I'm afraid.</p>
9,272
<p>I'm still learning Grails and seem to have hit a stumbling block.</p> <p><strong>Here are the 2 domain classes:</strong></p> <pre><code>class Photo { byte[] file static belongsTo = Profile } class Profile { String fullName Set photos static hasMany = [photos:Photo] } </code></pre> <p><strong>The relevant controller snippet:</strong> </p> <pre><code>class PhotoController { def viewImage = { def photo = Photo.get( params.id ) byte[] image = photo.file response.outputStream &lt;&lt; image } } </code></pre> <p><strong>Finally the GSP snippet:</strong></p> <pre><code>&lt;img class="Photo" src="${createLink(controller:'photo', action:'viewImage', id:'profileInstance.photos.get(1).id')}" /&gt; </code></pre> <p>Now how do I access the photo so that it will be shown on the GSP? I'm pretty sure that <code>profileInstance.photos.get(1).id</code> is not correct.</p>
<p>As it is a Set, if you want the first element, you will have to go:</p> <pre><code>profileInstance.photos.toArray()[0].id </code></pre> <p>or</p> <pre><code>profileInstance.photos.iterator().next() </code></pre>
<p>My guess is you need to set the content type of the response stream. Something like:</p> <pre><code>response.ContentType = "image/jpeg" </code></pre> <p>This may or may not need to be before you stream to the response stream (can't imagine that it would matter). I'd just put it before the outputStream line in your code above.</p>
32,393
<p>I am running a query on Sybase ASE that produces a <code>ResultSet</code> that I then traverse and write the contents out to a file. Sometimes, this will throw a <code>NullPointerException</code>, stating that the <code>ResultSet</code> is <code>null</code>. However, it will do this after printing out one or two records. Other times, with the same exact input, I will receive no errors.</p> <p>I have been unable to consistently produce this error. The error message is pointing to a line:</p> <pre><code>output.print(rs.getString(1)); </code></pre> <p>It appears to happen when the query takes a little longer to run, for some reason. The recordset returns thus far have been very small (4 to 7 records). Sometimes I'll have to run the app 3 or 4 times, then the errors will just stop, as though the query was getting "warmed up". I've run the query manually and there doesn't appear to be any performance problems.</p> <p>Thanks again!</p>
<p>I hope you will be doing it well, I mean after calling <em>rs.next()</em>. </p> <p>According to the specs. the ResultSet object should never be <em>null</em>, in any case. Even if no records found. Posting the code snippet and the stack trace would definitely help us in giving you a better answer.</p> <p><strong>EDIT:</strong> Since, the error is pointing to that line. It might be calling <em>toString()</em> method on <em>null</em> String, that caused NullPointerException. Not sure though, it doesn't happen in standard output (System.out.println()) if the passed argument is of String type. But you are using <em>output.print()</em>, so I am not sure about this. It might be calling <em>toString()</em> on the passed String argument, behind the scene.</p>
<p>try wrap the stuff for accessing the data like :</p> <p>if(rs!=null &amp;&amp; rs.next()) {</p> <p>// read the stuff</p> <p>}</p> <p>if still persists will advice to check the read value for null itself.</p>
49,324
<p>Whenever I try to add a new project to my SourceSafe repository it creates 3 folders with the same name nested within each other. There is only one folder on my drive yet in Sourcesafe there are 3??</p> <p>Can anyone suggest what may be causing this?</p> <p>Thanks</p>
<p>If you drag and rop a new project folder into VSS and do a recursive add then that's just how it works. Otherwise you have to create your own root project folder in VSS and add each file one at a time to VSS by hand. </p>
<p>well, that problem comes due to visual studio. because visual stuio by default save solution file in the my documents/...../.../vs 2008/projects/ location and that address is also saved in the .sln file.</p> <p>that's why every time you get latest within visual stuio it try to creat same strucute and make another copy with in the main project folder.</p> <p>Solution, well i still trying to figure out how to tackle it.</p> <p>cheers, Genious</p>
15,562
<p>I am trying to do some string concatenation/formatting, but it's putting all the parameters into the first placeholder.</p> <p><strong>Code</strong></p> <pre><code>function CreateAppPoolScript([string]$AppPoolName, [string]$AppPoolUser, [string]$AppPoolPass) { # Command to create an IIS application pool $AppPoolScript = "cscript adsutil.vbs CREATE ""w3svc/AppPools/$AppPoolName"" IIsApplicationPool`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserName"" ""$AppPoolUser""`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/WamUserPass"" ""$AppPoolPass""`n" $AppPoolScript += "cscript adsutil.vbs SET ""w3svc/AppPools/$AppPoolName/AppPoolIdentityType"" 3" return $AppPoolScript } $s = CreateAppPoolScript("name", "user", "pass") write-host $s </code></pre> <p><strong>Output</strong></p> <pre class="lang-none prettyprint-override"><code>cscript adsutil.vbs CREATE "w3svc/AppPools/name user pass" IIsApplicationPool cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserName" "" cscript adsutil.vbs SET "w3svc/AppPools/name user pass/WamUserPass" "" cscript adsutil.vbs SET "w3svc/AppPools/name user pass/AppPoolIdentityType" 3 </code></pre>
<p>Lose the parentheses and commas. </p> <p>Calling your function as:</p> <pre><code>$s = CreateAppPoolScript "name" "user" "pass" </code></pre> <p>gives:</p> <pre class="lang-none prettyprint-override"><code>cscript adsutil.vbs CREATE "w3svc/AppPools/name" IIsApplicationPool cscript adsutil.vbs SET "w3svc/AppPools/name/WamUserName" "user" cscript adsutil.vbs SET "w3svc/AppPools/name/WamUserPass" "pass" cscript adsutil.vbs SET "w3svc/AppPools/name/AppPoolIdentityType" 3 </code></pre>
<p>Paul's right.<br> In PowerShell, function parameters are not enclosed in parenthesis. (Method parameters still are.)<br> Your initial call was just passing one big array to the function, rather than the three separate parameters you wanted.</p>
4,277
<p>I have a PHP script that initialises an image gallery. It loops through all images, checks if they are thumbnailed and watermarks them.</p> <p>My shared hosting account only lets me have 30 seconds of execution per script, as set in the php.ini settings. I can't change that.</p> <p>What can I do to get round this? Currently I refresh the page after every 5 images, this prevents the script timing out, but the browser recognises that the script won't complete and gives an error. That's ok, but it's not really user friendly.</p> <p>Any suggestions?</p>
<p>three ideas:</p> <ol> <li><p>you could offload this to a script that runs on the server (PHP CLI perhaps?) and have your current script check the progress (still running! check back later!).</p></li> <li><p>if javascript is ok in your environment, perhaps you could make ajax calls to handle this as well. the first solution allows the user to keep wandering around the site though, not sure if that's an important consideration in your case.</p></li> <li><p>you could get the PHP script to just do a certain batch (say 10 images at a time), then refresh the page with a progress report and go for 10 more, instead of an arbitrary time based refresh.</p></li> </ol>
<p>What about some kind of task list, for example:</p> <ol> <li>First script makes a list of images that need thumbnails or watermarking</li> <li>Second script checks this list and does the first 5 or so (however many can be done in the time limit) and removes them from the list</li> <li>Have the script in step 2 return a value that tells you if the list is empty, if not then repeat step 2 (probably easiest with ajax)</li> </ol> <p>Using this method, the only thing 'running' for the whole time is the page in your browser, each script only runs for 30 seconds.</p>
23,820
<p>I am looking for a good way to consistently test my web applications from the end users point of view. I have all kinds of ways to check to make sure my code is working behind the scenes. I can't count the number of times that I make a change to a piece of code, test it and it works fine and then deploy it only to have it blow up somewhere else weeks later. I have by that time forgotten the change I made that caused it to blow up. I need something that I can run every time I make a change to assure me I did not break something somewhere else.</p> <p>It needs to be able to input correct and incorrect entries so that client side validation can be tested also.</p> <p>Thank you,</p> <p>Scott and the Dev Team</p>
<p>I thin you need to investigate <a href="http://selenium.openqa.org/" rel="nofollow noreferrer">Selenium</a>. We use it to do automated UI testing throughout our solution, and it is cross browser and cross platform.</p> <p>You can use the <a href="http://selenium-ide.openqa.org/" rel="nofollow noreferrer">Selenium IDE</a> to record a walkthrough of your web application, and then you can either run it in the browser, or export it to various languages such as C#, and run it using NUnit. I find this is the easiest approach because I can create the basic walkthrough and then modify the code to use inputs from a file/database in order to create multiple scenarios.</p>
<p>Have a look at <a href="http://teststack.github.com/TestStack.Seleno/" rel="nofollow noreferrer">Seleno</a>, which abstracts Selenium / Browser interaction into C# Page Objects which represent the pages of your site. More details in <a href="https://stackoverflow.com/a/14153528/169334">this answer</a>.</p>
11,712
<p>I'm a newbie when it comes to SQL. When creating a stored procedure with parameters as such:</p> <pre><code>@executed bit, @failure bit, @success bit, @testID int, @time float = 0, @name varchar(200) = '', @description varchar(200) = '', @executionDateTime nvarchar(max) = '', @message nvarchar(max) = '' </code></pre> <p>This is the correct form for default values in T-SQL? I have tried to use NULL instead of ''. </p> <p>When I attempted to execute this procedure through C# I get an error referring to the fact that description is expected but not provided. When calling it like this:</p> <pre><code> cmd.Parameters["@description"].Value = result.Description; </code></pre> <p>result.Description is null. Should this not default to NULL (well '' in my case right now) in SQL? </p> <p>Here's the calling command:</p> <pre><code> cmd.CommandText = "EXEC [dbo].insert_test_result @executed, @failure, @success, @testID, @time, @name, @description, @executionDateTime, @message;"; ... cmd.Parameters.Add("@description", SqlDbType.VarChar); cmd.Parameters.Add("@executionDateTime", SqlDbType.VarChar); cmd.Parameters.Add("@message", SqlDbType.VarChar); cmd.Parameters["@name"].Value = result.Name; cmd.Parameters["@description"].Value = result.Description; ... try { connection.Open(); cmd.ExecuteNonQuery(); } ... finally { connection.Close(); } </code></pre>
<p>A better approach would be to change the CommandText to just the name of the SP, and the CommandType to StoredProcedure - then the parameters will work much more cleanly:</p> <pre><code>cmd.CommandText = "insert_test_result"; cmd.CommandType = CommandType.StoredProcedure; </code></pre> <p>This also allows simpler passing by name, rather than position.</p> <p>In general, ADO.NET wants DBNull.Value, not null. I just use a handy method that loops over my args and replaces any nulls with DBNull.Value - as simple as (wrapped):</p> <pre><code> foreach (IDataParameter param in command.Parameters) { if (param.Value == null) param.Value = DBNull.Value; } </code></pre> <p>However! Specifying a value with null is different to letting it assume the default value. If you want it to use the default, don't include the parameter in the command.</p>
<p>If you aren't using named parameters, MSSQL takes the parameters in the order received (by index). I think there's an option for this on the cmd object.</p> <p>so your SQL should be more like </p> <pre><code>EXEC [dbo].insert_test_result @executed = @executed, @failure = @failure, @success = @success, @testID = @testID, @time = @time, @name = @name, @description = @description, @executionDateTime = @executionDateTime, @message = @message; </code></pre>
18,748
<p>The in-house application framework we use at my company makes it necessary to put every SQL query into transactions, even though if I know that none of the commands will make changes in the database. At the end of the session, before closing the connection, I commit the transaction to close it properly. I wonder if there were any particular difference if I rolled it back, especially in terms of speed.</p> <p>Please note that I am using Oracle, but I guess other databases have similar behaviour. Also, I can't do anything about the requirement to begin the transaction, that part of the codebase is out of my hands.</p>
<p>Databases often preserve either a before-image journal (what it was before the transaction) or an after-image journal (what it will be when the transaction completes.) If it keeps a before-image, that has to be restored on a rollback. If it keeps an after-image, that has to replace data in the event of a commit.</p> <p>Oracle has both a journal and rollback space. The transaction journal accumulates blocks which are later written by DB writers. Since these are asychronous, almost nothing DB writer related has any impact on your transaction (if the queue fills up, then you might have to wait.)</p> <p>Even for a query-only transaction, I'd be willing to bet that there's some little bit of transactional record-keeping in Oracle's rollback areas. I suspect that a rollback requires some work on Oracle's part before it determines there's nothing to actually roll back. And I think this is synchronous with your transaction. You can't really release any locks until the rollback is completed. [Yes, I know you aren't using any in your transaction, but the locking issue is why I think a rollback has to be fully released then all the locks can be released, then your rollback is finished.]</p> <p>On the other hand, the commit is more-or-less the expected outcome, and I suspect that discarding the rollback area might be slightly faster. You created no transaction entries, so the db writer will never even wake up to check and discover that there was nothing to do.</p> <p>I also expect that while commit may be faster, the differences will be minor. So minor, that you might not be able to even measure them in a side-by-side comparison. </p>
<p>Since you've not done any DML, I suspect there'd be no difference between a COMMIT and ROLLBACK in Oracle. Either way there's nothing to do.</p>
24,123
<p>We are in the process of designing a simple service-oriented architecture using WCF as the implementation framework. There are a handful of services that a few applications use. These services are mostly used internally, so a basic authentication and authorization scheme (such as Windows-based) is enough.</p> <p>We want, however, expose some of the services to some business partners. The set of services they have access to depend on the contract. Kind of a standard architecture.</p> <p>I think we can implement a <em>service gateway</em> which authenticates the requests and relays them to the correct internal service endpoint (this resembles simple ESB), so we can centralize the authentication/authorization code and expose one single endpoint to the world. I looked at some available ESB toolkits, but they seem way too complex for this purpose. We do not need to integrate a lot of different services, but just to expose some of them to the Internet.</p> <p>How can I design and implement such a relay/router in WCF, keeping it very simple? I have read <a href="http://www.microsoft.com/mspress/books/9610.aspx" rel="nofollow noreferrer">Inside Windows Communication Foundation</a>, which is a good book, but I'm still not confident enough on how to begin.</p>
<p>I have done something very similar to this. What you can do is expose an endpoint with a single operation.</p> <p>That operation would look something like</p> <pre><code>[OperationContract(Namespace="www.fu.com", Action="*")] void CallThis(Message msg); </code></pre> <p>Have your clients use a proxy that is intended for the service they intended to calling the operation they want. Then have them change the configuration to point to your endpoint/service. The "CallThis" method will accept any operation, regardless of its signature. The Message parameter is the WCF Message. </p> <p>Do what you need to do to determine where things are supposed to go, but you will need to change the "To" to go to your internal endpoint.</p> <p>I actually have a full implementation of this, so if you have questions, let me know.</p> <p>Joe.</p>
<p>Check out <a href="https://stackoverflow.com/questions/1213781/is-is-possible-to-relay-a-wcf-service-from-another-server">this SO question</a> where one of the responses suggests .NET 4's RoutingService. Very nice addition to WCF.</p>
48,106
<p>We're starting a new facebook app (incidentally in Rails), and are faced with the decision to use FBML or to use IFrames. It seems like in the past the consensus generally was that FBML was the better way to go, as it made things more inherently Facebook looking, however it seems now like things on the iFrame side are starting to improve, with one of their main engineers saying we <a href="http://www.ccheever.com/blog/?p=10" rel="nofollow noreferrer">should use iframes</a></p> <p>So I'm wondering what have people found to work best. What benefits and drawbacks have you seen with either the iFrame approach, or the FBML approach.</p> <p>Or, are people using a mix of both. I see there's a way you can override the setting in specific places.</p> <hr> <blockquote> <p><strong>UPDATE:</strong><br> For new readers, Facebook has <a href="http://developers.facebook.com/roadmap/" rel="nofollow noreferrer">stopped allowing new FBML applications</a>. <strong>All</strong> new Apps should use <strong>IFrames</strong>.</p> </blockquote>
<p>I have been developing a facebook app for the past several months, and recently switched our canvas page from FBML to an IFrame. The main reason for doing so has to do with these posts and features:</p> <p><a href="http://www.insidefacebook.com/2008/09/30/lead-facebook-engineer-recommends-developers-use-iframes-for-speed-convenience/" rel="nofollow noreferrer">Lead Facebook Engineer Recommends Developers Use IFrames for Speed, Convenience</a></p> <p><a href="https://developers.facebook.com/docs/guides/web/" rel="nofollow noreferrer">XFBML - Facebook Developer Wiki</a></p> <p>Basically, you can now embed FBML into an IFrame canvas using the XFBML features that were implemented to support Facebook Connect. IFrames may have performance improvements (although those are probably trashed by the client-side requests required by XFBML, which are a little tedious to set up at first), but the main advantages for me are:</p> <p>1) The ability to use jQuery or any other stuff I want.</p> <p>2) Useful, relevant ads from adsense, since I no longer have to embed the adsense javascript in its own IFrame.</p> <p>Once I made this switch, I realized that I was able to get all the facebook data I needed through the API, and take advantage of memcached to improve performance. So, now my canvas is just plain old HTML, without any XFBML.</p> <p>Hope this helps.</p>
<p>Using FBML gives you much deeper integration with Facebook as a whole.</p>
27,056
<p>I'm processing some data files that are supposed to be valid UTF-8 but aren't, which causes the parser (not under my control) to fail. I'd like to add a stage of pre-validating the data for UTF-8 well-formedness, but I've not yet found a utility to help do this.</p> <p>There's a <a href="http://www.w3.org/2005/01/yacker/uploads/utf8-validator" rel="noreferrer">web service</a> at W3C which appears to be dead, and I've found a Windows-only validation <a href="http://web.archive.org/web/20081101142036/http://bolek.techno.cz:80/UTF8-Validator/" rel="noreferrer">tool</a> that reports invalid UTF-8 files but doesn't report which lines/characters to fix.</p> <p>I'd be happy with either a tool I can drop in and use (ideally cross-platform), or a ruby/perl script I can make part of my data loading process. </p>
<p>You can use GNU iconv:</p> <pre><code>$ iconv -f UTF-8 your_file -o /dev/null; echo $? </code></pre> <p>Or with older versions of iconv, such as on macOS:</p> <pre><code>$ iconv -f UTF-8 your_file &gt; /dev/null; echo $? </code></pre> <p>The command will return 0 if the file could be converted successfully, and 1 if not. Additionally, it will print out the byte offset where the invalid byte sequence occurred.</p> <p><strong>Edit</strong>: The output encoding doesn't have to be specified, it will be assumed to be UTF-8.</p>
<p>You can also use <a href="https://linux.die.net/man/1/recode" rel="nofollow noreferrer"><code>recode</code></a>, which will exit with an error if it tries to decode UTF-8 and encounters invalid characters.</p> <pre class="lang-bash prettyprint-override"><code>if recode utf8/..UCS &lt; "$FILE" &gt;/dev/null 2&gt;&amp;1; then echo "Valid utf8 : $FILE" else echo "NOT valid utf8: $FILE" fi </code></pre> <p>This tries to recode to the <a href="https://en.wikipedia.org/wiki/Universal_Coded_Character_Set" rel="nofollow noreferrer">Universal Character Set (UCS)</a> which is always possible from valid UTF-8.</p>
14,051
<p>For part of my application I have a need to create an image of a certain view and all of its subviews.</p> <p>To do this I'm creating a context that wraps a bitmap with the same-size as the view, but I'm unsure how to draw the view hierarchy into it. I can draw a single view just be setting the context and explicitly calling drawRect, but this does not deal with all of the subviews.</p> <p>I can't see anything in the NSView interface that could help with this so I suspect the solution may lie at a higher level.</p>
<p>I found that writing the drawing code myself was the best way to:</p> <ul> <li>deal with potential transparency issues (some of the other options do add a white background to the whole image)</li> <li>performance was much better</li> </ul> <p>The code below is not perfect, because it does not deal with scaling issues when going from bounds to frames, but it does take into account the isFlipped state, and works very well for what I used it for. Note that it only draws the subviews (and the subsubviews,... recursively), but getting it to also draw itself is very easy, just add a <code>[self drawRect:[self bounds]]</code> in the implementation of <code>imageWithSubviews</code>.</p> <pre><code>- (void)drawSubviews { BOOL flipped = [self isFlipped]; for ( NSView *subview in [self subviews] ) { // changes the coordinate system so that the local coordinates of the subview (bounds) become the coordinates of the superview (frame) // the transform assumes bounds and frame have the same size, and bounds origin is (0,0) // handling of 'isFlipped' also probably unreliable NSAffineTransform *transform = [NSAffineTransform transform]; if ( flipped ) { [transform translateXBy:subview.frame.origin.x yBy:NSMaxY(subview.frame)]; [transform scaleXBy:+1.0 yBy:-1.0]; } else [transform translateXBy:subview.frame.origin.x yBy:subview.frame.origin.y]; [transform concat]; // recursively draw the subview and sub-subviews [subview drawRect:[subview bounds]]; [subview drawSubviews]; // reset the transform to get back a clean graphic contexts for the rest of the drawing [transform invert]; [transform concat]; } } - (NSImage *)imageWithSubviews { NSImage *image = [[[NSImage alloc] initWithSize:[self bounds].size] autorelease]; [image lockFocus]; // it seems NSImage cannot use flipped coordinates the way NSView does (the method 'setFlipped:' does not seem to help) // Use instead an NSAffineTransform if ( [self isFlipped] ) { NSAffineTransform *transform = [NSAffineTransform transform]; [transform translateXBy:0 yBy:NSMaxY(self.bounds)]; [transform scaleXBy:+1.0 yBy:-1.0]; [transform concat]; } [self drawSubviews]; [image unlockFocus]; return image; } </code></pre>
<p>You can use <a href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/Classes/NSBitmapImageRep_Class/Reference/Reference.html#//apple_ref/occ/instm/NSBitmapImageRep/initWithFocusedViewRect:" rel="nofollow noreferrer" title="-[NSBitmapImageRep initWithFocusedViewRect:]"><code>-[NSBitmapImageRep initWithFocusedViewRect:]</code></a> after locking focus on a view to have the view render itself (and its subviews) into the given rectangle.</p>
3,566
<p>When I call a static method like:</p> <pre><code>Something.action(); </code></pre> <p>Since a instance isn't created how long will the Class of the static method be held in memory?</p> <p>If I call the same method will the Class be reloaded for each call since no instance exists?</p> <p>And are only individual static methods loaded when called or are all the methods and static methods of a Class loaded into memory even though only one static method maybe used?</p>
<p>Unless you have configured garbage collection of permgenspace, the class stays in memory until the vm exits. The full class is loaded with all static methods.</p>
<p>The <em>Something</em> class should get loaded when the caller class will be loaded. And it stays there until the exit of the VM as krosenvold said.</p>
38,234
<p>Given the key for some registry value (e.g. HKEY_LOCAL_MACHINE\blah\blah\blah\foo) how can I:</p> <ol> <li>Safely determine that such a key exists.</li> <li>Programmatically (i.e. with code) get its value.</li> </ol> <p>I have absolutely no intention of writing anything back to the registry (for the duration of my career if I can help it). So we can skip the lecture about every molecule in my body exploding at the speed of light if I write to the registry incorrectly. </p> <p>Prefer answers in C++, but mostly just need to know what the special Windows API incantation to get at the value is.</p>
<p><strong>Here is some pseudo-code to retrieve the following:</strong></p> <ol> <li>If a registry key exists</li> <li>What the default value is for that registry key</li> <li>What a string value is</li> <li>What a DWORD value is</li> </ol> <p><strong>Example code:</strong></p> <p>Include the library dependency: Advapi32.lib</p> <pre><code>HKEY hKey; LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", 0, KEY_READ, &amp;hKey); bool bExistsAndSuccess (lRes == ERROR_SUCCESS); bool bDoesNotExistsSpecifically (lRes == ERROR_FILE_NOT_FOUND); std::wstring strValueOfBinDir; std::wstring strKeyDefaultValue; GetStringRegKey(hKey, L"BinDir", strValueOfBinDir, L"bad"); GetStringRegKey(hKey, L"", strKeyDefaultValue, L"bad"); LONG GetDWORDRegKey(HKEY hKey, const std::wstring &amp;strValueName, DWORD &amp;nValue, DWORD nDefaultValue) { nValue = nDefaultValue; DWORD dwBufferSize(sizeof(DWORD)); DWORD nResult(0); LONG nError = ::RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, reinterpret_cast&lt;LPBYTE&gt;(&amp;nResult), &amp;dwBufferSize); if (ERROR_SUCCESS == nError) { nValue = nResult; } return nError; } LONG GetBoolRegKey(HKEY hKey, const std::wstring &amp;strValueName, bool &amp;bValue, bool bDefaultValue) { DWORD nDefValue((bDefaultValue) ? 1 : 0); DWORD nResult(nDefValue); LONG nError = GetDWORDRegKey(hKey, strValueName.c_str(), nResult, nDefValue); if (ERROR_SUCCESS == nError) { bValue = (nResult != 0) ? true : false; } return nError; } LONG GetStringRegKey(HKEY hKey, const std::wstring &amp;strValueName, std::wstring &amp;strValue, const std::wstring &amp;strDefaultValue) { strValue = strDefaultValue; WCHAR szBuffer[512]; DWORD dwBufferSize = sizeof(szBuffer); ULONG nError; nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &amp;dwBufferSize); if (ERROR_SUCCESS == nError) { strValue = szBuffer; } return nError; } </code></pre>
<pre><code>#include &lt;windows.h&gt; #include &lt;map&gt; #include &lt;string&gt; #include &lt;stdio.h&gt; #include &lt;string.h&gt; #include &lt;tr1/stdint.h&gt; using namespace std; void printerr(DWORD dwerror) { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dwerror, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), // Default language (LPTSTR) &amp;lpMsgBuf, 0, NULL ); // Process any inserts in lpMsgBuf. // ... // Display the string. if (isOut) { fprintf(fout, "%s\n", lpMsgBuf); } else { printf("%s\n", lpMsgBuf); } // Free the buffer. LocalFree(lpMsgBuf); } bool regreadSZ(string&amp; hkey, string&amp; subkey, string&amp; value, string&amp; returnvalue, string&amp; regValueType) { char s[128000]; map&lt;string,HKEY&gt; keys; keys["HKEY_CLASSES_ROOT"]=HKEY_CLASSES_ROOT; keys["HKEY_CURRENT_CONFIG"]=HKEY_CURRENT_CONFIG; //DID NOT SURVIVE? keys["HKEY_CURRENT_USER"]=HKEY_CURRENT_USER; keys["HKEY_LOCAL_MACHINE"]=HKEY_LOCAL_MACHINE; keys["HKEY_USERS"]=HKEY_USERS; HKEY mykey; map&lt;string,DWORD&gt; valuetypes; valuetypes["REG_SZ"]=REG_SZ; valuetypes["REG_EXPAND_SZ"]=REG_EXPAND_SZ; valuetypes["REG_MULTI_SZ"]=REG_MULTI_SZ; //probably can't use this. LONG retval=RegOpenKeyEx( keys[hkey], // handle to open key subkey.c_str(), // subkey name 0, // reserved KEY_READ, // security access mask &amp;mykey // handle to open key ); if (ERROR_SUCCESS != retval) {printerr(retval); return false;} DWORD slen=128000; DWORD valuetype = valuetypes[regValueType]; retval=RegQueryValueEx( mykey, // handle to key value.c_str(), // value name NULL, // reserved (LPDWORD) &amp;valuetype, // type buffer (LPBYTE)s, // data buffer (LPDWORD) &amp;slen // size of data buffer ); switch(retval) { case ERROR_SUCCESS: //if (isOut) { // fprintf(fout,"RegQueryValueEx():ERROR_SUCCESS:succeeded.\n"); //} else { // printf("RegQueryValueEx():ERROR_SUCCESS:succeeded.\n"); //} break; case ERROR_MORE_DATA: //what do I do now? data buffer is too small. if (isOut) { fprintf(fout,"RegQueryValueEx():ERROR_MORE_DATA: need bigger buffer.\n"); } else { printf("RegQueryValueEx():ERROR_MORE_DATA: need bigger buffer.\n"); } return false; case ERROR_FILE_NOT_FOUND: if (isOut) { fprintf(fout,"RegQueryValueEx():ERROR_FILE_NOT_FOUND: registry value does not exist.\n"); } else { printf("RegQueryValueEx():ERROR_FILE_NOT_FOUND: registry value does not exist.\n"); } return false; default: if (isOut) { fprintf(fout,"RegQueryValueEx():unknown error type 0x%lx.\n", retval); } else { printf("RegQueryValueEx():unknown error type 0x%lx.\n", retval); } return false; } retval=RegCloseKey(mykey); if (ERROR_SUCCESS != retval) {printerr(retval); return false;} returnvalue = s; return true; } </code></pre>
5,422
<p>During coding I frequently encounter this situation:</p> <ol> <li>I have several objects (<code>ConcreteType1</code>, <code>ConcreteType2</code>, ...) with the same base type <code>AbstractType</code>, which has abstract methods <code>save</code> and <code>load</code> . Each object can (and has to) save some specific kind of data, by overriding the <code>save</code> method. </li> <li>I have a list of <code>AbstractType</code> objects which contains various <code>ConcreteTypeX</code> objects.</li> <li>I walk the list and the <code>save</code> method for each object.</li> </ol> <p>At this point I think it's a good OO design. (Or am I wrong?) The problems start when I want to reload the data:</p> <p>Each object can load its own data, but I have to know the concrete type in advance, so I can instantiate the right <code>ConcreteTypeX</code> and call the <code>load</code> method. So the loading method has to know a great deal about the concrete types. I usually "solved" this problem by writing some kind of marker before calling <code>save</code>, which is used by the loader to determine the right <code>ConcreteTypeX</code>.</p> <p>I always had/have a bad feeling about this. It feels like some kind of anti-pattern...</p> <p>Are there better ways?</p> <p>EDIT: I'm sorry for the confusion, I re-wrote some of the text. I'm aware of serialization and perhaps there is some next-to-perfect solution in Java/.NET/yourFavoriteLanguage, but I'm searching for a general solution, which might be better and more "OOP-ish" compared to my concept.</p>
<p>If you can't simply use serialization, then I would still definitely pull the object loading logic out of the base class. Your instinct is correct, leading you to correctly identify a <a href="http://en.wikipedia.org/wiki/Code_smell" rel="nofollow noreferrer">code smell</a>. The base class shouldn't need to change when you change or add derived classes.</p> <p>The problem is, <em>something</em> has to load the data and instantiate those objects. This sounds like a job for the <a href="http://en.wikipedia.org/wiki/Abstract_factory_pattern" rel="nofollow noreferrer">Abstract Factory pattern</a>.</p>
<p>There are better ways, but let's take a step back and look at it conceptually. What are all objects doing? Loading and Saving. When you get the object from memory, you really don't to have to care whether it gets its information from a file, a database, or the windows registry. You just want the object loaded. That's important to remember because later on, your maintanence programmer will look at the LoadFromFile() method and wonder, &quot;Why is it called that since it really doesn't load anything from a file?&quot;</p> <p>Secondly, you're running into the issue that we all run into, and it's based in dividing work. You want a level that handles getting data from a physical source; you want a level that manipulates this data, and you want a level that displays this data. This is the crux of <a href="https://web.archive.org/web/20070625214219/http://csharpstruggles.blogspot.com:80/2004/08/n-tier-development.html" rel="nofollow noreferrer">N-Tier Development</a>. I've linked to an article that <a href="https://www.red-gate.com/simple-talk/development/dotnet-development/net-application-architecture-the-data-access-layer/" rel="nofollow noreferrer">discusses your problem</a> in great detail, and details how to create a Data Access Layer to resolve your issue. There are also numerous code projects <a href="https://web.archive.org/web/20170224113830/http://www.dotnetheaven.com:80/uploadfile/tavanover/ntierdevelopmentwithms102052006231650pm/ntierdevelopmentwithms1.aspx" rel="nofollow noreferrer">here</a> and <a href="https://web.archive.org/web/20161028195850/http://geekswithblogs.net:80/steveclements/archive/2006/08/31/89892.aspx" rel="nofollow noreferrer">here</a>.</p> <p>If it's Java you seek, simply substitute 'java' for .NET and search for 'Java N-Tier development'. However, besides syntactical differences, the design structure is the same.</p>
37,333
<p>I am using ngen.exe (the .Net Native Image Generator) version 2.0.50727.312. Is this the latest version? If not, where can I download the latest version? This <a href="http://msdn.microsoft.com/en-us/library/6t9t5wcf.aspx" rel="noreferrer"><strong>page</strong></a> on msdn does not appear to have a link to a download. If it matters, I need ngen.exe for .Net Framework 3.5.</p>
<p>The .NET Runtime itself has been upgraded with what amounts to a "service pack" in the 3.5 version. If you have .NET 3.5 installed on that box, you are running the latest version of NGEN, even if the version number is 2.0.50727. Check out this article for more details:</p> <p><a href="http://www.danielmoth.com/Blog/2007/06/net-framework-35.html" rel="noreferrer">http://www.danielmoth.com/Blog/2007/06/net-framework-35.html</a></p>
<p>ngen.exe is stored in framework installation path</p> <p>C:\Windows\Microsoft.NET\Framework\v2.0.50727 or C:\Windows\Microsoft.NET\Framework\v1.1.4322</p> <p><a href="http://msdn.microsoft.com/en-us/library/6t9t5wcf(VS.80).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/6t9t5wcf(VS.80).aspx</a></p>
45,266
<p>My team is developing a new service oriented product with a web front-end. In discussions about what technologies we will use we have settled on running a JBoss application server, and Flex frontend (with possible desktop deployment using Adobe AIR), and web services to interface the client and server.</p> <p>We've reached an impasse when it comes to which server technology to use for our business logic. The big argument is between EJB3 and Spring, with our biggest concerns being scalability and performance, and also maintainability of the code base.</p> <p>Here are my questions:</p> <ol> <li>What are the arguments for or against EJB3 vs Spring? <ul> <li>What pitfalls can I expect with each?</li> <li>Where can I find good benchmark information?</li> </ul></li> </ol>
<p>There won't be much difference between EJB3 and Spring based on Performance. We chose Spring for the following reasons (not mentioned in the question):</p> <ul> <li>Spring drives the architecture in a direction that more readily supports unit testing. For example, inject a mock DAO object to unit test your business layer, or utilize Spring's MockHttpRequest object to unit test a servlet. We maintain a separate Spring config for unit tests that allows us to isolate tests to the specific layers.</li> <li>An overriding driver was compatibility. If you need to support more than one App Server (or eventually want the option to move from JBoss to Glassfish, etc.), you will essentially be carrying your container (Spring) with you, rather than relying on compatibility between different implementations of the EJB3 specification.</li> <li>Spring allows for technology choices for Persistence, object remoting, etc. For example, we are also using a Flex front end, and are using the Hessian protocol for communications between Flex and Spring.</li> </ul>
<p>I think EJB is a good component technology but not a good framework.Spring is the best framework available as of today.So i should consider Spring as the best implementation of JEE in the sense of a framework and my recommendation is to use spring in every project which gives us the flexibility to integrate with any component technology easily .</p>
9,400
<p>I try to add an addons system to my Windows.Net application using Reflection; but it fails when there is addon with dependencie.<br><br> Addon class have to implement an interface 'IAddon' and to have an empty constructor.<br> Main program load the addon using Reflection:</p> <pre><code>Assembly assembly = Assembly.LoadFile(@"C:\Temp\TestAddon\Addon.dll"); Type t = assembly.GetType("Test.MyAddon"); ConstructorInfo ctor = t.GetConstructor(new Type[] { }); IAddon addon= (IAddon) ctor.Invoke(new object[] { }); addon.StartAddon(); </code></pre> <p>It works great when addon do not use dependencie. But if my addon reference and use an another DLL (C:\Temp\TestAddon\MyTools.dll) that is saved near the addon in disk, it fails: <br> <em>System.IO.FileNotFoundException: Could not load file or assembly 'MyTools.dll' or one of its dependencies.</em> </p> <p>I do not wants to copy the addons DLL near my executable, how can i do to tell .Net runtime to search in "C:\Temp\TestAddon\" for any dependency?</p> <p>Note that adding </p> <pre><code>Assembly assembly = Assembly.LoadFile(@"C:\Temp\TestAddon\MyTools.dll"); </code></pre> <p>do not change anything.</p>
<p>If <em>MyTools.dll</em> is located in the same directory as <em>Addon.dll</em>, all you need to do is call <code>Assembly.LoadFrom</code> instead of <code>Assembly.LoadFile</code> to make your code work. Otherwise, handling the <code>AppDomain.AssemblyResolve</code> event is the way to go.</p>
<p>Couple of options:</p> <ol> <li>You can attach to <code>AppDomain.AssemblyResolve</code> to help the CLR resolve the assembly.</li> <li>You could look into isolating add-ins into their own <code>AppDomain</code> (see <code>System.AddIn</code> namespace and <a href="http://www.codeplex.com/clraddins" rel="nofollow noreferrer">this website</a>).</li> </ol>
21,969
<p>Can anybody suggest a good book/paper/website/background reading about universal codes for integers and especially Fibonacci code (in the sense of <a href="http://en.wikipedia.org/wiki/Fibonacci_code" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Fibonacci_code</a>)? Thanks!</p> <p><strong>Edit:</strong> Thanks for the answers and the useful links so far! I am sorry if I have not made myself completely clear: I am not asking about code (as in writing a program) to generate or compute Fibonacci numbers, but about a particular code (as in encoding, or compressing, data) that makes use of Fibonacci numbers.</p>
<p>One paper found with <a href="http://scholar.google.com" rel="nofollow noreferrer">Google Scholar</a> : </p> <ul> <li><a href="http://radio-1.ee.dal.ca/~ilow/4540/readings/DataCompression.pdf" rel="nofollow noreferrer">Data compression</a> (DA Lelewer, DS Hirschberg - ACM Computing Surveys (CSUR), 1987)</li> </ul> <p>I'm not so familiar with the subject but the article seems to be pretty decent by a brief looking.</p>
<p>One paper found with <a href="http://scholar.google.com" rel="nofollow noreferrer">Google Scholar</a> : </p> <ul> <li><a href="http://radio-1.ee.dal.ca/~ilow/4540/readings/DataCompression.pdf" rel="nofollow noreferrer">Data compression</a> (DA Lelewer, DS Hirschberg - ACM Computing Surveys (CSUR), 1987)</li> </ul> <p>I'm not so familiar with the subject but the article seems to be pretty decent by a brief looking.</p>
38,202
<p>I have to deal with very large text files (2 GBs), it is mandatory to read/write them line by line. To write 23 millions of lines using ofstream is really slow so, at the beginning, I tried to speed up the process writing large chunks of lines in a memory buffer (for example 256 MB or 512 MB) and then write the buffer into the file. This did not work, the performance is more or less the same. I have the same problem reading the files. I know the I/O operations are buffered by the STL I/O system and this also depends on the disk scheduler policy (managed by the OS, in my case Linux). </p> <p>Any idea about how to improve the performance?</p> <p>PS: I have been thinking about using a background child process (or a thread) to read/write the data chunks while the program is processing data but I do not know (mainly in the case of the subprocess) if this will be worthy. </p>
<p>A 2GB file is pretty big, and you need to be aware of all the possible areas that can act as bottlenecks:</p> <ul> <li>The HDD itself</li> <li>The HDD interface (IDE/SATA/RAID/USB?) </li> <li>Operating system/filesystem </li> <li>C/C++ Library </li> <li>Your code</li> </ul> <p>I'd start by doing some measurements: </p> <ul> <li>How long does your code take to read/write a 2GB file,</li> <li><p>How fast can the '<a href="http://en.wikipedia.org/wiki/Dd_%28Unix%29#Benchmarking_drive_performance" rel="nofollow noreferrer">dd</a>' command read and write to disk? Example...</p> <p><code>dd if=/dev/zero bs=1024 count=2000000 of=file_2GB</code></p></li> <li>How long does it take to write/read using just big fwrite()/fread() calls</li> </ul> <p>Assuming your disk is capable of reading/writing at about 40Mb/s (which is probably a realistic figure to start from), your 2GB file can't run faster than about 50 seconds.</p> <p>How long is it actually taking?</p> <blockquote> <p>Hi Roddy, using fstream read method with 1.1 GB files and large buffers(128,255 or 512 MB) it takes about 43-48 seconds and it is the same using fstream getline (line by line). cp takes almost 2 minutes to copy the file.</p> </blockquote> <p>In which case, your're hardware-bound. <em>cp</em> has to read and write, and will be seeking back and forth across the disk surface like mad when it does it. So it will (as you see) be more than twice as bad as the simple 'read' case.</p> <p>To improve the speed, the first thing I'd try is a faster hard drive, or an SSD.</p> <p>You haven't said what the disk interface is? SATA is pretty much the easiest/fastest option. Also (obvious point, this...) make sure the disk is physically on the same machine your code is running, otherwise you're network-bound...</p>
<p>If you are going to buffer the file yourself, then I'd advise some testing using unbuffered I/O (setvbuf on a file that you've fopened can turn off the library buffering).</p> <p>Basically, if you are going to buffer yourself, you want to disable the library's buffering, as it's only going to cause you pain. I don't know if there is any way to do that for STL I/O, so I recommend going down to the C-level I/O.</p>
33,646
<p>Best practices recommend not installing Sql Server to run as SYSTEM. What is the bare minumum you need to give the user account you create for it?</p>
<p>By default, SQL Server 2005 installation will create a security group called SQLServer2005MSSQLUser$ComputerName$MSSQLSERVER with the correct rights. You just need to create a domain user or local user and make it a member of that group. </p> <p>More details are available in the SQL Server Books Online: <a href="http://msdn.microsoft.com/en-us/library/ms143504(SQL.90).aspx#Review_NT_rights" rel="nofollow noreferrer" title="Setting Up Windows Service Accounts">Reviewing Windows NT Rights and Privileges Granted for SQL Server Service Accounts</a></p>
<p>Typically I create a Domain User with only the specific rights on the network which I will require the server to have (i.e. to write to the network backup drive), I then add the account to local power users or local administrators depending on what needs to be done on the machine, however this isn't required. I've installed SQL a number of times using a standard user as a Service Account but you need to ensure that the user has access to write to the resources as listed at <a href="https://web.archive.org/web/20081223155956/http://support.microsoft.com/kb/283811" rel="nofollow noreferrer">https://web.archive.org/web/20081223155956/http://support.microsoft.com/kb/283811</a> . Its probably not as defined an answer as you wanted but I'm only a developer (not a professional DBA / System Engineer).</p> <p>Mauro PS dont downmark me for saying "only a developer" :P</p>
8,220
<p>For my customer I occasionally do work in their live database in order to fix a problem they have created for themselves, or in order to fix bad data that my product's bugs created. Much like Unix root access, it's just dangerous. What lessons should I learn ahead of time?</p> <p>What is the #1 thing you do to be careful about operating on live data?</p>
<p>Three things I've learned the hard way over the years...</p> <p>First, if you're doing updates or deletes on live data, first write a SELECT query with the WHERE clause you'll be using. Make sure it works. Make sure it's correct. Then prepend the UPDATE/DELETE statement to the known working WHERE clause.</p> <p>You never want to have </p> <pre><code>DELETE FROM Customers </code></pre> <p>sitting in your query analyzer waiting for you to write the WHERE clause... accidentally hit "execute" and you've just killed your Customer table. Oops.</p> <p>Also, depending on your platform, find out how to take a quick'n'dirty backup of a table. In SQL Server 2005,</p> <pre><code>SELECT * INTO CustomerBackup200810032034 FROM Customer </code></pre> <p>will copy every row from the entire Customer table into a new table called CustomerBackup200810032034, which you can then delete once you've done your updates and made sure everything's OK. If the worst happens, it's a lot easier to restore missing data from this table than to try and restore last night's backup from disk or tape.</p> <p>Finally, be wary of cascade deletes getting rid of stuff you didn't intend to delete - check your tables' relationships and key constraints before modifying anything.</p>
<p><strong>Make sure your query has a <code>WHERE</code> parameter specified</strong></p> <p>I was once mid-way through a complex update, got distracted, and finished the query early, forgetting the "where" clause. Then I got that sinking feeling, watching a half-second query rumble on for 3.. The several hours afterwards spent cleaning up customer data was quite the lesson!</p> <p>A result of which is now when I work on the live db, I structure my queries like:</p> <pre><code>UPDATE my_table WHERE condition = true; </code></pre> <p>then go back and put in the columns etc to update. Takes a bit longer to write, but <em>massively</em> reduces my chance of making the same mistake again!</p>
20,342
<p>Which component to use to play mp3 files from streams/files and also to know the lenght in seconds of that mp3 stream?</p>
<p>You can also use the components at <a href="http://www.mitov.com" rel="nofollow noreferrer">www.mitov.com</a> which has an Audio suite that can handle this type of file.</p>
<p>I use <a href="http://symmetrica.net/newac/" rel="nofollow noreferrer">NewAc</a> components for audio conversion and filtering, it can play MP3 and several others formats.</p>
43,341
<p>One of my DBs have grown closer to permitted size.</p> <p>Inorder to find out the table containing the max data, i used the following query:</p> <pre><code>exec sp_MSforeachtable @command1="print '?' exec sp_spaceused '?'" </code></pre> <p>It returned the culprit table comprising the max data.</p> <p>As a next step, i want to cleanup the rows based on the size. For this, i would like to order the rows based on size.</p> <p>How to achieve this using a query? Are there any tools to do this?</p>
<p>This will give you a list of rows by size, just set @table and @idcol accordingly (as written it'll run against the Northwind sample)</p> <pre><code>declare @table varchar(20) declare @idcol varchar(10) declare @sql varchar(1000) set @table = 'Employees' set @idcol = 'EmployeeId' set @sql = 'select ' + @idcol +' , (0' select @sql = @sql + ' + isnull(datalength(' + name + '), 1)' from syscolumns where id = object_id(@table) set @sql = @sql + ') as rowsize from ' + @table + ' order by rowsize desc' exec (@sql) </code></pre>
<p>Maybe something like this will work </p> <pre><code>delete table where id in ( select top 100 id from table order by datalength(event_text) + length(varchar_column) desc ) </code></pre> <p>(since you are dealing with an event table its probably a text column you are looking at ordering on so the datalength sql command is key here)</p>
14,002
<p>If a "WITH NOLOCK" query hint is used on a View in SQL Server, does it propagate that hint to the view definition itself, even if NOLOCK is NOT used for the raw tables in the View definition? The reason to need this is that sometimes the support staff wants to do huge time-consuming queries but would rather not force this lock on all queries using the view within the application itself.</p>
<p>Yes, NOLOCK will propagate to the tables used by the view definition (at least in SQL Server 2005).</p> <p>See <a href="http://msdn.microsoft.com/en-us/library/ms187373(SQL.90).aspx" rel="noreferrer">Table Hints</a> in MSDN:</p> <blockquote> <p>In SQL Server 2005, all lock hints are propagated to all the tables and views that are referenced in a view. Also, SQL Server performs the corresponding lock consistency checks.</p> </blockquote> <p>However,</p> <blockquote> <p>If a table contains computed columns and the computed columns are computed by expressions or functions accessing columns in other tables, the table hints are not used on those tables. This means the table hints are not propagated. For example, a NOLOCK table hint is specified on a table in the query. This table has computed columns that are computed by a combination of expressions and functions that access columns in another table. The tables referenced by the expressions and functions do not use the NOLOCK table hint when accessed.</p> </blockquote> <p>If you're using indexed views you might want to read a bit more as there are some special cases there too.</p> <p>Also see <a href="http://msdn.microsoft.com/en-us/library/ms190237(SQL.90).aspx" rel="noreferrer">View Resolution</a> for more info.</p>
<p>Just to supplement Rory's excellent answer. </p> <p>He writes "Yes, NOLOCK will propagate to the tables used by the view definition <strong><em>(at least in SQL Server 2005)</em></strong>."</p> <p>In fact this will work in SQL 2000 as well. <a href="http://msdn.microsoft.com/en-us/library/aa258253(SQL.80).aspx" rel="noreferrer">From BOL:</a></p> <blockquote> <p>Because select_statement uses the SELECT statement, it is valid to use and hints as specified in the FROM clause. For more information, see <a href="http://msdn.microsoft.com/en-us/library/aa258869(SQL.80).aspx" rel="noreferrer">FROM</a> and <a href="http://msdn.microsoft.com/en-us/library/aa259187(SQL.80).aspx" rel="noreferrer">SELECT</a>.</p> </blockquote>
40,131