instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I have an Adventurer 3 printer from Flashforge and every time I unclog it, it gets clogged up again. I’ve done about 6 or 7 prints with it. So after I unclog it, I load the filament and it comes out of the nozzle like it should but once I start a 3D print, it’s clogged again. The process of what I do to unclog it is by heating the nozzle up and then shove a small metal rod down the nozzle to push out the clogged filament. I do this several times until its all gone. I’ve read up on what I can do to prevent it but it doesn’t seem to work. What should I do? <img src="https://i.stack.imgur.com/WT9Cg.jpg" alt="enter image description here"><img src="https://i.stack.imgur.com/1zjzA.jpg" alt="enter image description here"></p>
<p>I can see from the photo that filament melted and frozen thicker inside extruder. This is the problem and not the clogged extruder. This thick part produce a lot of friction and actually diameter grow until the print finally will stuck. Basically I had the same problem and I could guess that you are also using Bowden setup. The length of this built thicker part is actually corresponded to your retraction length setting in your slicer (the default value in Cura is unreasonably big like 6.5 millimetres). I solved the same problem by decreasing retraction settings to about 2-3&nbsp;mm. Just try it and I am sure you will not have this problem again.</p>
<p>The Flashforge documentation is not much help, so unless there's a way for you to connect with their user community (because, maybe what you're dealing with is a known issue related to firmware or the machine itself) or Flashforge's customer service folks, you've got some fun detective work ahead of you. Seriously--you will enjoy solving this!</p> <p>So: It will help to teach yourself the ABC's of clog symptoms, so you can see what the cause(s) <em>could</em> and <em>couldn't</em> be, in your situation. This is <a href="https://rigid.ink/blogs/news/clogged-extruder-nozzle-what-causes-it-how-to-avoid-it-and-how-to-fix-it" rel="nofollow noreferrer">not a bad starter guide</a>, and there are lots of others. You say you've "read up" on preventive measures--that's great! When your original post says, "but it doesn’t seem to work," please understand, though, that we who read don't yet know what "it" <em>means</em>, in this case. Clarity &amp; details are you friends here. </p>
1,024
<p>Has Mono been ported to the iPhone yet? I'd love to write .NET apps for the iPhone, and learning Objective C isn't an option for me.</p>
<p>Mono today is available in two forms:</p> <ul> <li>Mono with bindings to iOS APIs per <a href="http://monotouch.net" rel="noreferrer">http://monotouch.net</a></li> <li>Mono as a scripting engine powering Unity3D</li> </ul>
<p>Sorry, kid, but Obj-C is the only way. Why is it "not an option"?</p> <p>Your app will be "not an option" to Apple for the App Store unless it's written in Obj-C on Xcode, and signed properly.</p>
49,377
<p>I am trying to access my WCF service on a server from my client console application for testing. I am getting the following error: </p> <blockquote> <p>The caller was not authenticated by the service</p> </blockquote> <p>I am using <code>wsHttpBinding</code>. I'm not sure what kind of authentication the service is expecting?</p> <p> <br> <br> </p> <pre><code>&lt;behaviors&gt; &lt;serviceBehaviors&gt; &lt;behavior name="MyTrakerService.MyTrakerServiceBehavior"&gt; &lt;!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment --&gt; &lt;serviceMetadata httpGetEnabled="true"/&gt; &lt;!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information --&gt; &lt;serviceDebug includeExceptionDetailInFaults="false"/&gt; &lt;/behavior&gt; &lt;/serviceBehaviors&gt; &lt;/behaviors&gt; </code></pre> <p></p> <p><b>Update</b> It works if I change my binding to <code>&lt;endpoint "basicHttpBinding" ... /&gt;</code> (from wsHttpBinding) on the IIS 7.0 hosted, windows 2008 server</p>
<p>If you use basicHttpBinding, configure the endpoint security to "None" and transport clientCredintialType to "None."</p> <pre><code>&lt;bindings&gt; &lt;basicHttpBinding&gt; &lt;binding name="MyBasicHttpBinding"&gt; &lt;security mode="None"&gt; &lt;transport clientCredentialType="None" /&gt; &lt;/security&gt; &lt;/binding&gt; &lt;/basicHttpBinding&gt; &lt;/bindings&gt; &lt;services&gt; &lt;service behaviorConfiguration="MyServiceBehavior" name="MyService"&gt; &lt;endpoint binding="basicHttpBinding" bindingConfiguration="MyBasicHttpBinding" name="basicEndPoint" contract="IMyService" /&gt; &lt;/service&gt; </code></pre> <p>Also, make sure the directory Authentication Methods in IIS to Enable Anonymous access</p>
<p>Why can't you just remove the security setting altogether for wsHttpBinding ("none" instead of "message" or "transport")?</p>
36,104
<p>Why won't my connection string to SQL server work with Windows authentication? A sql user works fine, acme\administrator or administrator@acme.com won't work. This is a Win Form app written in C#.</p> <pre><code> { OdbcConnection cn = null; String connectionString; connectionString = "Driver={SQL Server};Server=" + cbxDataSources.Text +";Database=" + strDatabase + ";"; connectionString += "UID=" + textBoxUserName.Text + ";"; connectionString += "PWD=" + textBoxPassword.Text + ";"; cn = new OdbcConnection(connectionString); return cn; } </code></pre> <p>Thanks guys</p>
<p>You are using SQL Server authentication.</p> <p>Windows authentication authenticates your connection with the Windows identity of the currently executing process or thread. You cannot set a username and password with Windows authentication. Instead, you set Integrated Security = SSPI.</p>
<p>You have to connect using a Trusted Connection.</p> <p>2005:</p> <pre><code>Driver={SQL Native Client};Server=myServerAddress;Database=myDataBase;Trusted_Connection=yes; </code></pre> <p>2000:</p> <pre><code>Driver={SQL Server};Server=myServerAddress;Database=myDataBase;Trusted_Connection=Yes; </code></pre>
25,341
<p>One of the things that get me thoroughly confused is the use of <code>session.Flush</code>,in conjunction with <code>session.Commit</code>, and <code>session.Close</code>.</p> <p>Sometimes <code>session.Close</code> works, e.g., it commits all the changes that I need. I know I need to use commit when I have a transaction, or a unit of work with several creates/updates/deletes, so that I can choose to rollback if an error occurs.</p> <p>But sometimes I really get stymied by the logic behind <code>session.Flush</code>. I have seen examples where you have a <code>session.SaveOrUpdate()</code> followed by a flush, but when I remove Flush it works fine anyway. Sometimes I run into errors on the Flush statement saying that the session timed out, and removing it made sure that I didn't run into that error.</p> <p>Does anyone have a good guideline as to where or when to use a Flush? I've checked out the NHibernate documentation for this, but I still can't find a straightforward answer.</p>
<p>Briefly:</p> <ol> <li>Always use transactions</li> <li>Don't use <code>Close()</code>, instead wrap your calls on an <code>ISession</code> inside a <code>using</code> statement or <strong>manage the lifecycle of your ISession somewhere else</strong>.</li> </ol> <p>From <a href="http://nhibernate.info/doc/nh/en/index.html#manipulatingdata-flushing" rel="noreferrer">the documentation</a>:</p> <blockquote> <p>From time to time the <code>ISession</code> will execute the SQL statements needed to synchronize the ADO.NET connection's state with the state of objects held in memory. This process, flush, occurs by default at the following points</p> <ul> <li>from some invocations of <code>Find()</code> or <code>Enumerable()</code></li> <li>from <code>NHibernate.ITransaction.Commit()</code></li> <li>from <code>ISession.Flush()</code></li> </ul> <p>The SQL statements are issued in the following order</p> <ol> <li>all entity insertions, in the same order the corresponding objects were saved using <code>ISession.Save()</code></li> <li>all entity updates</li> <li>all collection deletions</li> <li>all collection element deletions, updates and insertions</li> <li>all collection insertions</li> <li>all entity deletions, in the same order the corresponding objects were deleted using <code>ISession.Delete()</code></li> </ol> <p>(An exception is that objects using native ID generation are inserted when they are saved.)</p> <p><strong>Except when you explicity <code>Flush()</code>, there are absolutely no guarantees about when the Session executes the ADO.NET calls, only the order in which they are executed</strong>. However, NHibernate does guarantee that the <code>ISession.Find(..)</code> methods will never return stale data; nor will they return the wrong data.</p> <p>It is possible to change the default behavior so that flush occurs less frequently. The <code>FlushMode</code> class defines three different modes: only flush at commit time (and only when the NHibernate <code>ITransaction</code> API is used), flush automatically using the explained routine, or never flush unless <code>Flush()</code> is called explicitly. The last mode is useful for long running units of work, where an <code>ISession</code> is kept open and disconnected for a long time.</p> </blockquote> <p>...</p> <p>Also refer to <a href="http://nhibernate.info/doc/nh/en/index.html#manipulatingdata-endingsession" rel="noreferrer">this section</a>:</p> <blockquote> <p>Ending a session involves four distinct phases:</p> <ul> <li>flush the session</li> <li>commit the transaction</li> <li>close the session</li> <li>handle exceptions</li> </ul> <h2>Flushing the Session</h2> <p>If you happen to be using the <code>ITransaction</code> API, you don't need to worry about this step. It will be performed implicitly when the transaction is committed. Otherwise you should call <code>ISession.Flush()</code> to ensure that all changes are synchronized with the database.</p> <h2>Committing the database transaction</h2> <p>If you are using the NHibernate ITransaction API, this looks like:</p> <pre><code>tx.Commit(); // flush the session and commit the transaction </code></pre> <p>If you are managing ADO.NET transactions yourself you should manually <code>Commit()</code> the ADO.NET transaction.</p> <pre><code>sess.Flush(); currentTransaction.Commit(); </code></pre> <p>If you decide not to commit your changes:</p> <pre><code>tx.Rollback(); // rollback the transaction </code></pre> <p>or:</p> <pre><code>currentTransaction.Rollback(); </code></pre> <p>If you rollback the transaction you should immediately close and discard the current session to ensure that NHibernate's internal state is consistent.</p> <h2>Closing the ISession</h2> <p>A call to <code>ISession.Close()</code> marks the end of a session. The main implication of Close() is that the ADO.NET connection will be relinquished by the session.</p> <pre><code>tx.Commit(); sess.Close(); sess.Flush(); currentTransaction.Commit(); sess.Close(); </code></pre> <p>If you provided your own connection, <code>Close()</code> returns a reference to it, so you can manually close it or return it to the pool. Otherwise <code>Close()</code> returns it to the pool.</p> </blockquote>
<p>Here are two examples of my code where it would fail without session.Flush():</p> <p><a href="http://www.lucidcoding.blogspot.co.uk/2012/05/changing-type-of-entity-persistence.html" rel="nofollow noreferrer">http://www.lucidcoding.blogspot.co.uk/2012/05/changing-type-of-entity-persistence.html</a></p> <p>at the end of this, you can see a section of code where I set identity insert on, save the entity then flush, then set identity insert off. Without this flush it seemed to be setting identity insert on and off then saving the entity. </p> <p>The use of Flush() gave me more control over what was going on.</p> <p>Here is another example:</p> <p><a href="https://stackoverflow.com/questions/12494943/sending-nservicebus-message-inside-transactionscope">Sending NServiceBus message inside TransactionScope</a></p> <p>I don't fully understand why on this one, but Flush() prevented my error from happening.</p>
6,492
<p>Here's another problem with qt: I extend a QAbstractTableModel, but I get a compiling error ( I'm using cmake)</p> <pre><code>// file.h #ifndef TABLEMODEL_H #define TABLEMODEL_H #include &lt;QAbstractTableModel&gt; class TableModel : public QAbstractTableModel { Q_OBJECT public: TableModel(QObject *parent = 0); int rowCount(const QModelIndex &amp;parent = QModelIndex()) const; int columnCount(const QModelIndex &amp;parent = QModelIndex()) const; }; #endif // file.c #include "tableModel.h" TableModel::TableModel(QObject *parent) : QAbstractTableModel(parent){} int TableModel::rowCount(const QModelIndex &amp; ) const { return 1; } int TableModel::columnCount(const QModelIndex &amp; ) const { return 1;} </code></pre> <p>when I compile I get:</p> <p>In function <code>TableModel': /partd/unusedsvn/unusedpkg/iface/tableModel.cpp:4: undefined reference to</code>vtable for TableModel' /partd/unusedsvn/unusedpkg/iface/tableModel.cpp:4: undefined reference to <code>vtable for TableModel' collect2: ld returned 1 exit status</code></p> <p>does anybody got the same trouble??</p>
<p>Make sure you're running your header through MOC, and are linking those MOC object files.</p>
<p>This is a fairly common bug when an <a href="http://doc.qt.io/archives/4.6/debug.html#common-bugs" rel="nofollow noreferrer">object isn't moc'ed</a>. I'd read the whole <a href="http://doc.qt.io/archives/4.6/debug.html" rel="nofollow noreferrer">debugging document</a> to save yourself some time down the road.</p>
41,703
<p>I'm running my first project that I'm compiling with flex builder. Before I used to compile with flash or flash develop.</p> <p>For a while it worked pretty neatly. But as soon as it start throwing typeerrors, I can't seem to compile the updated and saved actionscript files. It seems as if it keeps stuck in time and compiles the actionscript file from when the error was still there.</p> <p>Perhaps any options I missed regarding configuring the debugger ?</p>
<p>Have you tried doing a Clean? In FlexBuilder, the Project menu, select Clean...</p> <p>It's possible Flex is building off of temp files, in which case doing a clean should clear them out.</p>
<p>Minimize Eclipse and see if any other windows are lurking behind the IDE, also try terminating all sessions, and like Herms suggested go to Project->Clean...->YourProject</p> <p>I'm sure Chris already moved on since '08 but for anyone else this solved the problem for me.</p>
27,525
<p>At what level of complexity is it mandatory to switch to an existing framework for web development?</p> <p>What measurement of complexity is practical for web development? Code length? Feature list? Database Size?</p>
<p>If you work on several different sites then by using a common framework across all of them you can spend time working on the code rather than trying to remember what is located where and why.</p> <p>I'd always use a framework of some sort, even if it's your own, as the uniformity will help you structure your project. Unless it's a one page static HTML project.</p> <p>There is no mandatory limit however.</p>
<p>All factors matter. You should measure how much time you can save using 3rd party framework and compare it to the risks of using other's code</p>
9,385
<p>I am working on an ASP.NET web application that is required to bring up a popup on a roolover. I am using the "OnMouseOver" event and it works as expected. The problem is that the event is on a "hair trigger"; even a casual passage of the mouse over the control brings up the popup (which then must be manually dismissed). I want to add a delay so that a rapid pass over the control in question does not trigger the event. Is there a way to set such a delay or is there a different event that I could use to get the same "trigger event on a slow rollover"? </p>
<p>One solution that comes to mind, there may be better ways though:</p> <ol> <li>Make the <code>onmouseover</code> call the function via a <code>setTimeout</code> delay</li> <li>Inside the function, check the mouse is actually over that element.</li> </ol> <p>You could also use an <code>onmouseout</code> to clear the <code>setTimeout</code>, but then you'd have to store a reference to the timer in a global variable to get at it again.</p>
<p>What I ended up doing is as follows (oRow is a table row but it could be any control):</p> <pre><code>function ItemMouseOver(oRow, "parameters for the popup") { oRow.showTimer = window.setTimeout(function() { alert('popup'); }, 1000); } function ItemMouseOut(oRow) { if (oRow.showTimer) window.clearTimeout(oRow.showTimer); </code></pre> <p>In the ASP.NET grid view RowDataBound event: I added the following code:</p> <pre><code>protected void ReportGridView_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow &amp;&amp; ( e.Row.RowState == DataControlRowState.Normal || e.Row.RowState == DataControlRowState.Alternate)) { // get the input values for the popup for the row (stuff deleted) e.Row.Attributes["onmouseover"] = "javascript:ItemMouseOver(this, "parameters for the popup");"; e.Row.Attributes["onmouseout"] = "javascript:ItemMouseOut(this);"; } } </code></pre> <p>It works just fine. Thanks.</p>
44,874
<p>I currentyl have no clue on how to sort an array which contains UTF-8 encoded strings in PHP. The array comes from a LDAP server so sorting via a database (would be no problem) is no solution. The following does not work on my windows development machine (although I'd think that this should be at least a possible solution):</p> <pre><code>$array=array('Birnen', 'Äpfel', 'Ungetüme', 'Apfel', 'Ungetiere', 'Österreich'); $oldLocal=setlocale(LC_COLLATE, "0"); var_dump(setlocale(LC_COLLATE, 'German_Germany.65001')); usort($array, 'strcoll'); var_dump(setlocale(LC_COLLATE, $oldLocal)); var_dump($array); </code></pre> <p>The output is:</p> <pre><code>string(20) "German_Germany.65001" string(1) "C" array(6) { [0]=&gt; string(6) "Birnen" [1]=&gt; string(9) "Ungetiere" [2]=&gt; string(6) "Äpfel" [3]=&gt; string(5) "Apfel" [4]=&gt; string(9) "Ungetüme" [5]=&gt; string(11) "Österreich" } </code></pre> <p>This is complete nonsense. Using 1252 as the codepage for <code>setlocale()</code> gives another output but still a plainly wrong one:</p> <pre><code>string(19) "German_Germany.1252" string(1) "C" array(6) { [0]=&gt; string(11) "Österreich" [1]=&gt; string(6) "Äpfel" [2]=&gt; string(5) "Apfel" [3]=&gt; string(6) "Birnen" [4]=&gt; string(9) "Ungetüme" [5]=&gt; string(9) "Ungetiere" } </code></pre> <p>Is there a way to sort an array with UTF-8 strings locale aware?</p> <p><em>Just noted that this seems to be PHP on Windows problem, as the same snippet with <code>de_DE.utf8</code> used as locale works on a Linux machine. Nevertheless a solution for this Windows-specific problem would be nice...</em></p>
<pre><code>$a = array( 'Кръстев', 'Делян1', 'делян1', 'Делян2', 'делян3', 'кръстев' ); $col = new \Collator('bg_BG'); $col-&gt;asort( $a ); var_dump( $a ); </code></pre> <p>Prints:</p> <pre><code>array 2 =&gt; string 'делян1' (length=11) 1 =&gt; string 'Делян1' (length=11) 3 =&gt; string 'Делян2' (length=11) 4 =&gt; string 'делян3' (length=11) 5 =&gt; string 'кръстев' (length=14) 0 =&gt; string 'Кръстев' (length=14) </code></pre> <p>The <code>Collator</code> class is defined in <a href="http://www.php.net/manual/en/book.intl.php" rel="noreferrer">PECL intl extension</a>. It is distributed with PHP 5.3 sources but might be disabled for some builds. E.g. in Debian it is in package php5-intl .</p> <p><code>Collator::compare</code> is useful for <code>usort</code>.</p>
<p>Your collation needs to match the character set. Since your data is UTF-8 encoded, you should use a UTF-8 collation. It could be named differently on different platforms, but a good guess would be <code>de_DE.utf8</code>.</p> <p>On UNIX systems, you can get a list of currently installed locales with the command</p> <pre><code>locale -a </code></pre>
14,634
<p>An MXML component can be quite complex, containing many nested controls, including asynchronously loaded content such as Image/SWFLoader.</p> <p>Is there one event I can watch for on my component that will only be raised when every control and sub-component has loaded, including SWFs and Images?</p>
<p>CreationComplete will NOT do the trick if you are talking about loading swf content or anything really external like that. CreationComplete gets fired when the MXML components have been laid out as defined in MXML (IE nested components, buttons, boxes, canvasses, etc.), so content that needs to get loaded externally (an image, a swf) does not count.</p> <p>What you need to do is keep track of everything that you're waiting for and fire off a custom event once all of those elements have loaded.</p> <p>One possible hackish way to do it would be to listen for whatever load complete event is relevant for each element, then have them call back to the same function that increments a value equal to the number of components you're waiting for. This means you have to pay more attention if you're modifying it, but it also means you don't have to check a boolean for every element that needs to load (IE "if (image1Loaded &amp;&amp; image2Loaded &amp;&amp; swfLoaded)" etc.)</p>
<p>The onApplicationComplete event?</p>
18,722
<p>What is reflection, and why is it useful?</p> <p>I'm particularly interested in Java, but I assume the principles are the same in any language.</p>
<p>The name reflection is used to describe code which is able to inspect other code in the same system (or itself).</p> <p>For example, say you have an object of an unknown type in Java, and you would like to call a 'doSomething' method on it if one exists. Java's static typing system isn't really designed to support this unless the object conforms to a known interface, but using reflection, your code can look at the object and find out if it has a method called 'doSomething' and then call it if you want to.</p> <p>So, to give you a code example of this in Java (imagine the object in question is foo) :</p> <pre><code>Method method = foo.getClass().getMethod("doSomething", null); method.invoke(foo, null); </code></pre> <p>One very common use case in Java is the usage with annotations. JUnit 4, for example, will use reflection to look through your classes for methods tagged with the @Test annotation, and will then call them when running the unit test.</p> <p>There are some good reflection examples to get you started at <a href="http://docs.oracle.com/javase/tutorial/reflect/index.html" rel="noreferrer">http://docs.oracle.com/javase/tutorial/reflect/index.html</a></p> <p>And finally, yes, the concepts are pretty much similar in other statically typed languages which support reflection (like C#). In dynamically typed languages, the use case described above is less necessary (since the compiler will allow any method to be called on any object, failing at runtime if it does not exist), but the second case of looking for methods which are marked or work in a certain way is still common.</p> <p><strong>Update from a comment:</strong></p> <blockquote> <p>The ability to inspect the code in the system and see object types is not reflection, but rather Type Introspection. Reflection is then the ability to make modifications at runtime by making use of introspection. The distinction is necessary here as some languages support introspection, but do not support reflection. One such example is C++</p> </blockquote>
<p><strong>IMPORTANT</strong></p> <p>Starting from Java 9 you can no longer use reflection, unless the package-info.java <strong>opens</strong> the module to reflection access.</p> <p>By default, &quot;reflection&quot; access is denied to all packages in the module.</p> <p>See <a href="https://www.oracle.com/corporate/features/understanding-java-9-modules.html" rel="nofollow noreferrer">Understanding Java 9 Modules</a></p>
5,840
<p>I've written a script which takes the summary of an order and stores in into an XML file, except the problem is that I don't want people to be able to open the XML file in their browser, obviously.</p> <p>I'm hosted on a very dodgy shared server with limited abilities: no SSH, for starters.</p> <p><strong>Is there a place I can put this file so that PHP will still be able to read/write to it, but web browsers won't be able to get to it?</strong></p> <p>Ordinarily, I'd create a folder outside the document root and put it there, but I get a "Permission denied" message when I try that.</p> <p>The folders which <em>are</em> there are:</p> <ul> <li>anon_ftp</li> <li>bin</li> <li>cert</li> <li>cgi-bin</li> <li>conf</li> <li>error_docs</li> <li>etc</li> <li>httpdocs</li> <li>httpsdocs</li> <li>pd</li> <li>private</li> <li>statistics</li> <li>subdomains</li> <li>web_users</li> </ul> <p>PHP can't access the file when it's in the <code>private</code> folder. Would this be possible using .htaccess?</p>
<p>You could create a directory containing a <code>.htaccess</code> file that looks something like the following:</p> <pre><code>Deny from all </code></pre> <p>This will instruct Apache not to serve files from that directory; any attempts to access the directory or its contents will be met with a "403 Forbidden" response from the server.</p> <p><strong>Note:</strong> This depends upon the host not having removed <code>Limit</code> from the list of options in their <code>AllowOverride</code> directive; most shared hosts shouldn't have a reason to do this.</p>
<p>Couldn't you ask the shared-hosting provider to create an outside-web-root folder <strong>for you</strong>? I've certainly done this in the past.</p>
39,106
<p>Typically when writing new code you discover that you are missing a #include because the file doesn't compile. Simple enough, you add the required #include. But later you refactor the code somehow and now a couple of #include directives are no longer needed. How do I discover which ones are no longer needed? </p> <p>Of course I can manually remove some or all #include lines and add them back until the file compiles again, but this isn't really feasible in a large project with thousands of files. Are there any tools available that will help automating task?</p>
<p>You can use <a href="http://www.gimpel.com/" rel="nofollow noreferrer">PC-Lint/FlexeLint</a> to do that.</p> <p>Unusually there isn't a free OS version of the tool available.</p> <p>You can remove #includes by passing by reference instead of passing by value and forward declaring. This is because the compiler doesn't need to know the size of the object at compile time. This will require a large amount of manual work on your behalf however. The good thing is it will reduce your compile times.</p>
<p>Here is 'brute force' VC6 macro which works on single <strong><em>.cpp</strong> or <strong></em>.h</strong> file opened in editor by commenting include by include and running compile:</p> <pre><code>Sub RemoveNotUsedIncludes() 'Check if already processed; Exit if so ActiveDocument.Selection.FindText "//INCLUDE NOT USED", dsMatchFromStart IF ActiveDocument.Selection &lt;&gt; "" THEN ActiveDocument.Selection.SetBookmark MsgBox "Already checked" ActiveDocument.Selection.ClearBookmark EXIT SUB END IF 'Find first #include; Exit if not found ActiveDocument.Selection.FindText "#include", dsMatchFromStart IF ActiveDocument.Selection = "" THEN MsgBox "No #include found" EXIT SUB END IF Dim FirstIncludeLine FirstIncludeLine = ActiveDocument.Selection.CurrentLine FOR i=1 TO 200 'Test build ActiveDocument.Selection.SetBookmark ActiveDocument.Selection = "//CHECKING... #include" Build ActiveDocument.Undo ActiveDocument.Selection.ClearBookmark IF Errors = 0 THEN 'If build failed add comment ActiveDocument.Selection.EndOfLine ActiveDocument.Selection = " //INCLUDE NOT USED" END IF 'Find next include ActiveDocument.Selection.EndOfLine ActiveDocument.Selection.FindText "#include" 'If all includes tested exit IF ActiveDocument.Selection.CurrentLine = FirstIncludeLine THEN EXIT FOR NEXT </code></pre> <p>End Sub</p> <p>Of case it could be improved to work on whole project.</p>
7,467
<p>I have the following attributes in my DB.</p> <blockquote> <p>statistic id, devicename, value, timestamp.</p> </blockquote> <p>For a given statistic, I want to find the 2 most recent timestamps and corresopnding values for a every unique device.</p> <p>I am trying stuff like </p> <p>Trial 1)</p> <pre><code>select statistic, devicename, value, timestamp from X_STATSVALUE where statistic=19 order by orgtime DESC limit 2; </code></pre> <p>This gives me the top 2 timestamps, but not per device.</p> <p>Trial 2)</p> <pre><code>select statistic, devicename, value, timestamp from X_STATSVALUE as x where x.statistic=241 and (select count(*) from X_STATSVALUE as y where y.statistic=x.statistic and y.device=x.device and y.timestamp &gt; x.timestamp) &lt;=1; </code></pre> <p>But that's not working too well either..</p> <p>Basically, I want the 2 most recent timestamps with values for each device, for a given statistic.. any help is really appreciated :)</p>
<p>This is how I solve this type of problem:</p> <pre><code>SELECT x.statistic, x.devicename, x.value, x.timestamp FROM X_STATSVALUE AS x LEFT OUTER JOIN X_STATSVALUE AS x2 ON (x.statistic = x2.statistic AND x.devicename = x2.devicename AND x.timestamp &lt; x2.timestamp) GROUP BY x.statistic, x.devicename HAVING COUNT(*) &lt; 2; </code></pre> <p>In other words, show the rows such that there are fewer than two other rows with the same <code>statistic</code> and <code>devicename</code> and a greater (more recent) <code>timestamp</code>.</p> <p>I'm assuming that you won't have duplicates in the <code>timestamp</code> column for a given statistic &amp; devicename.</p>
<p>Try something like :</p> <pre><code>SELECT DISTINCT x.statistic, x.devicename, x.value, x.timestamp FROM X_STATSVALUE AS x WHERE x.timestamp IN (SELECT timestamp FROM X_STATSVALUE WHERE devicename = x.devicename AND statistic = x.statistic ORDER BY timestamp LIMIT 2) </code></pre> <p>(may not work in old MySQL though)</p>
46,206
<p>What's the best way to make a linked list in Java?</p>
<p>The obvious solution to developers familiar to Java is to use the <strong>LinkedList</strong> class already provided in <strong>java.util</strong>. Say, however, you wanted to make your own implementation for some reason. Here is a quick example of a linked list that inserts a new link at the beginning of the list, deletes from the beginning of the list and loops through the list to print the links contained in it. <strong>Enhancements</strong> to this implementation include making it a <strong>double-linked list</strong>, adding methods to <strong>insert</strong> and <strong>delete</strong> from the middle or end, and by adding <strong>get</strong> and <strong>sort</strong> methods as well. </p> <p><strong>Note</strong>: In the example, the Link object doesn't actually contain another Link object - <em>nextLink</em> is actually only a reference to another link. </p> <pre><code>class Link { public int data1; public double data2; public Link nextLink; //Link constructor public Link(int d1, double d2) { data1 = d1; data2 = d2; } //Print Link data public void printLink() { System.out.print("{" + data1 + ", " + data2 + "} "); } } class LinkList { private Link first; //LinkList constructor public LinkList() { first = null; } //Returns true if list is empty public boolean isEmpty() { return first == null; } //Inserts a new Link at the first of the list public void insert(int d1, double d2) { Link link = new Link(d1, d2); link.nextLink = first; first = link; } //Deletes the link at the first of the list public Link delete() { Link temp = first; if(first == null){ return null; //throw new NoSuchElementException(); // this is the better way. } first = first.nextLink; return temp; } //Prints list data public void printList() { Link currentLink = first; System.out.print("List: "); while(currentLink != null) { currentLink.printLink(); currentLink = currentLink.nextLink; } System.out.println(""); } } class LinkListTest { public static void main(String[] args) { LinkList list = new LinkList(); list.insert(1, 1.01); list.insert(2, 2.02); list.insert(3, 3.03); list.insert(4, 4.04); list.insert(5, 5.05); list.printList(); while(!list.isEmpty()) { Link deletedLink = list.delete(); System.out.print("deleted: "); deletedLink.printLink(); System.out.println(""); } list.printList(); } } </code></pre>
<p>Its much better to use java.util.LinkedList, because it's probably much more optimized, than the one that you will write.</p>
3,131
<p>I am thinking about something like this:</p> <pre><code>public static &lt;T extends Comparable&lt;T&gt;&gt; T minOf(T...ts){ SortedSet&lt;T&gt; set = new TreeSet&lt;T&gt;(Arrays.asList(ts)); return set.first(); } public static &lt;T extends Comparable&lt;T&gt;&gt; T maxOf(T...ts){ SortedSet&lt;T&gt; set = new TreeSet&lt;T&gt;(Arrays.asList(ts)); return set.last(); } </code></pre> <p>But is not null safe, which is something I want too.</p> <p>Do you know a better way to solve this problem?</p> <p>EDIT:</p> <p>After the comments I have also tried min():</p> <pre><code>public static &lt;T extends Comparable&lt;T&gt;&gt; T minOf(T...ts){ return Collections.min(Arrays.asList(ts), new Comparator&lt;T&gt;(){ public int compare(T o1, T o2) { if(o1!=null &amp;&amp; o2!=null){ return o1.compareTo(o2); }else if(o1!=null){ return 1; }else{ return -1; } }}); } </code></pre> <p>What do you think of that?</p>
<p>What's wrong with <a href="http://java.sun.com/javase/6/docs/api/java/util/Collections.html#max(java.util.Collection)" rel="noreferrer">Collections.max</a>?</p> <p>And why do you care about null safety? Are you sure you want to allow nulls to be in your Collection?</p>
<p>You <em>should not</em> implement <code>Comparable</code> to accept null, as it breaks the interface's contract.</p> <p>From <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html" rel="nofollow noreferrer">https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html</a> : </p> <blockquote> <p>Note that null is not an instance of any class, and e.compareTo(null) should throw a NullPointerException even though e.equals(null) returns false.</p> </blockquote> <p>You must instead create a new interface, e.g. <code>ComparableNull</code> instead.</p> <p>See also:</p> <ul> <li><a href="https://stackoverflow.com/questions/6259354/what-should-int-compareto-return-when-the-parameter-string-is-null">What should int compareTo() return when the parameter string is null?</a></li> <li><a href="https://stackoverflow.com/questions/481813/how-to-simplify-a-null-safe-compareto-implementation">How to simplify a null-safe compareTo() implementation?</a></li> </ul>
48,243
<p>A fellow maker has tried printing a 3D model in clear PLA (&lt;5% infill, 1 or 2 perimeters), burying it most of the way into casting sand, and then pouring molten aluminum. This melts and burns the PLA, and the aluminum takes the space that the printed model used to take.</p> <p>There's plenty of room for improvement in his process, but I'm asking about what he can do in terms of the 3D printing process to make his prints more casting-friendly.</p> <p>What print settings are (generally) best for use in this sort of casting?</p> <p>What materials, if any, would work better than unpigmented PLA? (Must be a material that a typical thermoplastic FDM printer can handle.)</p> <p>Any other tips or considerations?</p>
<p>Print a two part negative (mold) of your objects. <a href="http://www.thingiverse.com/thing:31581" rel="nofollow">http://www.thingiverse.com/thing:31581</a></p> <p><a href="https://pinshape.com/blog/how-to-generate-a-3d-printed-mold-for-an-object/" rel="nofollow">https://pinshape.com/blog/how-to-generate-a-3d-printed-mold-for-an-object/</a></p> <p>Melt and pour wax into the mold. Praffin wax melts at only 37C, not an issue for both PLA and ABS. Use the wax object for casting, not ABS/PLA/etc. The mold is also reusable this way.</p> <p>To prevent the wax from sticking to the mold, something might be applied to the surface. Oil maybe?</p>
<p>I believe casting typically uses a wax for the positive when using casting sand. So, I would suggest using <a href="http://www.machinablewax.com/product.php?product=52" rel="nofollow">wax filament</a> in your 3D printer.</p> <p>I would try to shy away from hard polymers like PLA/ABS/Nylon (all typical 3D printing filaments) if the goal is to "melt it away" because a certain amount of the plastic material will either bind itself with the metal or large chunks of plastic will cause inclusions in your part. Both of these side effects will potentially degrade the quality/strength of your part.</p> <p>I haven't personally used wax filament, so I can't tell you what the correct setting are. However, you can get most of the necessary information from whichever supplier you go through. I might suggest running your machine slower when using a low-melting filament such as wax or PVA (water soluble).</p>
128
<p>I've done many web apps where the first thing you do is make a user table with usernames, passwords, names, e-mails and all of the other usual flotsam. My current project presents a situation where non-users records need to function similarly to users, but do not need to the ability to be a first order user. </p> <p>Is it reasonable to create a second table, <code>people_tb</code>, that is the main relational table and data store, and only use the <code>users_tb</code> for authentication? Does separating <code>user_tb</code> from <code>people_tb</code> present any problems? If this is commonly done, what are some strategies and solutions as well as drawbacks? </p>
<p>This is certainly a good idea, as you are normalizing the database. I have done a similar design in an app that I am writing, where I have an employee table and a user table. Users may a from an external company or an employee, so I have separate tables because an employee is always a user, but a user may not be an employee.</p> <p>The issues that you'll run into is that whenever you use the user table, you'll nearly always want the person table to get the name or other common attributes you would want to show up. </p> <p>From a coding standpoint, if you're using straight SQL, it will take a little more effort to mentally parse the select statement. It may be a little more complicated if you're using an ORM library. I don't have enough experience with those.</p> <p>In my application, I'm writing it in Ruby on Rails, so I'm constantly doing things like employee.user.name, where if I kept them together, it would be just employee.name or user.name.</p> <p>From a performance standpoint, you are hitting two tables instead of one, but given proper indexes, it should be negligible. If you had an index that contained the primary key and the person name, for instance, the database would hit the user table, then the index for the person table (with a nearly direct hit), so the performance would be nearly the same as having one table.</p> <p>You could also create a view in the database to keep both tables joined together to give you additional performance enhancements. I know in the later versions of Oracle you can even put an index on a view if needed to increase performance.</p>
<p>I always try to avoid as much data repetition as possible. If not all people need to login, you can have a generic <code>people</code> table with the information that applies to both people and users (eg. firstname, lastname, etc).</p> <p>Then for people that login, you can have a <code>users</code> table that has a 1~1 relationship with <code>people</code>. This table can store the username and password.</p>
11,841
<p>What would be the simplest way to daemonize a python script in Linux ? I need that this works with every flavor of Linux, so it should only use python based tools. </p>
<p>See <a href="http://www.kohala.com/start/" rel="noreferrer">Stevens</a> and also this <a href="http://code.activestate.com/recipes/278731/" rel="noreferrer">lengthy thread on activestate</a> which I found personally to be both mostly incorrect and much to verbose, and I came up with this:</p> <pre><code>from os import fork, setsid, umask, dup2 from sys import stdin, stdout, stderr if fork(): exit(0) umask(0) setsid() if fork(): exit(0) stdout.flush() stderr.flush() si = file('/dev/null', 'r') so = file('/dev/null', 'a+') se = file('/dev/null', 'a+', 0) dup2(si.fileno(), stdin.fileno()) dup2(so.fileno(), stdout.fileno()) dup2(se.fileno(), stderr.fileno()) </code></pre> <p>If you need to stop that process again, it is required to know the pid, the usual solution to this is pidfiles. Do this if you need one</p> <pre><code>from os import getpid outfile = open(pid_file, 'w') outfile.write('%i' % getpid()) outfile.close() </code></pre> <p>For security reasons you might consider any of these after demonizing</p> <pre><code>from os import setuid, setgid, chdir from pwd import getpwnam from grp import getgrnam setuid(getpwnam('someuser').pw_uid) setgid(getgrnam('somegroup').gr_gid) chdir('/') </code></pre> <p>You could also use <a href="http://en.wikipedia.org/wiki/Nohup" rel="noreferrer">nohup</a> but that does not work well with <a href="http://docs.python.org/lib/module-subprocess.html" rel="noreferrer">python's subprocess module</a></p>
<p>Use <a href="http://www.clapper.org/software/python/grizzled/" rel="nofollow noreferrer">grizzled.os.daemonize</a>:</p> <pre><code>$ easy_install grizzled &gt;&gt;&gt; from grizzled.os import daemonize &gt;&gt;&gt; daemon.daemonize() </code></pre> <p>To understand how this works or to do it yourself, read <a href="http://code.activestate.com/recipes/278731/" rel="nofollow noreferrer">the discussion on ActiveState</a>.</p>
14,134
<p>I have a rather large file (150 million lines of 10 chars). I need to split it in 150 files of 2 million lines, with each output line being alternatively the first 5 characters or the last 5 characters of the source line. I could do this in Perl rather quickly, but I was wondering if there was an easy solution using bash. Any ideas?</p>
<p>Homework? :-)</p> <p>I would think that a simple pipe with sed (to split each line into two) and split (to split things up into multiple files) would be enough.</p> <p>The man command is your friend.</p> <hr> <p>Added after confirmation that it is not homework:</p> <p>How about</p> <pre><code>sed 's/\(.....\)\(.....\)/\1\n\2/' input_file | split -l 2000000 - out-prefix- </code></pre> <p>?</p>
<p>I think that something like this could work:</p> <pre><code>out_file=1 out_pairs=0 cat $in_file | while read line; do if [ $out_pairs -gt 1000000 ]; then out_file=$(($out_file + 1)) out_pairs=0 fi echo "${line%?????}" &gt;&gt; out${out_file} echo "${line#?????}" &gt;&gt; out${out_file} out_pairs=$(($out_pairs + 1)) done </code></pre> <p>Not sure if it's simpler or more efficient than using Perl, though.</p>
8,928
<p>If you have a Java object and an XML schema (XSD), what is the best way to take that object and convert it into an xml file in line with the schema. The object and the schema do not know about each other (in that the java classes weren't created from the schema).</p> <p>For example, in the class, there may be an integer field 'totalCountValue' which would correspond to an element called 'countTotal' in the xsd file. Is there a way of creating a mapping that will say "if the object contains an int totalCountValue, create an element called 'countTotal' and put it into the XML". Similarly, there may be a field in the object that should be ignored, or a list in the object that should correspond to multiple XML elements.</p> <p>I looked at XStream, but didn't see any (obvious) way of doing it. Are there other XML libraries that can simplify this task?</p>
<p>I believe this can be achieved via JAXB using it's annotations. I've usually found it much easier to generate Objects from JAXB ( as defined in your schema) using XJC than to map an existing Java object to match my schema. YMMV.</p>
<p>I would say JAXB or Castor. I have found Castor to be easier to use and more reliable, but JAXB is the standard</p>
32,890
<pre><code>private static final GridLayout layout = new GridLayout( 3, 1, 1, 0 ); </code></pre> <p>in this line of code what do the numbers represent and how do you use them to arrange the checkboxes and buttons in the window?</p>
<p>I refer you to: <a href="http://java.sun.com/javase/6/docs/api/java/awt/GridLayout.html" rel="noreferrer">http://java.sun.com/javase/6/docs/api/java/awt/GridLayout.html</a></p>
<p>I refer you to: <a href="http://java.sun.com/javase/6/docs/api/java/awt/GridLayout.html" rel="noreferrer">http://java.sun.com/javase/6/docs/api/java/awt/GridLayout.html</a></p>
47,096
<p>I am trying to add a project reference or swc to papervision in FlashDevelop but intellisense isn't picking it up. I've done it before but i forgot how.</p> <p>Thanks.</p>
<p>Add your swc to the lib folder of your project. Then right-click it and mark "Add To Library".</p>
<p>In the menus:</p> <pre><code>Project -&gt; Properties -&gt; Compiler Options -&gt; SWC Libraries </code></pre> <p>(and then add the path or file to the list)</p>
13,547
<p>Visual studio is pretty good but doesn't create stored procedures automatically. Iron Speed designer does supposedly. But is it any good?</p>
<p>I have used Ironspeed extensively for the past two years for most of our ASP.NET forms over data projects. </p> <p>It works. Does several things well: stored procs, fast layout of table browse and CRUD screens, fast layout of single record CRUD screens. It manages the round-trip (or half-round trip) process decently, detecting changes in your back end db schema and updating its data access layer, then making the changed columns available for you to alter your UI (in record or table control panels). ISD (as they call it) does an excellent job in making security management for your app pretty painless, even down to the control level (if you use ISD's subclassed versions of asp.net controls). Final plus, not a small one, is the CSS-based theme control (easy to change to a variety of themes, easy to customize a particular theme, and not even too bad to build your own theme variant by forking an existing one you like). Depending upon whether you let ISD create your stored procs in the code base or the database, changing DB's at run time can be a piece of cake.</p> <p>Fairly active forum with a core group of helpful contributors. You can probably avoid the paid tech support through the forum.</p> <p>Okay, the down sides. Creates fairly large code conglomerations, being a three tiered architecture. As Galwegian says, like any framework, you've got the velvet handcuffs (get your mind out of the gutter if you are thinking about anything other than code limitations and conventions!). The velvet handcuffs are the page and control model, the data layer, lack of a business object/class capability per se, the postback model, and the temptation to make your user GUI look like THEIR user GUI that comes out of the box because it is so darned easy and convenient.</p> <p>ISD builds a basic page by combining an HTML template (in to which you place ISD specific code generation tags and any other tags, etc., you which using the ISD GUI or by hand). The page model relies upon a code behind page created from a piece of code template. The base classes are almost completely overridable, so that you can override all of the default functions, regenerate the application and not lose your overrides. The database controls live in the page container, but have their own class definitions (i.e., their code-behind) in specific /app_code files. Again, each control type has its own base class with pretty completely overridable methods. A single record control (showing a single db record) is pretty simple. A table, showing several records, has a table class and a table row class. The ISD website (www.ironspeed.com/support) has good documentation of the ISD model as a whole.</p> <p>So, where are the problems in this model? 1. Easy and tempting to live with their out of the box GUI. Point ISD at your database, pick the tables you want to have it turn in to pages, tell it the kinds of pages, give it a thematic style and five minutes later you're viewing the application. Cool. But, it is very easy to forget that their user GUI is probably not what your user wants to see. So, be prepared to think for yourself and tinker with the GUI thus created. Not hard to do, and you can use VS 2005 to help you.</p> <ol start="2"> <li>Business objects. You could put together your own business objects, but it would be difficult and you would get no help from ISD. ISD does a LOT of building of simple validation and checking (appropriate look up values, ranges, lengths, etc.) ISD lets you build custom queries, but these are read-only. It is smart enough (and you can override the write from a page in any case) to let you take a one to many view and write it back to the database (you'd probably override the default base method, but it isn't that hard to do). However, when you get in to serious dependency checking, ISD is still really about tables and not business objects. So, you're going to write some code. </li> </ol> <p>If you are smart, you'll write it once store it in app_code somewhere and use it by calling it from an overridden method in your table or record controls. If you are like most of us, you'll first spaghetti it in to one of the code-behind classes above, and then forget you did so, or have a copy in each of the 10 pages that manipulates customer data. In my world, that has usually meant 5 identical functions and 5 that are all different (even though they are all supposed to be the same). ISD makes it tempting to order marinara, because the model lends itself to spaghetti code. Of course, you can completely prevent this, but you gotta learn the ISD model to determine the best way to do it on your project.</p> <ol start="3"> <li>Page state and postbacks. Although ISD is quite open about this problem and tells users not to just take the defaults of returning the whole asp.net page state in the postback stream (cache on the server instead), the default is to return the whole page. Can make for some BIG pages. Which makes users think S L O W. As I said, you can manipulate this. But, what newbie is going to get this when it is SO tempting to just point, click, and boom - instant application. Your manager is now off your back because her product inventory table is "on the web" with a cool search and edit GUI (of 400kb state pages if you've gone a bit nuts and have just taken the default behaviors of ISD). Great in-house, but the customers in the real world.... </li> </ol> <p>Again, knowledge is the key. You can fix this, but you need to know you SHOULD.</p> <ol start="4"> <li>Database read/write postbacks. No big problem here, but you also need to know that the model is to fetch only the data used at the moment. If your table shows 1000 records in 50 record increments, when you go from records 1 to 50 to 51 through 100, you will postback and hit the database again. This keeps data current, but increases server traffic.</li> </ol> <p>Overall: Try the demo version. Point it at something simple that you really want to turn in to an asp.net application. Build maybe three tables. Then dissect it using the above as a guide. See what YOU think and post back to this question.</p>
<p>Iron Speed Designer is great for simple CRUD type web applications. You can find some useful information on our web site <a href="http://www.dotnetarchitect.co.uk/" rel="nofollow">http://www.dotnetarchitect.co.uk/</a></p>
10,854
<p>I need to combine a VB web project and a C# web project and have them run alongside each other in the same web root. For instance, I need to be able to navigate to <code>localhost:1234/vbProjPage.aspx</code> and then redirect to <code>localhost:1234/cSharpProjPage.aspx</code>. Is this possible from within Visual Studio 2008?</p> <p>I know you have the ability to create a web site and throw everything into the root, but it would be best in this scenario to keep each project separate from each other.</p> <p>UPDATE: To answer Wes' question, it is possible but not desirable to change paths like that (<code>/vb/vbPage.aspx</code> &amp; <code>/cs/csPage.aspx</code>)</p> <p>UPDATE: Travis suggested using sub-web projects. This <a href="http://blogs.msdn.com/webdevtools/archive/2006/07/01/652986.aspx" rel="nofollow noreferrer">link</a> explains how to do it but the solution involves putting a project inside of a project, that is exactly what I am trying to avoid. I need the projects physically separated.</p>
<p>You can do this using sub-web projects. This has been available in Visual Studio since 2005 and works with the Web Application Project style of web site. <a href="http://weblogs.asp.net/scottgu/archive/2006/08/16/tip_2f00_trick_3a00_-creating-sub_2d00_web-projects-using-the-vs-2005-web-application-project-option.aspx" rel="nofollow noreferrer">ScottGu has a great blog entry describing the process.</a> You may face some interesting challenges getting pages to commingle in the same folder, but the sub-web project structure should still lend you some ideas.</p>
<p>I don't think you'll be able to have two seperate projects but intermixing them within one project isn't a problem. You could always organize the files into folder to keep things seperate if you felt the need.</p>
12,971
<p>I printed this <a href="https://www.thingiverse.com/thing:4775702" rel="nofollow noreferrer">Curvy vase</a> from Thingiverse and it came out pretty well on my Chiron.</p> <p><a href="https://i.stack.imgur.com/AP0wQ.jpg" rel="nofollow noreferrer" title="Curvy vase print"><img src="https://i.stack.imgur.com/AP0wQ.jpg" alt="Curvy vase print" title="Curvy vase print" /></a></p> <p>However, I am not happy with the Z-seam that is very large. When I look at other people's problems with this, they often seem to have too little filament at the seam, but I have too much. What setting should I change to make it less visible?</p> <ul> <li>Printer: Anycubic Chiron with Marlin 2.0.7</li> <li>Material: PLA</li> <li>Slicer: Cura 4.8.0.</li> <li>Nozzle: 0.4 mm</li> </ul> <p>All Cura settings are <a href="https://www.telder.com/bilder/stackexchange/curvy_vase/Curvy_Vase.html" rel="nofollow noreferrer">here</a> (except that I lowered printing temperature to 200 ºC while printing).</p> <p>All files used and some pictures are <a href="https://www.telder.com/bilder/stackexchange/curvy_vase/" rel="nofollow noreferrer">here</a>.</p> <hr /> <p>2021-03-07 <strong>Addendum</strong> after I made 19 test-prints of a small portion of the vase's neck. Below are some of my notes:</p> <ol start="8"> <li>Combing Mode=All is better than Off</li> <li>Speed=60 is worse than 40</li> <li>Retract Before Outer Wall=On is worse than Off</li> <li>Outer Wall Line Width 0.45 to 0.35 gave a Z-seam on the outside with more build-up</li> <li>Inner Wall(s) Line Width 0.45 to 0.35. Some places has less contact between layers, so less appealing and less robust. Also less material use.</li> <li>Outer Wall Wipe Distance 2.0 spread ot the seam (too much), and also made a ditch before the Z-seam (on the outside of the ring).</li> <li>Coasting tripled to Vol=0.588 and Wipe Distance 5.0 is more appealing. Two changes at once make it impossible to know which one helped. 5 mm is not enough to completely wipe.</li> <li>50% printing speed improved Z-seam and surface smoothness</li> </ol> <p>In the future I will use slower speed for Outer Walls, test Wipe distance=2*Line Width, use Combing (turned Off because of some advice to do so when LIN_ADVANCE is used) and experiment with faster retractions and Z-movement. Pictures and complete notes are available <a href="https://www.telder.com/bilder/stackexchange/curvy_vase/" rel="nofollow noreferrer">here</a>.</p>
<p>There is a <a href="https://support.ultimaker.com/hc/en-us/articles/360012512340-Shell-settings" rel="nofollow noreferrer">Cura option</a> to choose a random seam alignment in the shell menu:</p> <p><a href="https://i.stack.imgur.com/I6UXi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/I6UXi.png" alt="enter image description here" /></a></p> <blockquote> <h2>Z-seam alignment</h2> <p>This setting allows you to choose where each new layer in the Z direction starts and affects where the seam of the model will be. This is useful for models with consecutive equal layers as the seam can be visible. By changing the Z-seam alignment you can decrease the visibility of the seam. The options available are:</p> <ul> <li><strong>User-specified:</strong> Set a coordinate for the X and Y direction of the Z-seam. This coordinate is absolute by default. Example: X 100, Y 200 will move the seam to the center back of the model.</li> <li><strong>Shortest:</strong> The next layer starts at the endpoint of the previous layer. This is the fastest way of printing, but also creates the most visible seam.</li> <li><strong>Random:</strong> The next layer starts at a random point of the previous layer, which eliminates the chance of a seam. Print time will increase due to the necessary travel moves.</li> <li><strong>Sharpest corner:</strong> This puts the seam in the sharpest inward or outward corner of the model, when available. This is the best method to completely hide the seam.</li> </ul> </blockquote>
<p>Use Cura's &quot;Vase Mode&quot; (known as <code>Spiralize Outer Contour</code>) for seamless printing.</p>
1,878
<p>I am trying to see what are the gotchas in using XmlHttpWebRequest such that it works for Safari, Firefox and IE?</p>
<p>probably the most obvious difference is how to get an XMLHttpRequest in the first place:</p> <pre><code>var xhr; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); // Mozilla/Webkit/Opera } else if (window.ActiveXObject) { xhr = new ActiveXObject('Msxml2.XMLHTTP'); // IE } else { throw new Error('Ajax likely not supported'); } </code></pre> <p>that being said, i'd strongly look into an abstraction library such as <a href="http://jquery.com" rel="nofollow noreferrer">jQuery</a>. it makes things like ajax ridiculously easy:</p> <pre><code>$('#container').load('/ajax/resource'); </code></pre>
<p>I know it's a bit of a cop-out answer, but this sort of thing will drive you insane if you use the built-in and inconsistent-across-browsers methods. Pick any javascript library and breathe a sigh of relief.</p>
35,830
<p>What would be the easiest way to view classes, methods, properties, etc. inside a jar file? I'm looking for something equivalent to the very useful <I> Lutz Roeder .NET Reflector </I> - for Java</p>
<p>Using the JDK, <code>jar -tf</code> will list the files in the jar. <code>javap</code> will give you more details from a particular class file.</p>
<p>You could try <a href="http://sourceforge.net/project/showfiles.php?group_id=42094" rel="nofollow noreferrer">JarSpy</a>. There is an IDEA plugin version of it that I use.</p>
41,465
<p>I am looking for a way to delete all files older than 7 days in a batch file. I've searched around the web, and found some examples with hundreds of lines of code, and others that required installing extra command line utilities to accomplish the task.</p> <p>Similar things can be <a href="https://stackoverflow.com/questions/25785/delete-all-but-the-most-recent-x-files-in-bash">done in BASH</a> in just a couple lines of code. It seems that something at least remotely easy could be done for batch files in Windows. I'm looking for a solution that works in a standard Windows command prompt, without any extra utilities. Please no PowerShell or Cygwin either.</p>
<p>Enjoy:</p> <pre><code>forfiles -p "C:\what\ever" -s -m *.* -d &lt;number of days&gt; -c "cmd /c del @path" </code></pre> <p>See <a href="http://ss64.com/nt/forfiles.html" rel="noreferrer"><code>forfiles</code> documentation</a> for more details.</p> <p>For more goodies, refer to <em><a href="http://www.ss64.com/nt/" rel="noreferrer">An A-Z Index of the Windows&nbsp;XP command line</a></em>.</p> <p>If you don't have <code>forfiles</code> installed on your machine, copy it from any <a href="http://en.wikipedia.org/wiki/Windows_Server_2003" rel="noreferrer">Windows&nbsp;Server&nbsp;2003</a> to your Windows&nbsp;XP machine at <code>%WinDir%\system32\</code>. This is possible since the EXE is fully compatible between Windows&nbsp;Server&nbsp;2003 and Windows&nbsp;XP.</p> <p>Later versions of Windows and Windows&nbsp;Server have it installed by default.</p> <p>For Windows&nbsp;7 and newer (including Windows&nbsp;10):</p> <p>The syntax has changed a little. Therefore the updated command is:</p> <pre><code>forfiles /p "C:\what\ever" /s /m *.* /D -&lt;number of days&gt; /C "cmd /c del @path" </code></pre>
<p>More flexible way is to use <a href="https://github.com/npocmaka/batch.scripts/blob/master/hybrids/jscript/FileTimeFilterJS.bat" rel="nofollow noreferrer"><code>FileTimeFilterJS.bat</code></a>:</p> <pre><code>@echo off :::::::::::::::::::::: set &quot;_DIR=C:\Users\npocmaka\Downloads&quot; set &quot;_DAYS=-5&quot; :::::::::::::::::::::: for /f &quot;tokens=* delims=&quot; %%# in ('FileTimeFilterJS.bat &quot;%_DIR%&quot; -dd %_DAYS%') do ( echo deleting &quot;%%~f#&quot; echo del /q /f &quot;%%~f#&quot; ) </code></pre> <p>The script will allow you to use measurements like days, minutes ,seconds or hours. To choose weather to filter the files by time of creation, access or modification To list files before or after a certain date (or between two dates) To choose if to show files or dirs (or both) To be recursive or not</p>
7,393
<p>I would like to display a Drupal view without the page template that normally surrounds it - I want just the plain HTML content of the view's nodes.</p> <p>This view would be included in another, non-Drupal site.</p> <p>I expect to have to do this with a number of views, so a solution that lets me set these up rapidly and easily would be the best - I'd prefer not to have to create a .tpl.php file every time I need to include a view somewhere.</p>
<p>I was looking for a way to pull node data via ajax and came up with the following solution for Drupal 6. After implementing the changes below, if you add ajax=1 in the URL (e.g. mysite.com/node/1?ajax=1), you'll get just the content and no page layout.</p> <p>in the template.php file for your theme:</p> <pre><code>function phptemplate_preprocess_page(&amp;$vars) { if ( isset($_GET['ajax']) &amp;&amp; $_GET['ajax'] == 1 ) { $vars['template_file'] = 'page-ajax'; } } </code></pre> <p>then create page-ajax.tpl.php in your theme directory with this content:</p> <pre><code>&lt;?php print $content; ?&gt; </code></pre>
<p>If I understand your question, you want to have nodes which contain all the HTML for a page, from DOCTYPE to &lt;/HTML&gt;. What I would do is create a content type for those nodes -- "fullhtml" as its machine-readable name -- and then create a node template for it called node-fullhtml.tpl.php. You can't just dump the node's contents, as they've been HTML-sanitized. node.fullhtml.tpl.php would literally be just this:</p> <pre><code>echo htmlspecialchars_decode($content); </code></pre> <p>Then you'll need a way to override the standard page.tpl.php. I <em>think</em> what you could do is at the top of your page.tpl.php check the $node's content type, and bail out if it's fullhtml. Or, set a global variable in node-fullhtml.tpl.php that page.tpl.php would check for.</p> <p>I'm no Drupal expert, but that's how I'd do it. I'm talking off the cuff, so watch for devils in the details.</p>
30,813
<p>I am wondering if it is possible to have a sort of thumbnail image gallery, in which clicking on a thumbnail would show the full image in a layer. I was wondering if it was possible to load all layers and respective images and use javascript to change the z index or something similar to avoid having to reload or leave the page. I would prefer to avoid using a server side technology but don't know if this is possible.</p> <p>edit:</p> <p>I am not after a "lightbox" solution or anything that overlays the page, I rather want an image to appear as part of the page, and change without reloading the page, basically like PIctureSlide linked below. But more importanlt, I am wondering if this would be easy to write without using a framework, and if it would work as I thought above?</p>
<p>Yes, you can do it without a framework:</p> <pre><code>&lt;div id='big' style='width:500px;height:500px'&gt;&lt;/div&gt; &lt;a href="javascript://load big image" onclick="document.getElementById('big').style.backgroundImage='url(Big.gif)'"&gt;&lt;img border="0" src="images/Thumb.gif" /&gt;&lt;/a&gt; </code></pre> <p>Here is a simple example using the <a href="http://www.prototypejs.org" rel="nofollow noreferrer">Prototype</a> library:</p> <pre><code>&lt;div id='big' style='width:500px;height:500px'&gt;&lt;/div&gt; &lt;a href="javascript://load big image" onclick="$('big').style.backgroundImage='url(Big1.gif)'"&gt;&lt;img border="0" src="thumb1.gif" /&gt;&lt;/a&gt; </code></pre> <p>This script assumes that the big images are all 500 x 500 pixels.</p> <p>Here's an alternate way to do it:</p> <pre><code>&lt;div id='big'&gt;&lt;/div&gt; &lt;a href="javascript://load big image" onclick="loadBig('Big1.gif')"&gt;&lt;img border="0" src="thumb1.gif" /&gt;&lt;/a&gt; &lt;script type="text/javascript"&gt; function loadBig() { $('big').innerHTML = "&lt;img src='Big1.gif'&gt;" } &lt;/script&gt; </code></pre>
<p><a href="http://jquery.com/" rel="nofollow noreferrer">JQuery</a> should be able to make what you want.</p> <p>You have multiple thumbnails developped with it, like:</p> <ul> <li><a href="http://www.robertnyman.com/picture-slides/" rel="nofollow noreferrer">Picture-slide</a></li> <li><a href="http://herr-schuessler.de/blog/jquerypopeye-an-inline-lightbox-alternative/" rel="nofollow noreferrer">JQuery Popeye</a> (which could be close of what you are looking for)</li> </ul>
41,444
<p>I have an Ubuntu Server (with all of LAMP and Subversion installed). I use Eclipse with Subclipse, PDT and a few other great addins and use those exclusively to develop applications. The problem I'm having is that I'm developing on a Windows Vista machine and transferring everything to the remote Linux server. </p> <p>However, developing for windows and developing for Linux machines is quite different. One example would be the apostrophes/quotation marks required on the Windows server in the settings.ini file or the httpd.conf file. I tried installing XAMPP and getting the Eclipse debugger to work that way, but it was too much work and required me to constantly change my code when I moved them live on the server. I also tried using Wubi but didn't like that I had to reboot each time I wanted to go back to Vista.</p> <p>Is there a solution for this situation? Is there a way to run a virtual copy of Linux on Windows Vista that will allow me to install LAMP and debug through Eclipse? Is there a better program with Eclipse that will allow me to debug my code with an internal server?</p> <p>I'm looking for something really cheap as I'm in college and therefore low on funds, but am definitely open to any and all solutions to help me out.</p>
<p>You could use VMWare or Virtual PC to virtualise a linux build, or run the AMP stack up in <a href="http://www.cygwin.com/" rel="nofollow noreferrer">Cygwin</a>. Architecturally, Cygwin is a port of glibc adapted to sit on top of the Windows system call layer - it provides a unix-like system on top of Windows. There is a a large cross-section of ported software that you can install on it, including the AMP stack.</p> <p><strong>Edit:</strong> Just to add another good piece of software to the mix; <a href="http://virtualbox.org/wiki/Editions" rel="nofollow noreferrer">VirtualBox</a> is free for personal or evaluation use, partially open source, stable, and released by Sun. I've found it to be a good solid alternative to VMWare or Virtual PC.</p>
<p>I agree with NXC's answer (+1 ;) ), and here is a practical procedure to install a <a href="http://cmsproducer.com/Ubuntu-Linux-Windows-VMware-Server" rel="nofollow noreferrer">Linux on Windows XP using VMware Server</a>.</p> <p>That way, you will be able to deploy your server file directly on the target platform, but still debugging from a Widows eclipse session.</p> <p><a href="https://i.stack.imgur.com/enunp.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/enunp.gif" alt="alt text"></a><br> <sub>(source: <a href="http://cmsproducer.com/files/ubuntu-linux-vmware-windows.gif" rel="nofollow noreferrer">cmsproducer.com</a>)</sub> </p>
34,706
<p>What is the ideal code to logging ratio? I'm not used to writing logs as most of the applications I've developed have not had much logging.</p> <p>Recently though I've changed job, and I've noticed that you can't see the application code for the calls to log4net. I appreciate that this is useful but surely having too many debug statements is just as bad as not having any at all?</p> <p>There are logging statements that tell you when every method starts and finishes and what they are returning. and when pretty much anything is done.</p> <p>Would it not be easier to have some addon that used reflection to add the logging statements in at compile time so they didn't get in the way as you were trying to look at the code?</p> <p>Also in these days of powerful IDEs and remote debugging is that much logging really nescisary?</p>
<p>Since log4net does a great job at not clogging up the resources, I tend to be a little verbose on logging because when you have to change to debug mode, the more info you have, the better. Here's what I typically log:</p> <p><strong>DEBUG Level</strong></p> <ul> <li>Any parameters passed into the method</li> <li>Any row counts from result sets I retrieve</li> <li>Any datarows that may contain suspicious data when being passed down to the method </li> <li>Any "generated" file paths, connection strings, or other values that could get mungled up when being "pieced together" by the environment.</li> </ul> <p><strong>INFO Level</strong></p> <ul> <li>The start and end of the method</li> <li>The start and end of any major loops</li> <li>The start of any major case/switch statements</li> </ul> <p><strong>ERROR Level</strong></p> <ul> <li>Handled exceptions</li> <li>Invalid login attempts (if security is an issue)</li> <li>Bad data that I have intercepted forreporting</li> </ul> <p><strong>FATAL Level</strong></p> <ul> <li>Unhandled exceptions.</li> </ul> <p>Also having a lot of logging details prevents me from asking the user what they were doing when they got the error message. I can easily piece it together.</p>
<p>I think another factor is the toolset/platform being used and the conventions that come with it. For example, logging seems to be quite pervasive in the J(2)EE world, whereas I can't remember ever writing a log statement in a Ruby on Rails application.</p>
18,534
<p>I'm writing an app in C# (.net 3.5) and I have a question about class design: </p> <p>I'd like to create a class which accesses a file (read, write) and provides its content to the users (instanciators) of the class. The most common operation on an instance will be to retrieve a certain value from the file. The actual read and write (io) operations are faily expensive so I'd like to keep the file data in memory and let all instances access this data. The class is located in an assembly that is used from various applications simultaniously, so I guess I should be worrying about thread safety.</p> <p>How do I design this with respect to thread-safety and unit-testability (for unit-tests, different inputfiles must be used than in operational code)? Any help is greatly appreciated.</p>
<p>Firstly, make your class implement an appropriate interface. That way, clients can test their behaviour without needing real files at all.</p> <p>Testing the thread safety is hard - I've never seen anything which is really useful on that front, though that's not to say the tools aren't out there.</p> <p>For unit testing your class, I'd suggest that if possible it should work with a general stream rather than just a file. Then you can embed different test files in your test assembly, and refer to them with <a href="http://msdn.microsoft.com/en-us/library/system.reflection.assembly.getmanifestresourcestream.aspx" rel="nofollow noreferrer">GetManifestResourceStream</a>. I've done this several times in the past, with great success.</p>
<p>Regarding thread safety: Thread safety is not an issue unless multiple threads <em>within a single application</em> will be referring to the same instance of your class concurrently. Unless your class is contained within an out of process server, there is no way for multiple applications to refer to the same instance concurrently. Therefore, the conflicts you're likely to see will come from file sharing violations rather than threading issues (in other words, different <em>instances</em> of the class attempting to read and write the same <em>file</em>). And yes, you must design your code to deal with file sharing appropriately.</p> <p>One way to make the class unit testable is to provide the class with a stream in the constructor rather than having the class access a file directly. Then the unit test can supply a memory stream, for example, instead of supplying a file stream.</p>
25,537
<p>I'm tasked with replicating a production environment to create many test/sit environments.</p> <p>One of the things I need to do is build up Perl, with all the modules which have been installed (including internal and external modules) over the years. I could just use CPAN.pm autobundle, but this will result in the test environment having much newer versions of the external modules that production has.</p> <p>What is the easiest/best way to get and install (a lot of) version specific Perl modules.</p>
<p>bdfoy has the best large scale solution, but if you just want to install a few modules you can ask the CPAN shell to install a specific distribution by referencing a path to a tarball (relative to the top of the CPAN tree).</p> <pre><code>cpan&gt; install MSCHWERN/Test-Simple-0.62.tar.gz </code></pre> <p>Throw a URL to BackPAN into your URL list and you can install any older version.</p> <pre><code>cpan&gt; o conf urllist push http://backpan.perl.org/ </code></pre> <p>This is in the <a href="https://metacpan.org/pod/CPAN#pod12" rel="noreferrer">CPAN.pm FAQ</a> under "how do I install a 'DEVELOPER RELEASE' of a module?"</p>
<p><a href="https://stratopan.com" rel="nofollow noreferrer">Stratopan.com</a> is another alternative. Stratopan provides private CPANs in the cloud. You can fill your Stratopan repository with specific versions of modules (and their dependencies) and then install them using the standard Perl tool chain. The repository changes only when <em>you</em> decide to change it, so you'll get always get the versions of the modules that you want.</p> <p><em>Disclaimer: I operate Stratopan.</em></p>
32,579
<p>I have a directory on a linux box that I want to make publicly readable using Tomcat (5.5). I think this is easy to set up but can't find the appropriate documentation. Is there a simple way to accomplish this?</p>
<p>It is possible by defining that directory as an web application, but it's not really what Tomcat is designed to do, other servers are far better at serving static content.</p> <p>The way to define a directory as a webapp is to either</p> <ul> <li>put it into <code>$TOMCAT_HOME/webapps</code>,</li> <li>configure it in <code>$TOMCAT_HOME/conf/server.xml</code> or</li> <li>provide a context <code>.xml</code> file and put it in <code>$TOMCAT_HOME/conf/Catalina/localhost</code> (by default, depends on your configuration).</li> </ul>
<p>Although Tomcat is a good web server, it's not particularly made to list directories. </p> <p>You might want to look at a web server like the <a href="http://www.apache.org/" rel="nofollow noreferrer">Apache</a> web server instead, it's more designed for this type of thing.</p>
48,188
<p>Can I call a function from lisp from a library written in c or c++? How can I extend lisp? This is useful when you want to do some system calls or stuff like that.</p>
<p>It is unusual to call non-lisp code from lisp, and rarely necessary. CLX (the X11 client implementation for CL) doesn't link to the Xlib implementation but "speaks" X11 directly. On any system, your CL implementation is likely to already have excellent operating system hooks rendering this unnecessary.</p> <p>That said, the answer depends on the lisp implementation:</p> <p>In <a href="http://ecls.sourceforge.net/" rel="noreferrer">ECL</a> you can actually host a CL environment under C and simply call <code>cl_eval()</code> with the code to execute. This can let you write your application (or application host) in C (or C++) and "call to" lisp code.</p> <p>In <a href="http://www.clozure.com/clozurecl.html" rel="noreferrer">CCL</a>, there is a C-compatible calling interface which lets you do something like this:</p> <pre><code>(with-cstrs ((x "Hello World")) (#_puts x)) </code></pre> <p>In most other CL implementations (like SBCL; and yes this works in ECL and CCL as well) you can use UFFI (or CFFI) which simply lets you call C functions, which is what other people are talking about. If this is all you want to do, then CFFI is a good, safe place to start.</p>
<p><a href="http://common-lisp.net/project/cffi/" rel="nofollow noreferrer">CFFI</a>!</p>
49,666
<p>I know that new-ing something in one module and delete-ing it in another can often cause problems in VC++. Problems with different runtimes. Mixing modules with staticly linked runtimes and/or dynamically linked versioning mismatches both can screw stuff up if I recall correctly.</p> <p><strong>However, is it safe to use VC++ 2008's std::tr1::shared_ptr across modules?</strong></p> <p>Since there is only one version of the runtime that even knows what what a shared_ptr is, static linking is my only danger (for now...). I thought I've read that boost's version of a shared_ptr was safe to use like this, but I'm using Redmond's version...</p> <p>I'm trying to avoid having a special call to free objects in the allocating module. (or something like a "delete this" in the class itself). If this all seems a little hacky, I'm using this for unit testing. If you've ever tried to unit test existing C++ code you can understand how <strong><em>creative</em></strong> you need to be at times. My memory is allocated by an EXE, but ultimately will be freed in a DLL (if the reference counting works the way I think it does).</p>
<p>Freeing the memory is safe, so long as it all came from the same <em>memory management</em> context. You've identified the most common issue (different C++ runtimes); having separate heaps is another less-common issue you can run into.</p> <p>Another issue which you didn't mention, but which can be exascerbated by shared pointers, is when an object's code exists in the DLL and is created by the DLL, but another object outside the DLL ends up with a reference to it (via shared pointer). If that object is destroyed after the DLL is unloaded (for example, if it's a module-level static, or if the DLL is explicitly unloaded by <code>FreeLibrary()</code>, the shared object's destructor will crash. </p> <p>This can bite you if you attempt to write DLL-based, loosely-coupled plugins. It's also the reason that COM lets DLLs decide when they <em>can</em> be unloaded, rather than letting COM servers demand-unload them.</p>
<p>I'd guess it is as safe as to use any of the classes in <code>std</code> across modules.</p> <p>That is: It should be safe if the modules use exactly the same runtime library, and exactly the same compiler switches and options.</p> <p>Never use the static runtime library, as each module will get their own instance of all globals within it.</p>
44,886
<p>I have a group of checkboxes that I only want to allow a set amount to be checked at any one time. If the newly checked checkbox pushes the count over the limit, I'd like the oldest checkbox to be automatically unchecked. The group of checkboxes all use the same event handler shown below.</p> <p>I have achieved the functionality with a Queue, but it's pretty messy when I have to remove an item from the middle of the queue and I think there's a more elegant way. I especially don't like converting the queue to a list just to call one method before I convert the list back to a queue.</p> <ul> <li>Is there a better way to do this?</li> <li>Is it a good idea to unhook are rehook the event handlers like I did.</li> </ul> <p>Here's the code. </p> <pre><code>private Queue&lt;CheckBox&gt; favAttributesLimiter - new Queue&lt;CheckBox&gt;(); private const int MaxFavoredAttributes = 5; private void favoredAttributes_CheckedChanged(object sender, EventArgs e) { CheckBox cb = (CheckBox)sender; if (cb.Checked) { if (favAttributesLimiter.Count == MaxFavoredAttributes) { CheckBox oldest = favAttributesLimiter.Dequeue(); oldest.CheckedChanged -= favoredAttributes_CheckedChanged; oldest.Checked = false; oldest.CheckedChanged += new EventHandler(favoredAttributes_CheckedChanged); } favAttributesLimiter.Enqueue(cb); } else // cb.Checked == false { if (favAttributesLimiter.Contains(cb)) { var list = favAttributesLimiter.ToList(); list.Remove(cb); favAttributesLimiter=new Queue&lt;CheckBox&gt;(list); } } } </code></pre> <p>Edit: <br /> <a href="https://stackoverflow.com/questions/110385/limiting-a-group-of-checkboxes-to-a-certain-amount-of-checks#110398">Chakrit</a> answered my actual question with a better replacement for Queue(Of T). However, the argument that my idea of unchecking boxes was actually a bad idea was quite convincing. I'm leaving Chakrit's answer as accepted, but I've voted up the other answers because they're offering a more consistent and usable solution in the eyes of the user.</p>
<p>I think you are looking for a <a href="http://msdn.microsoft.com/en-us/library/he2s3bh7.aspx" rel="nofollow noreferrer">LinkedList</a>.</p> <p>Use <code>AddLast</code> instead of <code>Enqueue</code> and <code>RemoveFirst</code> instead of <code>Dequeue</code> and for removing something in the middle, just use a normal <code>Remove</code>.</p>
<p>If you ask a user to pick form a list of options and limit the number of choices it is likely that the first choice is there primary choice.</p> <p>e.g. Pick two, you will never have any of what you don't choose:</p> <ul> <li>Money</li> <li>Power</li> <li>Sex</li> <li>Excitement</li> <li>Gadgets</li> <li>Army of Coders.</li> </ul> <p>Was your first choice you primary choice?</p> <p>If you want to use check boxes, simply disable all the unchecked ones when the the second one is checked.</p>
13,565
<p>How do I open the default mail program with a Subject and Body in a cross-platform way?</p> <p>Unfortunately, this is for a a client app written in Java, not a website.</p> <p>I would like this to work in a cross-platform way (which means Windows and Mac, sorry Linux). I am happy to execute a VBScript in Windows, or AppleScript in OS X. But I have no idea what those scripts should contain. I would love to execute the user's default program vs. just searching for Outlook or whatever.</p> <p>In OS X, I have tried executing the command:</p> <pre><code>open mailto:?subject=MySubject&amp;body=TheBody </code></pre> <p>URL escaping is needed to replace spaces with <code>%20</code>.</p> <p><strong>Updated</strong> On Windows, you have to play all sorts of games to get <code>start</code> to run correctly. Here is the proper Java incantation:</p> <pre><code>class Win32 extends OS { public void email(String subject, String body) throws Exception { String cmd = "cmd.exe /c start \"\" \"" + formatMailto(subject, body) + "\""; Runtime.getRuntime().exec(cmd); } } </code></pre>
<p>In Java 1.6 you have a stardard way to open the default mailer of the platform: <a href="http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html" rel="noreferrer">the Desktop.mail(URI) method</a>.The URI can be used to set all the fields of the mail (sender, recipients, body, subject). You can check a full example of desktop integration in Java 1.6 on <a href="http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/" rel="noreferrer">Using the Desktop API in Java SE 6</a></p>
<p>I have implemented this, and it works well on OS X. (Ryan's mention of the max URL length has not been codified.)</p> <pre><code>public void email(String subject, String body) throws Exception { String cmd = "open mailto:"; cmd += "?subject=" + urlEncode(subject); cmd += "&amp;body=" + urlEncode(body); Runtime.getRuntime().exec(cmd); } private static String urlEncode(String s) { StringBuilder sb = new StringBuilder(); for (int i = 0; i &lt; s.length(); i++) { char ch = s.charAt(i); if (Character.isLetterOrDigit(ch)) { sb.append(ch); } else { sb.append(String.format("%%%02X", (int)ch)); } } return sb.toString(); } </code></pre> <p>I had to re-implement URLencode because Java's would use <code>+</code> for space and Mail took those literally. Haven't tested on Windows yet.</p>
3,804
<p>I'm trying to generate pairwise combinations of rows on based on their ids. SQLite version is 3.5.9. The table contents are the following:</p> <pre><code>id|name|val 1|A|20 2|B|21 3|C|22 </code></pre> <p>with table schema being:</p> <pre><code>CREATE TABLE mytable ( id INTEGER NOT NULL, name VARCHAR, val INTEGER, PRIMARY KEY (id) ); </code></pre> <p>Then there's the self-join on ids:</p> <pre><code>sqlite&gt; select t1.id, t2.id from mytable as t1, mytable as t2 where t2.id &gt; t1.id; id|id 2|2 2|3 3|3 </code></pre> <p>Which is clearly not what I want. Now, changing the order of t2 and t1 produces the correct result:</p> <pre><code>sqlite&gt; select t1.id, t2.id from mytable as t2, mytable as t1 where t2.id &gt; t1.id; id|id 1|2 1|3 2|3 </code></pre> <p>Now, for another experiment, I tried combining on a numeric column other than row id. That, on the other hand, gives correct result in both cases.</p> <p>I am hoping someone can give an insight into what's going on here. As far as I understand, its either a bug in SQLite or some delicate aspect of SQL I don't know.</p> <p>Thanks,</p>
<p>Seems to be a bug in SQLite - the first result you posted is, as you suspected, wrong. I've tested it on both PG8.3 and sqlite3.6.4 on my workstation, couldn't reproduce. Got correct result in all cases. Might be linked to your sqlite version; try upgrading.</p>
<pre><code>SQLite version 3.6.2 Enter ".help" for instructions Enter SQL statements terminated with a ";" sqlite&gt; create table mytable ( ...&gt; id integer not null, ...&gt; name varchar, ...&gt; val integer, ...&gt; primary key (id) ...&gt; ); sqlite&gt; insert into mytable values(null,'A',20); sqlite&gt; insert into mytable values(null,'B',21); sqlite&gt; insert into mytable values(null,'C',22); sqlite&gt; select t1.id, t2.id from mytable as t1, mytable as t2 where t2.id &gt; t1.id; 1|2 1|3 2|3 </code></pre>
39,065
<p>I'd like to give my boyfriend a taste of programming. If it was up to me, I'd teach Scheme, Haskell or F# but since he'd rather learn something that can be useful in his job as a fiscal consultant, i.e. programming Excel.</p> <p>What are the options for programming Excel? Which one would you recommend for someone who's just learning to program and yet wants to get things done? Are there any books / resources you recommend for him (advanced Excel user, beginner programmer) or me (intermediate Excel user, advanced programmer)?</p> <p>Thanks. I've started <a href="http://excel4vivi.blogspot.com/" rel="nofollow noreferrer">a blog about programming Excel</a> to document our findings.</p>
<p>As a long time (business) Excel user and programmer, I recommend starting with a good VBA book that focuses on the key features of the Basic language, and how to communicate with the Excel objects (workbooks, sheets, etc). I wouldn't worry about userforms, initially - I haven't used those for years - and I wouldn't worry too much about databases at first either.</p> <p>I suggest focusing on two areas in particular, starting with the Basic language itself, writing output to the Immediate window with Debug.Print and ignoring the fact that Excel is attached. You can get very good practice in this by solving some of the <a href="http://projecteuler.net/" rel="nofollow noreferrer">Euler problems</a>, which favour pure code solutions with no user interface.</p> <p>After that, I would learn how to talk to the Excel objects, and read as many Excel forums and web pages as possible to pick up tips. For example, it is much faster to read and write many cells at once, than one at a time.</p> <p>And yes, VBA is not as full featured as most 'professional' languages, but it has one crucial advantage over most of them - it is much easier to write and for the average user to check, modify and maintain - and checkability and flexibility are crucial in the business world. Together with Excel, it is an amazing business tool.</p>
<p>Macros are one way to program Excel. Check out this YouTube video: <a href="http://in.youtube.com/watch?v=k_fWcffRAG4" rel="nofollow noreferrer">http://in.youtube.com/watch?v=k_fWcffRAG4</a> It demonstrates how to Record and use Macro.</p>
35,013
<p>We have a file that has a 64 bit integer as a string in it. How do we scanf() or otherwise parse this numeric string into an unsigned 64 bit integer type in C++ ? </p> <p>We are aware of things like %lld etc., but a lot of ways to do this parse seem to break compiles under different compilers and stdlibs. The code should compile under gcc and the Microsoft C++ compiler (of course full compliance with standards would be a plus)</p>
<p>GCC has long long, as will compilers for C++0x. MSVC++ doesn't (yet), but does have its __int64 you can use.</p> <pre><code>#if (__cplusplus &gt; 199711L) || defined(__GNUG__) typedef unsigned long long uint_64_t; #elif defined(_MSC_VER) || defined(__BORLANDC__) typedef unsigned __int64 uint_64_t; #else #error "Please define uint_64_t" #endif uint_64_t foo; std::fstream fstm( "file.txt" ); fstm &gt;&gt; foo; </code></pre>
<p>Don't use <code>scanf()</code>, tokenize your input separately and then use <code>strtoull()</code> or similar.</p>
31,522
<p>I'm sick of remembering all the passwords for different logins. Lately I found the interesting tool <a href="http://www.xs4all.nl/~jlpoutre/BoT/Javascript/PasswordComposer/" rel="nofollow noreferrer">password composer</a> which lets you generate passwords base on the <strong>hostname</strong> and a secret <strong>master password</strong>. But I don't want to use a website or installing software to generate my passwords.</p> <p>So I'm looking for a simple one way hashing alogorithm which I can execute without computer aid to generate my passwords. Something in the spirit of the <a href="http://en.wikipedia.org/wiki/Solitaire_(cipher)" rel="nofollow noreferrer">solitare cipher</a> without the need for cards.</p> <p>Using a PW store is not an option.</p>
<p>Why don't you just use the exact same algorithm as the password composer?</p> <ul> <li>Pick a master password</li> <li>Take the application/machine name for which you want a password</li> <li>Concatenate the two (or shuffle)</li> <li>Apply a code you can do in your head, like <a href="http://en.wikipedia.org/wiki/Caesar%27s_cipher" rel="nofollow noreferrer">Caesar's cipher</a></li> <li>Take the first X characters (15 is usually a good length for secure passwords)</li> </ul> <p>Example:</p> <pre><code>Master Password: kaboom Machine Name: hal9000 Shuffle: khaablo9o0m00 Transposition table: shift 5 left abcdefghijklmnopqrstuvwxyz 1234567890 vwxyzabcdefghijklmnopqrstu 6789012345 Result: fcvvwgj4j5h55 </code></pre> <p>You could use as complex a substitution as your head can do reliably (with or without a paper). You could also use a different table for each password (say, deduce the table from the first letter of each machine name). As long as your master password is secure, there's nothing to fear about the simplicity of the algorithm.</p>
<p>Something I used to do (before I started using <em>pwgen</em> to generate my passwords) was to find a nearby paper document and use the first and last character of each line. So long as you know which document goes with which account, regenerating the password is easy if you lose/forget it and no computer is required to do so. (It is important to use a book or other paper document for this, of course, as anything electronic could change and then you'd be lost.)</p>
16,618
<p>Is there a way to have % in vim find the next ([{ or whatever, even if it is not on the same line?</p> <p>Example:</p> <pre><code>int main(int argc, char ** argv) { #Your cursor is somewhere in this comment, I want #it to get to the ( after printf printf("Hello there.\n"); } </code></pre>
<p>If you want to find opening braces on subsequent lines, without plugins, just enter normal mode and type:</p> <pre><code>/{ [enter] </code></pre> <p>Where { is the type of brace your looking for.</p> <p>You can then browse them all with <kbd>n</kbd> and <kbd>N</kbd>.</p> <p>To map the <kbd>F12</kbd> key to turn search highlighting on and off <a href="http://ronny.haryan.to/archives/2005/03/03/tip-quick-no-highlight-search-matches-in-vim/" rel="nofollow noreferrer">use this trick.</a></p>
<p>That's puzzling... For me, % finds the matching close for any {[( no matter how many lines away the match is. I don't see anything in my .vimrc that would change this behaviour, offhand.</p>
33,076
<p>I've used several apps now that launch the itunes store directly from the app. I'm even using some on my 2.1 iPod 2G.</p> <p>I know there's a bug in 2.1 that prevents appstore links from working in safari, but somehow people are launching the appstore directly, not even through safari.</p> <p>How do you do this? Is it an undocumented openURL feature?</p>
<p>From iTunes, drag the icon of your app to the desktop, this will give you a link you can use directly (for example, <a href="http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=284036524&amp;mt=8" rel="noreferrer"><a href="http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=284036524&amp;mt=8" rel="noreferrer">http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=284036524&amp;mt=8</a></a> launches the AppStore to Crosswords, both on a desktop and an iPhone). </p> <p>Pop this into an NSURL and call openURL on it. </p>
<p>If you are just releasing your app... you won't have an "app ID #" yet... so none of those methods will work.</p> <p>I had to insert a "non-working link" in my v1.0... and then later in my v1.1 update... added the actual link and app ID #.</p>
28,083
<p>When should I <strong>not</strong> use the ThreadPool in .Net?</p> <p>It looks like the best option is to use a ThreadPool, in which case, why is it not the only option?</p> <p>What are your experiences around this?</p>
<p>The only reason why I wouldn't use the <code>ThreadPool</code> for cheap multithreading is if I need to&hellip;</p> <ol> <li>interract with the method running (e.g., to kill it)</li> <li>run code on a <a href="http://msdn.microsoft.com/en-us/library/system.stathreadattribute.aspx" rel="nofollow noreferrer" title="Single-Threaded Apartment thread; see e.g. this MSDN reference page for STAThreadAttribute">STA thread</a> (this happened to me)</li> <li>keep the thread alive after my application has died (<code>ThreadPool</code> threads are background threads)</li> <li>in case I need to change the priority of the Thread. We can not change priority of threads in ThreadPool which is by default Normal.</li> </ol> <blockquote> <p><strong>P.S.:</strong> The MSDN article <a href="http://msdn.microsoft.com/en-us/library/0ka9477y.aspx" rel="nofollow noreferrer" title="The Managed Thread Pool (page on MSDN)"><em>"The Managed Thread Pool"</em></a> contains a section titled, <em>"When Not to Use Thread Pool Threads"</em>, with a very similar but slightly more complete list of possible reasons for not using the thread pool.</p> </blockquote> <p>There are lots of reasons why you would need to skip the <code>ThreadPool</code>, but if you don't know them then the <code>ThreadPool</code> should be good enough for you.</p> <p>Alternatively, look at the new <a href="https://learn.microsoft.com/en-us/visualstudio/extensibility/debugger/parallel-extension-internals-for-the-dotnet-framework" rel="nofollow noreferrer">Parallel Extensions Framework</a>, which has some neat stuff in there that may suit your needs without having to use the <code>ThreadPool</code>.</p>
<p>@Eric</p> <blockquote> <p>@Derek, I don't exactly agree with the scenario you use as an example. If you don't know exactly what's running on your machine and exactly how many total threads, handles, CPU time, RAM, etc, that your app will use under a certain amount of load, you are in trouble.</p> </blockquote> <p>Are you the only target customer for the programs you write? If not, you can't be certain about most of that. You generally have no idea when you write a program whether it will execute effectively solo, or if it will run on a webserver being hammered by a DDOS attack. You can't know how much CPU time you are going to have.</p> <p>Assuming your program's behavior changes based on input, it's rare to even know exactly how much memory or CPU time your program will consume. Sure, you should have a pretty good idea about how your program is going to behave, but most programs are never analyzed to determine exactly how much memory, how many handles, etc. will be used, because a full analysis is expensive. If you aren't writing real-time software, the payoff isn't worth the effort.</p> <p>In general, claiming to know exactly how your program will behave is far-fetched, and claiming to know everything about the machine approaches ludicrous.</p> <blockquote> <p>And to be honest, if you don't know exactly what method you should use: manual threads, thread pool, delegates, and how to implement it to do just what your application needs, you are in trouble.</p> </blockquote> <p>I don't fully disagree, but I don't really see how that's relevant. This site is here specifically because programmers don't always have all the answers.</p> <blockquote> <p>If your application is complex enough to require throttling the number of threads that you use, aren't you almost always going to want more control than what the framework gives you?</p> </blockquote> <p>No. If I need a thread pool, I will use the one that's provided, unless and until I find that it is not sufficient. I will not simply assume that the provided thread pool is insufficient for my needs without confirming that to be the case.</p> <blockquote> <p>I'm not speaking as someone with only theoretical knowledge here. I write and maintain high volume applications that make heavy use of multithreading, and I generally don't find the thread pool to be the correct answer.</p> </blockquote> <p>Most of my professional experience has been with multithreading and multiprocessing programs. I have often needed to roll my own solution as well. That doesn't mean that the thread pool isn't useful, or appropriate in many cases. The thread pool is built to handle worker threads. In cases where multiple worker threads are appropriate, the provided thread pool should should generally be the first approach.</p>
3,148
<p>I am adding membership-related schemas to an existing database (lets call it myDatabase) following <a href="https://web.archive.org/web/20210506052241/http://aspnet.4guysfromrolla.com/articles/040506-1.aspx" rel="nofollow noreferrer">those instructions</a>.</p> <p>As a results the number of tables, views and stored procedures are being created in myDatabase.</p> <p>The next step is to modify web.config for the application to use CustomizedMembershipProvider</p> <pre><code>&lt;membership defaultProvider="CustomizedMembershipProvider"&gt; &lt;providers&gt; &lt;add name="CustomizedMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="MyDBConnectionString" /&gt; &lt;/providers&gt; &lt;/membership&gt; </code></pre> <p>Then we also need to specify the connection string like:</p> <pre><code>&lt;connectionStrings&gt; &lt;add name="MyDB" MyDBConnectionString ="..." /&gt; &lt;/connectionStrings&gt; </code></pre> <p><strong>Here is my question:</strong></p> <ol> <li>Should I use different connection string to the one the application uses? As is there a need to create a new user in the database with permissions related specifically to the membership objects?</li> <li>Once the connection string is specified with the User ID etc., do I need to grant permissions for that user for those newly created objects? Would that be for stored procedures only or also tables and views?</li> </ol> <p><strong>EDIT:</strong> I noticed that there was a set of roles created in the database along with the membership object. So it is a matter of assigning the user to the proper role(s). The roles are the likes of </p> <pre><code>aspnet_Membership_FullAccess aspnet_Personalization_FullAccess etc... </code></pre> <p>So the only the first part of the question remains in place. So is there a point in creating a new database user (so separate db connection)</p>
<p>I looked it up a bit, </p> <ol> <li>The standard connection can be used</li> <li>In terms of permissions it looks like it is a matter of assigning the database user to the aspnet_Membership_FullAccess role (<a href="http://msdn.microsoft.com/en-us/library/ms164596(VS.80).aspx" rel="nofollow noreferrer">other roles if you require privileges related to them</a>)</li> </ol>
<ol> <li>It's perfectly okay to use the same user/database as your application.</li> <li>I don't know, sorry. </li> </ol>
35,963
<p>I have converted one of my VS2006 projects into VS2008 and when trying to build the project in VS2008 I get the above error. What is .sbr file ? and how can I fix the compile error? Any help is hugely appreciated.</p>
<p>An .sbr file is used to keep the "browse information" for symbol browsing within the projects. It's created at the same time as its source .cpp file gets complied. </p> <p>If VS cannot find an .sbr file, it means that the source .cpp was not compiled properly. Try to "rebuild" the project (rather than just "build" it), it may fix the error.</p>
<p>I'm new to c++ and I'm using Visual Studio 2008. I was trying to add a new class to a large program and got the same error (BK1506). </p> <p>The problem for me was that I had not implemented my class correctly using: </p> <pre><code>namespace ns { class Name { }; } </code></pre> <p>Although this most likely wasn't the reason for your error I would advise people to check this first as the previous answers got me thinking my problem was more advanced than it really was </p>
13,456
<p>I know there is a command line syntax for adding custom stacks to the OSX Leopard dock besides the "Downloads" which comes by default. What is it?</p>
<p><a href="http://code.google.com/p/dockutil/" rel="nofollow noreferrer">http://code.google.com/p/dockutil/</a></p>
<p>While this doesn't completely answer your question, <a href="http://www.tuaw.com/2008/09/16/terminal-tips-add-recent-applications-as-a-stack-on-dock/" rel="nofollow noreferrer">this page</a> has some info on how to add a "recent items" stack to the Dock. Maybe that will help you to figure out what the generic syntax for adding Stacks is?</p>
20,018
<p>I'm interested in making desktop widgets, similar to Apple's Dashboard or what Vista has. I'd like to make them cross-platform, if possible. Opera's widgets are cross-platform but require the user to have Opera installed, so that's a big limitation.</p> <p>I know most widgets are made with HTML/XML, CSS, and Javascript. Is there a way to create them using Python?</p> <hr> <p><strong>Update</strong>: I did find a site talking about <a href="http://advogato.org/article/981.html" rel="nofollow noreferrer">Pyjamas</a>. Does anyone have experience with it and, if so, what are its capabilities/limitations?</p>
<p>You should take a look at what the guys at <a href="http://www.digsby.com/" rel="nofollow noreferrer">Digsby</a> are doing. Basically, they've written a port of <a href="http://wxwebkit.wxcommunity.com/" rel="nofollow noreferrer">WebKit to wxWidgets</a>, and then use WebKit to render the interface, and wxPython for writing the rest of the app. Pretty neat, but <em>very</em> alpha at the moment.</p>
<p>You can check out <a href="http://www.pygtk.org/" rel="nofollow noreferrer">PyGTK</a>, which will allow you to create desktop widgets, but they won't be managed by OSX's Dashboard. If you'd like to <a href="http://developer.apple.com/macosx/dashboard.html" rel="nofollow noreferrer">develop an OSX widget</a>, you'll want to stick with HTML/CSS/JavaScript.</p>
18,021
<p>Long ago, I wrote a style 'normalizer' program to scan the ASP/HTML code of a big pile of classic ASP pages (most of which were originally generated from MS-Word documents, so naturally they were littered with superflous stylesheets and massive one-off styles). The style normalizer generated a minimal set of stylesheets and styles and a new 'sanitized' asp/html document, so that the sanitized document produced exactly the same rendered output as the original (verified with screenshot image comparisons).</p> <p>Every now and then, I run across a need for a program like this, and am toying with the idea of writing one for commercial release.</p> <p>My googling skills have not turned up anything exactly like this (HTML:Normalize Perl module and HTML Tidy project just seem to clean up tags).</p> <p>So, my questions are:</p> <ol> <li>is there such a tool already, commercial or otherwise?</li> <li>if not, does anybody really need it?</li> <li>if so, what features would make it truly worthwhile?</li> </ol> <p>re #3 for example, collecting a base stylesheet for a set of pages, or adjusting all pages to use a given base stylesheet; preserving classic asp commands, following #includes, preserving asp.net embedded scripts, et al. The more specific and numerous, the better.</p> <p>Example:<br> Old html w/embedded tags</p> <pre><code>&lt;html&gt;&lt;head&gt; &lt;title&gt;title&lt;/title&gt; &lt;style type='css/text'&gt; .cls1 { font-family: arial; font-size: 10px; font-weight: bold; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;% somefunction() %&gt; &lt;div class='cls1' style='font-size:10px;'&gt;test div&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>New html</p> <pre><code>&lt;html&gt;&lt;head&gt; &lt;title&gt;title&lt;/title&gt; &lt;style type='css/text'&gt; .cls1 { font-family: arial; font-size: 10px; font-weight: bold; } &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;% somefunction() %&gt; &lt;div class='cls1'&gt;test div&lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Note that the style on the div is gone, since it was redundant with the class cls1</p> <p>EDIT: removed the term 'sanitizer' since i'm not focused on XSS attacks or filtering input in comments, merely on consolidating a lot of ad-hoc styles and random CSS classes into a minimal coherent set of stylesheets.</p>
<p>Well, I can't say definitively that this "works" for everything described, but Tidy does a bit more than clean up tags.</p> <p>See the <a href="http://tidy.sourceforge.net/docs/quickref.html" rel="nofollow noreferrer">HTML Tidy Configuration Options</a>, especially those relating to Microsoft Word (like <a href="http://tidy.sourceforge.net/docs/quickref.html#word-2000" rel="nofollow noreferrer">word-2000</a>)</p>
<p>Don't forget beautiful soup</p> <p><a href="https://stackoverflow.com/questions/293482/how-do-i-fix-wrongly-nested-unclosed-html-tags">How do I fix wrongly nested / unclosed HTML tags?</a></p>
38,399
<p>The <code>System.Windows.Threading.DispatcherObject</code> class (which <code>DependencyObject</code> is based on) contains a useful function, called <code>CheckAccess()</code>, that determines whether or not the code is running on the UI thread.</p> <p>When I wanted to use it yesterday, I was puzzled to find out that Intellisense didn't show the function (nor <code>VerifyAccess()</code>, which throws an exception when not on the UI thread), even though the MSDN library lists it. I decided to investigate the class using Reflector. It seems that the function in question has an <code>EditorBrowsable(EditorBrowsableState.Never)</code> attribute attached to it. The <code>Dispatcher</code> class, which is used by <code>DispatcherObject</code>, has the same attribute attached to <code>CheckAccess()</code> and <code>VerifyAccess()</code>:</p> <pre><code>public abstract class DispatcherObject { // ... [EditorBrowsable(EditorBrowsableState.Never)] public bool CheckAccess(); [EditorBrowsable(EditorBrowsableState.Never)] public void VerifyAccess(); // ... [EditorBrowsable(EditorBrowsableState.Advanced)] public Dispatcher Dispatcher { get; } } public sealed class Dispatcher { // ... [EditorBrowsable(EditorBrowsableState.Never)] public bool CheckAccess(); [EditorBrowsable(EditorBrowsableState.Never)] public void VerifyAccess(); // ... } </code></pre> <p>I don't believe that the application of that attribute is random (or a joke), so my question is: why is it there? Should those methods not be called directly? Then why aren't they <code>protected</code> (or <code>internal</code>, like some of the most useful methods in the WPF)?</p>
<p>A Microsoft employee <a href="http://social.msdn.microsoft.com/Forums/en-US/wpf/thread/bd0e6f6c-cadd-48f1-8e1a-163c2f17e4ca/" rel="noreferrer">recently stated</a> CheckAccess is used only for "advanced scenarios", so they hid it from Intellisense.</p> <blockquote> <p>"CheckAccess and VerifyAccess have always been marked to be not visible, maybe IntelliSense wasn't respecting it. You can use Reflector to confirm. The idea here is that CheckAccess and VerifyAccess are advances scenarios, that normal developers don't need.</p> <p>However, I do think that EditorBrowsableState.Advanced would have been a more appropriate level."</p> </blockquote> <p>There's a Microsoft Connect case for this shortcoming. <a href="https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=367777" rel="noreferrer">Vote for it</a> if it's important to you.</p>
<p>I can't find any documentation that says you shouldn't use those methods directly, but I haven't looked very long.</p> <p>Also you refer to the EditorVisibleAttribute, which doesn't exist. According to Reflector it's the <a href="http://msdn.microsoft.com/en-us/library/system.componentmodel.editorbrowsableattribute.aspx" rel="nofollow noreferrer">EditorBrowsableAttribute</a>.</p> <p>Reflector disassembly:</p> <pre><code>[EditorBrowsable(EditorBrowsableState.Never)] public bool CheckAccess() { //CODE } </code></pre>
3,813
<p>In the following example should I expect that <code>values.size()</code> will be called every time around the loop? In which case it might make sense to introduce a temporary <code>vectorSize</code> variable. Or should a modern compiler be able to optimize the calls away by recognising that the vector size cannot change.</p> <pre><code>double sumVector(const std::vector&lt;double&gt;&amp; values) { double sum = 0.0; for (size_t ii = 0; ii &lt; values.size(); ++ii) { sum += values.at(ii); } } </code></pre> <p>Note that I don't care if there are more efficient methods to sum the contents of a vector, this question is just about the use of size() in a for construct.</p>
<p>Here's one way to do it that makes it explicit - size() is called only once.</p> <pre><code>for (size_t ii = 0, count = values.size(); ii &lt; count; ++ii) </code></pre> <p><strong>Edit:</strong> I've been asked to actually answer the question, so here's my best shot.</p> <p>A compiler generally won't optimize a function call, because it doesn't know if it will get a different return value from one call to the next. It also won't optimize if there are operations inside the loop that it can't predict the side effects of. Inline functions might make a difference, but nothing is guaranteed. Local variables are easier for the compiler to optimize.</p> <p>Some will call this premature optimization, and I agree that there are few cases where you will ever notice a speed difference. But if it doesn't make the code any harder to understand, why not just consider it a best practice and go with it? It certainly can't hurt.</p> <p>P.S. I wrote this before I read <a href="https://stackoverflow.com/questions/166641/is-using-size-for-the-2nd-expression-in-a-for-construct-always-bad#166654">Benoit's</a> answer carefully, I believe we're in complete agreement.</p>
<p>Most, maybe even all, standard implementations of size() will be inlined by the compiler to what would be the equivalent of a temporary or at most a pointer dereference.</p> <p>However, you can never be sure. Inlining is about as hidden as these things get, and 3rd party containers may have virtual function tables - which means you may not get inlined.</p> <p>However, seriously, using a temporary reduces readability slightly for almost certainly no gain. Only optimise to a temporary if profiling says it is fruitful. If you make these micro optimisations everywhere, your code could become unreadable, perhaps even for yourself.</p> <p>As a slight aside, no compiler would optimise size() to one of call assigning to a temporary. There is almost no guarantee of const in C++. The compiler cannot risk assuming size() will return the same value for the whole loop. For example. Another thread could change the vector in between loop iterations.</p>
20,129
<p>How do I actually run a file on localhost? I know it is working, but how do I run a file on it, and how do I verify that the file is in fact running on localhost?</p> <p><strong>Server newbie here, additional questions (I have xampp running Apache 2.2):</strong> From your responses it sounds like I have to type in the path in the browser in order to open the file on the localhost. So, if I want to have the file in a subdirectory, I would have to type the full path including the directory? </p> <p>Is there a way to have the browser point to the localhost while I am working on my html, instead of having to type in the path all the time?</p> <p>I am working in Dreamweaver CS3, and want to use <strong>include</strong> commands (either SSI or PHP), but not have to keep putting my files up on HostGator in order to see if they are working.</p> <p>What is the best way to do this (please be specific, I know nothing). If there is a detailed tutorial anywhere, really appreciate a link.</p> <p>Thank you</p>
<p>Ok, thanks for the more specific info, ppl may remove their downvotes now...</p> <p>What you are proposing is a very common thing to do! You want to run your web application locally without uploading it to your host yet. That's totally fine and that's what your Apache is there for. Your Apache is a web server meaning its main purpose is to serve HTML, PHP, ASP, etc. files. Some like PHP; it first sends to the interpreter and then sends the rendered file to the browser. All in all: it's just serving pages to your browser (the client). </p> <p>Your web server has a root directory which is wwwroot (IIS) or htdocs (apache, xampp) or something else like public_html, www or html, etc. It depends on your OS and web server.</p> <p>Now if you type <code>http://localhost</code> into your browser, your browser will be directed to this webroot and the server will serve any <code>index.html</code>, <code>index.php</code>, etc. it can find there (in a customizable order). </p> <p>If you have a project called "mytutorial" you can enter <code>http://localhost/mytutorial</code> and the server will show you the index-file of your tutorial, etc. If you look at the absolute path of this tutorial folder then it's just a subfolder of your webroot, which is itself located somewhere on your harddrive, but that doesn't matter for your localhost.</p> <p>So the relative path is</p> <pre><code>http://localhost/mytutorial </code></pre> <p>while the absolute path may be</p> <pre><code>c:/webservices/apache/www </code></pre> <p>or</p> <pre><code>c:/xampp/htdocs </code></pre> <p>If you're working with Dreamweaver you can simplify the testing process by setting up your local server as a testing server in your project settings. Try it! It's easy. Once it's done, you can just press the browser icon with any of your files and it will open on localhost.</p>
<p>Looking at your other question I assume you are trying to run a php or asp file or something on your webserver and this is your first attempt in webdesign.</p> <p>Once you have installed php correctly (which you probably did when you got XAMPP) just place whatever file you want under your localhost (/www/var/html perhaps?) and it should run. You can check this of course at localhost/file.php in your browser.</p>
40,325
<p>I need to loop through all the matches in say the following string:</p> <p><code>&lt;a href='/Product/Show/{ProductRowID}'&gt;{ProductName}&lt;/a&gt;</code></p> <p>I am looking to capture the values in the {} including them, so I want {ProductRowID} and {ProductName}</p> <p>Here is my code so far:</p> <pre><code>Dim r As Regex = New Regex("{\w*}", RegexOptions.IgnoreCase) Dim m As Match = r.Match("&lt;a href='/Product/Show/{ProductRowID}'&gt;{ProductName}&lt;/a&gt;") </code></pre> <p>Is my RegEx pattern correct? How do I loop through the matched values? I feel like this should be super easy but I have been stumped on this this morning!</p>
<p>Your Pattern is missing a small detail:</p> <pre><code>\{\w*?\} </code></pre> <p>Curly braces must be escaped, and you want the non-greedy star, or your first (and only) match will be this: <code>"{ProductRowID}'&gt;{ProductName}"</code>.</p> <pre><code>Dim r As Regex = New Regex("\{\w*?\}") Dim input As String = "&lt;a href='/Product/Show/{ProductRowID}'&gt;{ProductName}&lt;/a&gt;" Dim mc As MatchCollection = Regex.Matches(input, r) For Each m As Match In mc MsgBox.Show(m.ToString()) Next m </code></pre> <p><code>RegexOptions.IgnoreCase</code> is not needed, because this particular regex is not case sensitive anyway.</p>
<p>Change your RegEx pattern to <code>\{\w*\}</code> then it will match as you expect.</p> <p>You can test it with an <a href="http://www.dotnetcoders.com/web/Learning/Regex/RegexTester.aspx" rel="nofollow noreferrer">online .net RegEx tester</a>.</p>
42,228
<p>I'm using the RxTx library over usbserial on a Linux distro. The RxTx lib seems to behave quite differently (in a bad way) than how it works over serial.</p> <p>One of my biggest problems is that the <code>RxTx SerialPortEvent.OUTPUT_BUFFER_EMPTY</code> does not work on linux over usb serial.</p> <p>How do I know when I should write to the stream? Any indicators I might have missed?</p> <p>So far my experience with writing and reading concurrently have not been great. Does anyone know if I should lock the <code>DATA_AVAILABLE</code> handler from being invoked while I'm writing on the stream? Or <code>RxTx</code> accepts concurrent read/writes?</p>
<p><em>(perhaps slightly off-topic, but here goes)</em></p> <p>I'm not familiar with that particular library, but I can assure you from dire experience (I work in the security systems (as in: hardware security devices) business, where RS-232 is heavily used) that not all USB-serial converters are born equal. Many such devices so not properly emulate all RS-232 lines, and many don't even handle any comms without flow control. Before blaming the library, try to confirm that the hardware actually does what it's supposed to do.</p> <p>Without wanting to endorse a particular product or brand, the best (as in: least buggy) USB-serial converter I have come across in years is the <a href="http://www.tripplite.com/en/products/model.cfm?txtModelID=3914" rel="nofollow noreferrer">USA-19HS</a>.</p>
<p>Using RxTx over usb-to-serial you can't set notifyOnOutput to true otherwise it locks up completely. </p> <p>I've learned this the hard way. This problem is documented on a few web sites over the internet.</p> <p>I'm running it on Linux and I believe that this is a Linux only issue, although I can't confirm that.</p> <p>As for the link you've given me... I've seen the SimpleReader and SimpleWriter examples, but these don't represent a real world application. It is not multi-threaded, assumes a read has the full data it needs instead of buffering reads, etc.</p> <p>Thanks,</p> <p>Jeach!</p>
11,038
<p>My Web Application is split up in a WebGui and an WebService. The WebService is responsible for Business Logic and Database handling. From Javascript in the Browser I request data depending on a date and time that is an input from the Browser. This request gous to an .asmx Url in the WebGui and inside this function the webservice is called.</p> <p>On my development system (windows xp) I get the right data, but when I install it on the test system I have to add the local time zone difference to get the right data.</p> <p>For example I want the data for the date and time '21.07.2008 14:27:30' I have to send '21.07.2008 16:27:30'.</p> <p>Why is the behaviour on the two systems different and what should I do to get on both systems the same behaviour?</p> <ul> <li>Web GUI is in asp.net 2.0 c# </li> <li>Web Service is in asp.net 1.1 c#</li> </ul> <p><strong>Update</strong></p> <p>This is no Problem of interpreting the date in different formats as the date and time is sent in the JSON Protocol as "/Date(1221738803000)/". It is a problem of interpreting/forgetting the time zone.</p>
<p>I would suspect this has to do with the DateTime.Kind property introduced in .NET 2.0. By default this is set to DateTimeKind.Unspecified, which is most of the time handled the same as DateTimeKind.Local, so when the date is serialized it will be converted to UTC. You could try to set the Kind to DateTimeKind.Utc using DateTime.SpecifyKind(...) before passing it to the web service call.</p>
<p>Depending on the culture settings of the server the date will be interpreted differently. I.e. given the date: 01.05.2008 a culture of en-GB (British) will read the date as First of May, a system with the culture en-US will read it as 5th of January. </p> <p>To get around this you should ensure that dates are always transmitted in UTC format (yyyy-mm-dd) which will always be interpreted in that manner regardless of culture.</p>
11,795
<p>A customer of ours has Quickbooks 2005 and is looking to have their web data (orders, customers, tax) sent as it is collected from the web in a format that can be imported into Quickbooks 2005 Pro. </p> <p>Does anyone have any experience with this? If so, what was your experience, and what component/method would you recommend for importing this data into Quickbooks?</p>
<p>I wrote the plugin mentioned by Till. The plugin is an implementation of the <a href="http://cometdproject.dojotoolkit.org/documentation/bayeux" rel="noreferrer">Bayeux</a> protocol and currently supports long-polling (local server via AJAX) and callback-polling (remote server via XSS). There is a <a href="http://cometdproject.dojotoolkit.org/documentation/bayeux" rel="noreferrer">Bayeux</a> implementation for Python called cometd-twisted that I have heard my plugin works with, but I have not verified this. I have tested and verified it works with <a href="http://cometdproject.dojotoolkit.org/documentation/cometd-jetty" rel="noreferrer">cometd-jetty</a> and <a href="http://code.google.com/p/erlycomet/" rel="noreferrer">erlycomet</a> which has a jQuery Comet example included. There is more info on my <a href="http://morglog.org" rel="noreferrer">blog</a> and the current code with a basic chat example can be found on its <a href="http://code.google.com/p/jquerycomet/" rel="noreferrer">google code page</a>. Hope this info is helpful and feel free to contact me if need any further help with the plugin.</p>
<p>Comet is a great solution, and there are all kinds of implementations. Which one depends on your needs.</p> <p>We've implemented a solution for IIS/ASP.NET, <a href="http://www.frozenmountain.com/websync" rel="nofollow noreferrer">WebSync</a>. It includes the javascript client, which plays nicely with jQuery. Technically, since it's the Bayeux protocol, any Bayeux client should work just dandy. The same protocol can also be found in the dojo library.</p> <p>For more detail, you can see the spec for <a href="http://svn.cometd.com/trunk/bayeux/bayeux.html" rel="nofollow noreferrer">the Bayeux protocol</a>.</p>
16,465
<p>On Internet Explorer, the standard HTML file upload form also allows for direct input of the file name (instead of using the file selector dialog). This makes it possible to enter non-existing files. On other browsers (which do not let you do that) I suppose this case can still occur if you delete the file after having selected it.</p> <p>In order to deal with bugs arising from this problem (like <a href="http://dev.fckeditor.net/ticket/2716" rel="nofollow noreferrer">this one</a>), I need to add some validation code on the server-side (which is only possible if the request actually goes to the server, of which I am not sure at this point), or on the client-side (which cannot be very straightforward, as you cannot access the actual file from the JavaScript sandbox). Other than that, the only (and possibly best) option seems to be to hide the input box with CSS magic, like GMail does for attachment files.</p> <p>So, what happens when you try to upload a non-existing file? Is there still a POST request being sent? Or will the browser abort, and if it does, how can I detect that?</p>
<p>I think I figured it out.</p> <p>First of all, it seems to make a difference whether it is just the file that does not exist, or the whole path is incorrect. If only the file is missing, apparently a POST does take place.</p> <p>At least in the case I mentioned (FCKEditor's image upload dialog on WinXP and IE6), the browser does not submit the form at all (so that there is nothing that can be done server-side).</p> <p>It is possible to detect the problem on the client, by not using the normal form submit, but by having an onSubmit handler that stops the submit (returns false) and instead submits the form itself using form.submit(). If the file is missing, there will be an exception.</p> <pre><code>try{ form.submit(); } catch (e){ // show some error message } return false; </code></pre>
<p>Really good question, in .net there is Request.IsClientConnected, but don't know if that will work for you in this case, or if you are even using .net in the first place. </p> <p>I would try running it through Fiddler on the client end and WireShark at the server end, and see if you get any insights by looking at the traffic patterns. You may then be able to work out how to detect this.</p> <p>Interested to see what you come up with. Sorry can't give a better answer.</p>
46,697
<p>I use VB6 for an application.</p> <p>Is it possible to force the compiler to inline a function?</p> <p>Or is there an add-in that achieves the same thing?</p> <p>There's a secure part of my code that I want to make difficult to hack, by repeating the code at every point where it is used instead of being listed once as a function.</p> <p>Hope someone can answer my question!</p>
<p>IMO if this is what you're doing as a security measure, you have bigger problems than getting VB to inline your function. And I don't think there is any provision in VB6 to do this. AND I tend to think that this technique would make it easier to hack your code, since you'd see the same really important function repeated over and over again... Sorry :-(</p>
<p>As Dave said there is no support for that in the VB compiler. </p> <p>If you really want to this why not run a search &amp; replace on a copy of your code and build that copy. Doing that on the command line shouldn't be too difficult.</p>
45,067
<p>Are there any known hash algorithms which input a vector of int's and output a single int that work similarly to an inner product?</p> <p>In other words, I am thinking about a hash algorithm that might look like this in C++:</p> <pre><code>// For simplicity, I'm not worrying about overflow, and assuming |v| &lt; 7. int HashVector(const vector&lt;int&gt;&amp; v) { const int N = kSomethingBig; const int w[] = {234, 739, 934, 23, 828, 194}; // Carefully chosen constants. int result = 0; for (int i = 0; i &lt; v.size(); ++i) result = (result + w[i] * v[i]) % N; return result; } </code></pre> <p>I'm interested in this because I'm writing up a paper on an algorithm that would benefit from any previous work on similar hashes. In particular, it would be great if there is anything known about the collision properties of a hash algorithm like this.</p> <p>The algorithm I'm interested in would hash integer vectors, but something for float vectors would also be cool.</p> <p><strong>Clarification</strong></p> <p>The hash is intended for use in a hash table for fast key/value lookups. There is no security concern here.</p> <p>The desired answer is something like a set of constants that provably work particularly well for a hash like this - analogous to a multiplier and modulo which works better than others as a pseudorandom number generator.</p> <p>For example, some choices of constants for a linear congruential pseudorandom generator are known to give optimal cycle lengths and have easy-to-compute modulos. Maybe someone has done research to show that a certain set of multiplicative constants, along with a modulo constant, in a vector hash can reduce the chance of collisions amongst nearby integer vectors.</p>
<p>I did some (unpublished, practical) experiments with testing a variety of string hash algorithms. (It turns out that Java's default hash function for Strings sucks.) </p> <p>The easy experiment is to hash the English dictionary and compare how many collisions you have on algorithm A vs algorithm B.</p> <p>You can construct a similar experiment: randomly generate $BIG_NUMBER of possible vectors of length 7 or less. Hash them on algorithm A, hash them on algorithm B, then compare number and severity of collisions.</p> <p>After you're able to do that, you can use simulated annealing or similar techniques to find "magic numbers" which perform well for you. In my work, for given vocabularies of interest and a tightly limited hash size, we were able to make a generic algorithm work well for several human languages by varying the "magic numbers".</p>
<p>While i might be totally misunderstanding you, maybe it's a good idea to treat a vector as a byte stream and do some know hash on it, i.e. <a href="http://en.wikipedia.org/wiki/SHA1" rel="nofollow noreferrer" title="SHA1">SHA1</a> or <a href="http://en.wikipedia.org/wiki/MD5" rel="nofollow noreferrer" title="MD5">MD5</a>.</p> <p>Just to clarify, those hashes are known to have good hash properties, and i believe there's no reason to reinvent a bicycle and to implement new hash. Another possibility is to use known CRC angorithm.</p>
35,881
<p>I can not figure out what all the parameters to the arc() function are (by experimentation) and I have not found any tutorial that seems to explain them. Where would a good explanation of the arc() function be?</p>
<pre><code>arc(x, y, radius, startAngle, endAngle, anticlockwise) </code></pre> <p>The first three parameters, x and y and radius, describe a circle, the arc drawn will be part of that circle. startAngle and endAngle are where along the circle to start and stop drawing. 0 is east, Math.PI/2 is south, Math.PI is west, and Math.PI*3/2 is north. If anticlockwise is 1 then the direction of the arc is reversed.</p> <p><a href="https://developer.mozilla.org/En/Canvas_tutorial/Drawing_shapes#Arcs" rel="noreferrer">https://developer.mozilla.org/En/Canvas_tutorial/Drawing_shapes#Arcs</a></p> <p><img src="https://i.stack.imgur.com/1qF8E.jpg" alt="Clockwise"></p> <p><img src="https://i.stack.imgur.com/LqtRU.jpg" alt="AntiClockwise"></p> <p>In the attached diagrams, the only difference is the anticlockwise param. Math.PI/2 always ends south when clockwise or anticlockwise</p>
<p>Check this simple example for a brief introduction to canvas and arc function of HTML5: <a href="http://pastebin.com/kxB7uJLD" rel="nofollow">http://pastebin.com/kxB7uJLD</a></p> <p>So long.</p>
41,276
<p>Do I have to restart IIS if I drop a new DLL in the bin of my virtual directory?</p>
<p>No you do not have to, the application will recycle, but an IISReset is NOT needed</p>
<p>If your application is an ASP.NET app, I believe the AppDomain will restart, but the worker process (w3wp.exe) will NOT. For most purposes, an AppDomain reset is sufficient to clear the state but for some (generally to do with unmanaged DLLs having been loaded in the process) this may not be sufficient. In these cases, IISRESET will work.</p>
15,010
<p>I am trying to draw a domain model or class diagram in UML for car dealership. I am stuck with how to present test drive in the model. One way is to have appointment class and then test-drive as sub class. A dealer also offers after-sale vehicle service so i could have appointment/booking class as super class and then vehicle service and test-drive as two sub classes.</p> <p>Another way is to have the customer class have a direct relationship with test drive class and vehicle service class under appointment class.</p> <p>A dealer also sells new and used cars and their parts.</p> <p>A dealer also offers finance for car sale.</p> <p>Would testdrive class have relationship with vehicle class or there is separate class for display and testdrive class?</p> <p>Another question is how do I show potential customers and their inquiries about sale and service in the model. A dealer wants to save details of potential customers if they allow for marketing purposes. Shall I have two classes: one for customers and one for potential customers or it can be achieved just by using an attribute in customer class?</p>
<p>You can really only distinguish the right decision by having a good set of use cases or expected behaviors of the model.</p> <p>This will inform whether a particular sub-classing is really accurate.</p> <p>I can see that an appointment might contain several test-drives, which are themselves linked to individual vehicles, So a test-drive itself is nothing more than a link from a customer to a vehicle which are linked to an appointment.</p>
<p>test-drive would contain the information relevant only to the test-drive:</p> <p>reference to the customer - even this might be debatable to include</p> <p>reference to the vehicle</p> <p>length of test drive</p> <p>location (perhaps the vehicle was driven at a different location than could be determined from the owning appointment)</p> <p>customer temperature (hot or cold - i.e. did the customer seem enthusiastic)</p> <p>comments</p> <p>etc.</p> <p>But what is not in the test-drive object is anything related to the appointment - since it is always contained in a collection - possibly as part of an appointment or some other event container. Now if the containers which can contain test-drives always include customer information, I might not even include the customer reference in the test-drive object - after all, it will be redundant.</p> <p>It depends if test-drives can occur in non-appointment scenarios - perhaps at a "sales event" or an "open house" or something where appointments are not actually created in the use cases - or if test-drives for multiple customers will occur within a container.</p>
26,517
<p>Is there a free or open source library to read Excel files (.xls) directly from a C# program? </p> <p>It does not need to be too fancy, just to select a worksheet and read the data as strings. So far, I've been using Export to Unicode text function of Excel, and parsing the resulting (tab-delimited) file, but I'd like to eliminate the manual step.</p>
<pre><code>var fileName = string.Format("{0}\\fileNameHere", Directory.GetCurrentDirectory()); var connectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName); var adapter = new OleDbDataAdapter("SELECT * FROM [workSheetNameHere$]", connectionString); var ds = new DataSet(); adapter.Fill(ds, "anyNameHere"); DataTable data = ds.Tables["anyNameHere"]; </code></pre> <p>This is what I usually use. It is a little different because I usually stick a AsEnumerable() at the edit of the tables: </p> <pre><code>var data = ds.Tables["anyNameHere"].AsEnumerable(); </code></pre> <p>as this lets me use LINQ to search and build structs from the fields.</p> <pre><code>var query = data.Where(x =&gt; x.Field&lt;string&gt;("phoneNumber") != string.Empty).Select(x =&gt; new MyContact { firstName= x.Field&lt;string&gt;("First Name"), lastName = x.Field&lt;string&gt;("Last Name"), phoneNumber =x.Field&lt;string&gt;("Phone Number"), }); </code></pre>
<p>I just used <a href="http://code.google.com/p/excellibrary/" rel="nofollow noreferrer">ExcelLibrary</a> to load an .xls spreadsheet into a DataSet. Worked great for me.</p>
3,664
<p>How can my app get a list of the True Type Fonts that are available on Linux. </p> <p>Is there a standard directory where they are stored across different distributions? Or some other standard way to locate them?</p>
<p>I think fontconfig is the right way to do it. Take a look on the <a href="http://en.wikipedia.org/wiki/Fontconfig" rel="noreferrer">wikipedia article</a> or the <a href="http://fontconfig.org" rel="noreferrer">fontconfig hompage</a>.</p>
<p>If you aren't writing proprietary software, or any other licensed software that's incompatible with GPL, you could try looking at the code to xlsfonts to see how to query the font server. (The font server could be X itself, but it won't matter.)</p>
24,867
<p>I've discovered that cElementTree is about 30 times faster than <code>xml.dom.minidom</code> and I'm rewriting my XML encoding/decoding code. However, I need to output XML that contains CDATA sections and there doesn't seem to be a way to do that with ElementTree.</p> <p>Can it be done?</p>
<p>After a bit of work, I found the answer myself. Looking at the ElementTree.py source code, I found there was special handling of XML comments and preprocessing instructions. What they do is create a factory function for the special element type that uses a special (non-string) tag value to differentiate it from regular elements.</p> <pre><code>def Comment(text=None): element = Element(Comment) element.text = text return element </code></pre> <p>Then in the <code>_write</code> function of ElementTree that actually outputs the XML, there's a special case handling for comments:</p> <pre><code>if tag is Comment: file.write("&lt;!-- %s --&gt;" % _escape_cdata(node.text, encoding)) </code></pre> <p>In order to support CDATA sections, I create a factory function called <code>CDATA</code>, extended the ElementTree class and changed the <code>_write</code> function to handle the CDATA elements.</p> <p>This still doesn't help if you want to parse an XML with CDATA sections and then output it again with the CDATA sections, but it at least allows you to create XMLs with CDATA sections programmatically, which is what I needed to do.</p> <p>The implementation seems to work with both ElementTree and cElementTree.</p> <pre><code>import elementtree.ElementTree as etree #~ import cElementTree as etree def CDATA(text=None): element = etree.Element(CDATA) element.text = text return element class ElementTreeCDATA(etree.ElementTree): def _write(self, file, node, encoding, namespaces): if node.tag is CDATA: text = node.text.encode(encoding) file.write("\n&lt;![CDATA[%s]]&gt;\n" % text) else: etree.ElementTree._write(self, file, node, encoding, namespaces) if __name__ == "__main__": import sys text = """ &lt;?xml version='1.0' encoding='utf-8'?&gt; &lt;text&gt; This is just some sample text. &lt;/text&gt; """ e = etree.Element("data") cdata = CDATA(text) e.append(cdata) et = ElementTreeCDATA(e) et.write(sys.stdout, "utf-8") </code></pre>
<p>Here's my version which is based on both gooli's and amaury's answers above. It works for both ElementTree 1.2.6 and 1.3.0, which use very different methods of doing this.</p> <p>Note that gooli's does not work with 1.3.0, which seems to be the current standard in Python 2.7.x.</p> <p>Also note that this version does not use the CDATA() method gooli used either.</p> <pre><code>import xml.etree.cElementTree as ET class ElementTreeCDATA(ET.ElementTree): """Subclass of ElementTree which handles CDATA blocks reasonably""" def _write(self, file, node, encoding, namespaces): """This method is for ElementTree &lt;= 1.2.6""" if node.tag == '![CDATA[': text = node.text.encode(encoding) file.write("\n&lt;![CDATA[%s]]&gt;\n" % text) else: ET.ElementTree._write(self, file, node, encoding, namespaces) def _serialize_xml(write, elem, qnames, namespaces): """This method is for ElementTree &gt;= 1.3.0""" if elem.tag == '![CDATA[': write("\n&lt;![CDATA[%s]]&gt;\n" % elem.text) else: ET._serialize_xml(write, elem, qnames, namespaces) </code></pre>
21,088
<p>I'm tired of using: </p> <pre><code>tail -f development.log </code></pre> <p>To keep track of my rails logs. Instead I would like something that displays the info in a grid and allows my to sort, filter and look at stack traces per log message.</p> <p>Does anyone know of a GUI tool for displaying rails logs. Ideally I would like a standalone app (not something in Netbeans or Eclipse) </p>
<p>FWIW I started <a href="http://github.com/SamSaffron/logviewer/tree/master" rel="nofollow noreferrer">this project</a> at GitHub to try and solve this problem, its far from functional.</p>
<p>You might be able to use <a href="http://logging.apache.org/chainsaw/index.html" rel="nofollow noreferrer">http://logging.apache.org/chainsaw/index.html</a> . Haven't used it in a long time but I think its log parser should be configurable</p>
15,118
<p>I'm trying to install RSpec as a gem after having it installed as a plugin. I've gone ahead and followed the directions found here <a href="http://github.com/dchelimsky/rspec-rails/wikis" rel="noreferrer">http://github.com/dchelimsky/rspec-rails/wikis</a> for the section titled <strong>rspec and rspec-rails gems</strong>. When I run <code>ruby script/generate rspec</code>, I get the error <code>Couldn't find 'rspec' generator</code>. Do only the plugins work? If so, why do they even offer the gems for rspec and rspec-rails? I'm running a frozen copy of Rails 2.1.2, and the version of rpsec and rspec-rails I'm using is the newest for today (Nov 7, 2008) 1.1.11.</p> <p>EDIT Nov 12, 2008 I have both the rspec and rspec-rails gems installed. I've unpacked the gems into the vender/gems folder. Both are version 1.1.11.</p>
<p>Have you installed both rspec and rspec-rails gems?</p> <pre><code>script/generate rspec </code></pre> <p>requires rspec-rails gem to be installed.</p>
<p>You'll need to do</p> <pre><code>sudo gem install cucumber-rails </code></pre>
34,366
<p>I have the following arrays in PHP (okay they are a bit bigger but the idea is what counts).</p> <pre><code>$array1 = array(1 =&gt; 'a', 2 =&gt; 'b'); $array2 = array(3 =&gt; 'c', 4 =&gt; 'd'); </code></pre> <p>Essentially I want to combine the two arrays as if it were something like this</p> <pre><code>$array3 = array(1 =&gt; 'a', 2 =&gt; 'b', 3 =&gt; 'c', 4 =&gt; 'd'); </code></pre> <p>Thanks</p>
<p>Use</p> <pre><code>$array3 = $array1 + $array2; </code></pre> <p>See <a href="http://de3.php.net/manual/en/language.operators.array.php" rel="nofollow noreferrer">Array Operators</a></p> <p>By the way: <a href="http://de3.php.net/array_merge" rel="nofollow noreferrer">array_merge()</a> does something different with the arrays given in the example:</p> <pre><code>$a1=array(1 =&gt; 'a', 2 =&gt; 'b'); $a2=array(3 =&gt; 'c', 4 =&gt; 'd'); print_r($a1+$a2); Array ( [1] =&gt; a [2] =&gt; b [3] =&gt; c [4] =&gt; d ) print_r(array_merge($a1, $a2)); Array ( [0] =&gt; a [1] =&gt; b [2] =&gt; c [3] =&gt; d ) </code></pre> <p>Note the different indexing.</p>
<p>array_merge only keeps STRING keys. You have to wrote your function for doing this</p>
26,843
<p>It just happens to me about one code design question. Say, I have one "template" method that invokes some functions that may "alter". A intuitive design is to follow "Template Design Pattern". Define the altering functions to be "virtual" functions to be overridden in subclasses. Or, I can just use delegate functions without "virtual". The delegate functions is injected so that they can be customized too. </p> <p>Originally, I thought the second "delegate" way would be faster than "virtual" way, but some coding snippet proves it is not correct.</p> <p>In below code, the first DoSomething method follows "template pattern". It calls on the virtual method IsTokenChar. The second DoSomthing method doesn't depend on virtual function. Instead, it has a pass-in delegate. In my computer, the first DoSomthing is always faster than the second. The result is like 1645:1780.</p> <p>"Virtual invocation" is dynamic binding and should be more time-costing than direct delegation invocation, right? but the result shows it is not.</p> <p>Anybody can explain this? </p> <pre><code>using System; using System.Diagnostics; class Foo { public virtual bool IsTokenChar(string word) { return String.IsNullOrEmpty(word); } // this is a template method public int DoSomething(string word) { int trueCount = 0; for (int i = 0; i &lt; repeat; ++i) { if (IsTokenChar(word)) { ++trueCount; } } return trueCount; } public int DoSomething(Predicate&lt;string&gt; predicator, string word) { int trueCount = 0; for (int i = 0; i &lt; repeat; ++i) { if (predicator(word)) { ++trueCount; } } return trueCount; } private int repeat = 200000000; } class Program { static void Main(string[] args) { Foo f = new Foo(); { Stopwatch sw = Stopwatch.StartNew(); f.DoSomething(null); sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); } { Stopwatch sw = Stopwatch.StartNew(); f.DoSomething(str =&gt; String.IsNullOrEmpty(str), null); sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); } } } </code></pre>
<p>Think about what's required in each case:</p> <p><strong>Virtual call</strong><br/></p> <ul> <li>Check for nullity</li> <li>Navigate from object pointer to type pointer</li> <li>Look up method address in instruction table</li> <li>(Not sure - even Richter doesn't cover this) Go to base type if method isn't overridden? Recurse until we find the right method address. (I don't think so - see edit at bottom.)</li> <li>Push original object pointer onto stack ("this")</li> <li>Call method</li> </ul> <p><strong>Delegate call</strong><br /></p> <ul> <li>Check for nullity</li> <li>Navigate from object pointer to array of invocations (all delegates are potentially multicast)</li> <li>Loop over array, and for each invocation: <ul> <li>Fetch method address</li> <li>Work out whether or not to pass the target as first argument</li> <li>Push arguments onto stack (may have been done already - not sure)</li> <li>Optionally (depending on whether the invocation is open or closed) push the invocation target onto the stack</li> <li>Call method</li> </ul></li> </ul> <p>There may be some optimisation so that there's no looping involved in the single-call case, but even so that will take a very quick check.</p> <p>But basically there's just as much indirection involved with a delegate. Given the bit I'm unsure of in the virtual method call, it's possible that a call to an unoverridden virtual method in a massively deep type hierarchy would be slower... I'll give it a try and edit with the answer.</p> <p>EDIT: I've tried playing around with both the depth of inheritance hierarchy (up to 20 levels), the point of "most derived overriding" and the declared variable type - and none of them seems to make a difference.</p> <p>EDIT: I've just tried the original program using an interface (which is passed in) - that ends up having about the same performance as the delegate.</p>
<p>virtual overrides have some sort of redirection table or something which is hardcoded and fully optimized at compile time. It's set in stone, very fast.</p> <p>Delegates are dynamic which will always have an overhead and they seem to be objects too so that adds up.</p> <p>You shouldn't worry about these small performance differences (unless developing performance critical software for the military), for most purposes good code structure wins over optimization.</p>
26,553
<p>I searched and found <a href="https://stackoverflow.com/questions/233441/svn-how-do-i-maintain-my-local-configblah-file">this question</a> but did not like the answer.</p> <p>Is there another way to get SVN to ignore config files that are checked in in-place (that you cannot check-in changed), but must be modified on your system.</p> <p>This is a pretty severe failure of SVN, my first disappointment with the system actually. What I'm hoping for is that someone out there figured out a trick, perhaps with branching just the config files onto a new branch while leaving everything else pointing at the original branch. Perhaps modifying the .svn directory?</p> <p>There must be a better solution then template/copy, that seems so unmaintainable.</p>
<p>After messing around for a few hours I think I have an answer. Since it's my own question, I guess I'll make it community wiki...</p> <p>I created a branch of the entire repository and pointed the "Config" type files at the new branch, then checked them in.</p> <p>I'm not sure how this will play out, but it made the "Check everything in" stuff work correctly. I think if I change one of those files it'll work fine, checking it into my local repository.</p> <p>The only thing that could be annoying is if someone else changes a file that I have branched, I'm not sure how I'll identify the fact that I'm supposed to merge.</p>
<p>After messing around for a few hours I think I have an answer. Since it's my own question, I guess I'll make it community wiki...</p> <p>I created a branch of the entire repository and pointed the "Config" type files at the new branch, then checked them in.</p> <p>I'm not sure how this will play out, but it made the "Check everything in" stuff work correctly. I think if I change one of those files it'll work fine, checking it into my local repository.</p> <p>The only thing that could be annoying is if someone else changes a file that I have branched, I'm not sure how I'll identify the fact that I'm supposed to merge.</p>
38,414
<p>I would like to control options on the debugger without using the debugging GUI's, preferably from inside the code being debugged. I would think that would be quite difficult, but maybe my debugged code can request a service from independent code that will communicate with the debugger.</p> <p>This relates to <a href="https://stackoverflow.com/questions/201182/debugging-with-exceptions-how-to-work-around-break-when-thrown#201197">another question of mine</a> on controlling when to break on exceptions.</p>
<p>You can write Visual Studio macros that can do anything the GUI can, but they can get rather involved. See the MSDN documentation on <a href="http://msdn.microsoft.com/en-us/library/xc52cke4(VS.80).aspx" rel="nofollow noreferrer">Automation and Extensibility for Visual Studio</a></p> <p>Doing this from the code being debugged would be tricky, you would definitely need some new form of communication with VS, maybe a custom add-in. I don't think an independent service would fundamentally help here. The biggest problem is that your code will stop running when the debugger breaks.</p>
<p>I know that you can do it with WinDBG and OutputDebugString, but for Visual Studio, I think you have to spool off another process, pipe commands to that, and have that manipulate the Debugger API.</p>
24,604
<p>Both ideas sound very similar to me, but there might be subtle differences or the exact same thing, explained in different ways. What is the relationship between TDD and Test First Development/Programming?</p>
<p>There's a difference in terms of what the driving factor is.</p> <p>Do you have a vague idea of what the class (or system - this can happen at different scales, of course) should look like, then think up tests which give it the actual shape? That's TDD.</p> <p>Do you know exactly what the public API of the class should be, and just write the tests before the implementation? That's test-first development.</p> <p>My style tends to be a mixture of the two. Sometimes it's obvious what the API should be before writing any tests - in other cases testability really drives the design.</p> <p>To put it another way, TDD starts with "What questions do I want to ask?" whereas non-TDD (whether test first or not) starts with "What answer do I want to give?"</p>
<p>They are exactly the same thing. Both reference writing tests first, then writing the code that will pass the test</p>
43,414
<p>I've been searching for a library that can render organisation charts in either flash and/or javascript(preferably jQuery). I know of several javascript and/or flash chart libraries but none of them seem to be able to render an organisation chart such as this: <a href="http://www.fsai.ie/images/org_chart.gif" rel="nofollow noreferrer">http://www.fsai.ie/images/org_chart.gif</a></p>
<p><a href="http://www.adobe.com/products/flex/ilogelixir/" rel="nofollow noreferrer">iLog Elixir</a> seems to have what you're looking for, in Flash/Flex. It's a commercial product and quite expensive, though. I Also found <a href="http://blogs.ilog.com/elixir/category/ilog-elixir/org-chart/" rel="nofollow noreferrer">these blog posts</a> (apparently by people from their dev team) where you can see a bit of how org charts are implemented in their product.</p>
<p>have you considered just embedding something like gliffy? it has it's own versioning and editing. Do you need to just render something already created or enable visio creation?</p>
24,008
<p>How do I forcefully unload a <code>ByteArray</code> from memory using ActionScript 3?</p> <p>I have tried the following:</p> <pre><code>// First non-working solution byteArray.length = 0; byteArray = new ByteArray(); // Second non-working solution for ( var i:int=0; i &lt; byteArray.length; i++ ) { byteArray[i] = null; } </code></pre>
<p>(I'm not positive about this, but...)</p> <p>AS3 uses a non-deterministic garbage collection which means that dereferenced memory will be freed up whenever the runtime feels like it (typically not unless there's a reason to run, since it's an expensive operation to execute). This is the same approach used by most modern garbage collecting languages (like C# and Java as well).</p> <p>Assuming there are no other references to the memory pointed to by <code>byteArray</code> or the items within the array itself, the memory will be freed at some point after you exit the scope where <code>byteArray</code> is declared.</p> <p>You can force a garbage collection, though you really shouldn't. If you do, do it only for testing. If you do it in production, you'll hurt performance much more than help it.</p> <p>To force a GC, try (yes, twice):</p> <pre><code>flash.system.System.gc(); flash.system.System.gc(); </code></pre> <p><a href="http://www.craftymind.com/2008/04/09/kick-starting-the-garbage-collector-in-actionscript-3-with-air/" rel="nofollow noreferrer">You can read more here</a>.</p>
<p>Use <code>bytearray.clear()</code></p> <p>As per the <a href="https://airsdk.dev/reference/actionscript/3.0/" rel="nofollow noreferrer">Language Reference</a></p> <p>this</p> <blockquote> <p>Clears the contents of the byte array and resets the length and position properties to 0. Calling this method explicitly frees up the memory used by the ByteArray instance.</p> </blockquote>
2,241
<p>I'm using <a href="http://www.khronos.org/opengles/" rel="nofollow noreferrer">OpenGL ES</a> on a <a href="http://www.apple.com/iphone/" rel="nofollow noreferrer">low-resolution, embedded device</a>.</p> <p>I've applied a vertical color gradient, using vertex coloring, to a large polygon serving as a backdrop to my rendered scene. I can see clear visible banding artifacts in the color gradient.</p> <p>My main experience is using software renderers. With software renderers it is common to dither away <a href="http://en.wikipedia.org/wiki/Mach_band" rel="nofollow noreferrer">mach bands</a> and other banding artifacts. We often do this during the quantization step of rendering a frame, where the floating point, high-precision representations of colors are transformed to a lower-precision output (usually with integer components). We achieve dithering by randomly rounding the final integer component either up or down, to insert just the tiniest bit of noise in the image with which to fool the eye into seeing a continuos and smooth blend between colors.</p> <p>My question is whether I can achieve this using OpenGL ES? Is this kind of dithering part of the OpenGL pipeline, or should I skip vertex-coloring and render the gradient to a texture and apply a bit of noise to it?</p>
<p>Have you tried glEnable(GL_DITHER)? It's normally initially enabled, but I've never worked with GL ES or on an embedded device. It may also depend on the color depth you're using in the frame buffer, you're going to get artifacts if you've only got 4 bits per channel.</p>
<p>I have never heard of the effect you describe being in the OGL pipe. My knowledge is a bit dated at this point, though, so I may be wrong. I'd give the render to texture a shot if you can.</p>
24,187
<p>I am trying to implement ajax back/forward button support and therefore writing variables after a # in my url. I would also like the user to be able to copy the url and then link back to it. Does anyone know how can I parse the url and grab my "querystrings" even though they are behind a #?</p>
<p>The value after the hash is not transmitted to the server. There's another SO question about that somewhere, but I'm having trouble finding it. Likewise it's taken me a while to find a decent reference to cite, but <a href="http://en.wikipedia.org/wiki/Fragment_identifier" rel="nofollow noreferrer">this Wikipedia article</a> has some confirmation:</p> <blockquote> <p>The fragment identifier functions differently than the rest of the URI: namely, its processing is exclusively client-side with no participation from the server. When an agent (such as a Web browser) requests a resource from a Web server, the agent sends the URI to the server, but does not send the fragment.</p> </blockquote> <p>I assume you want to respond to it on the server side rather than the browser side? (Given that you're asking about doing it in C#...)</p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.uri.fragment.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/system.uri.fragment.aspx</a></p>
44,310
<p>I'm working on a site which is at the core/ master of a number of sites. We are also responsible for handling the authentication across all the sites under the brand banner.</p> <p>The client has wanted a single-sign-on operation to be included, so if I was to sign into any of the sites I would be signed into all the sites. We're handling the <em>child</em> site sign-ins by redirecting to the main site (ours) and executing the login.</p> <p>It was decided that the SSO would operate via embedding image tags into the page and then calling a page on each child site. This would open a client session to their site so they can set cookies/ do what they want to handle a login.</p> <p>This works <em>for the most part</em>, it's been tested on IE7, FF 2 &amp; 3 and they all work. The problem browser at the moment is Safari (and Chrome). Although the images do appear to load in the client session doesn't seem to be opened, we get no cookies from the child sites set. The problem seems to be WebKit based browsers with Safari and Chrome being the problem (I'd presume that konqueror may suffer the same fate but at the moment I don't have a Linux install at my disposal).</p> <p>Does anyone know a way to have Safari recognise an embeded image tag to an external host as opening a client context? Or can someone provide a better way to do SSO from ASP.NET to site(s) which are not ASP.NET?</p> <p><strong>Note:</strong> yes I am aware there are problems in the SSO concept we've done thus far in regards to having images disabled. The solution proposed wasn't mine, I'm just stuck with it.</p>
<p>It looks like Safari (on my OS X, at least - which should be default settings) and, I assume Chrome, don't allow 3rd party cookies <em>by default</em>.</p> <p>Safari->Preferences->Security->Accept Cookies:</p> <p>o Always<br/> o Never<br/> + Only From Sites You Navigate To</p> <p>There's some <a href="http://trainofthoughts.org/blog/2007/04/14/cross-site-cookies/" rel="nofollow noreferrer">AJAX hackery</a> to get <em>your</em> document domain to set the cookie, but I don't think that'll really solve your problem here. I think Safari even forbids iframes from setting a 3rd party cookie, unless perhaps you set document.domain (though, if you shared a common domain, you could probably just set the cookie domain and be done with it all).</p> <p>Short of window.open, or a series of redirects, I can't really think of much you can do to get around the 3rd party cookie problem - so I'd probably scrap the embedded image trick and start from scratch.</p>
<p>It looks like Safari (on my OS X, at least - which should be default settings) and, I assume Chrome, don't allow 3rd party cookies <em>by default</em>.</p> <p>Safari->Preferences->Security->Accept Cookies:</p> <p>o Always<br/> o Never<br/> + Only From Sites You Navigate To</p> <p>There's some <a href="http://trainofthoughts.org/blog/2007/04/14/cross-site-cookies/" rel="nofollow noreferrer">AJAX hackery</a> to get <em>your</em> document domain to set the cookie, but I don't think that'll really solve your problem here. I think Safari even forbids iframes from setting a 3rd party cookie, unless perhaps you set document.domain (though, if you shared a common domain, you could probably just set the cookie domain and be done with it all).</p> <p>Short of window.open, or a series of redirects, I can't really think of much you can do to get around the 3rd party cookie problem - so I'd probably scrap the embedded image trick and start from scratch.</p>
29,909
<p>Problem: How can I tell if a selection of text in the CRichEditCtrl has multiple font sizes in it?</p> <hr> <p>Goal: I am sort of making my own RichEdit toolbar (bold, italic, font type, font size, etc). I want to emulate what MS Word does when a selection of text has more than a single font size spanning the selection.</p> <p>Ex - You have a line of text with the first 10 characters 9 pt font and the next 15 characters 14 pt font. If you highlight the first 5 characters, the "Font Pt Selection" drop down displays "9". If you then select the first 20 characters, the same drop down should have a empty/blank display.</p> <hr> <p>What I have going so far: I am getting the necessary notification when the selection changes inside of the CRichEditCtrl. Also, if there is only a single font size in the selection I am able to figure that out</p> <pre><code>CHARFORMAT cf; cf.cbSize = sizeof(CHARFORMAT); CRichEditCtrl ctrl; ctrl.GetSelectionCharFormat( cf ); int nFontPtSize = cf.yHeight / 20; </code></pre> <p>This will give me the needed info for the first case of my example above. Unfortunately, what I seem to get for the second part of my example only gives me back the info for where the selection ends (instead of the entire selection).</p> <p>In conclusion, is there some info I am missing in the CHARFORMAT or some other struct I can get from the CRichEditCtrl or some kind of interesting calculation I can do to make the decision that there are multiple sizes in the selection? So far my only idea is to chug through the selection a character at a time and see if the current font size of that character is different than any of the previous characters. I am mostly just hoping the info I need is there, and I just don't see it (In a similar way that from the CHARFORMAT's dwMask member tells me that any or all of Bold, Italic, Underline, etc are turned on).</p>
<p>As the above answer notes, the easiest way I can think of to do this is to use the Text Object Model (TOM), which is accessed through the ITextDocument COM interface. To get at this from your rich edit control (note code not tested, but should work):</p> <pre><code>CComPtr&lt;IRichEditOle&gt; richOle; richOle.Attach(edit.GetIRichEditOle()); CComQIPtr&lt;ITextDocument&gt; textDoc(richOle); </code></pre> <p>Then get a range. Here this is for the selected text, but one of the advantages of TOM is that you can operate on any range, not just what's selected.</p> <pre><code>CComPtr&lt;ITextSelection&gt; range; textDoc-&gt;GetSelection(&amp;range); </code></pre> <p>Then get the font for the range, and see what its characteristics are, e.g.</p> <pre><code>CComPtr&lt;ITextFont&gt; font; range-&gt;GetFont(&amp;font); long size; font-&gt;GetSize(&amp;size); </code></pre> <p>If the range is formatted with a single font size, you'll get that back in "size". If there's multiple font sizes, you'll get the value "tomUndefined" instead.</p>
<p>Been juggling a couple things, but I was finally able to work. This is how I finally was able to get everything to compile and run:</p> <pre><code>HWND hwnd; ITextDocument* pDoc; IUnknown* pUnk = NULL; float size = 0; hwnd = GetSafeHwnd(); ::SendMessage( hwnd, EM_GETOLEINTERFACE, 0, (LPARAM)&amp;pUnk ); if ( pUnk &amp;&amp; pUnk-&gt;QueryInterface( __uuidof(ITextDocument), (void**)&amp;pDoc ) == NOERROR ) { CComPtr&lt;ITextSelection&gt; range; pDoc-&gt;GetSelection( &amp;range ); CComPtr&lt;ITextFont&gt; font; range-&gt;GetFont( &amp;font ); // If there are multiple font sizes in the selection, "size" comes back as -9999 font-&gt;GetSize(&amp;size); } return size; </code></pre>
33,023
<p>I'm looking at setting up a small company that hosts flash-based websites for artist portfolios. The customer control panel would be django-powered, and would provide the interface for uploading their images, managing galleries, selling prints, etc.</p> <p>Seeing as the majority of traffic to the hosted sites would end up at their top level domain, this would result in only static media hits (the HTML page with the embedded flash movie), I could set up lighttpd or nginx to handle those requests, and pass the django stuff back to apache/mod_whatever.</p> <p>Seems as if I could set this all up on one box, with the django sites framework keeping each site's admin separate.</p> <p>I'm not much of a server admin. Are there any gotchas I'm not seeing?</p>
<p>Maybe. I don't think the built-in admin interface is really designed to corral admins into their own sites. The <code>sites</code> framework is more suited to publish the same content on multiple sites, not to constrain users to one site or another. You'd be better off writing your own admin interface that enforces those separations.</p> <p>As far as serving content goes, it seems like you could serve up a common (static) Flash file that uses a dynamic XML file to fill in content. If you use Django to generate the XML, that would give you the dynamic content you need.</p>
<p>Depending on the amount of sites you're going to host it might be easier to write a single Django app once, with admin, and to create a separate Django project for each new site. This is simple, it works for sure AND as an added bonus you can add features to newer sites without running the risk of causing problems in older sites.</p> <p>Then again, it might be handier to customize the admin such that you limit the amount of objects users can see to those on the given site itself. This is fairly easy to do, allthough you might want to use RequestSite instead of the usual Site from the sites framework as that requires separate settings for each site.</p> <p>There exists this one method in the ModelAdmin which you can override to have manual control over the objects being edited.</p>
24,695
<p>In reading Haskell-related stuff I sometimes come across the expression “tying the knot”, I think I understand <em>what</em> it does, but not <em>how</em>.</p> <p>So, are there any good, basic, and simple to understand explanations of this concept?</p>
<p>Tying the knot is a solution to the problem of circular data structures. In imperative languages you construct a circular structure by first creating a non-circular structure, and then going back and fixing up the pointers to add the circularity.</p> <p>Say you wanted a two-element circular list with the elements "0" and "1". It would seem impossible to construct because if you create the "1" node and then create the "0" node to point at it, you cannot then go back and fix up the "1" node to point back at the "0" node. So you have a chicken-and-egg situation where both nodes need to exist before either can be created.</p> <p>Here is how you do it in Haskell. Consider the following value:</p> <pre><code>alternates = x where x = 0 : y y = 1 : x </code></pre> <p>In a non-lazy language this will be an infinite loop because of the unterminated recursion. But in Haskell lazy evaluation does the Right Thing: it generates a two-element circular list. </p> <p>To see how it works in practice, think about what happens at run-time. The usual "thunk" implementation of lazy evaluation represents an unevaluated expression as a data structure containing a function pointer plus the arguments to be passed to the function. When this is evaluated the thunk is replaced by the actual value so that future references don't have to call the function again.</p> <p>When you take the first element of the list 'x' is evaluated down to a value (0, &amp;y), where the "&amp;y" bit is a pointer to the value of 'y'. Since 'y' has not been evaluated this is currently a thunk. When you take the second element of the list the computer follows the link from x to this thunk and evaluates it. It evaluates to (1, &amp;x), or in other words a pointer back to the original 'x' value. So you now have a circular list sitting in memory. The programmer doesn't need to fix up the back-pointers because the lazy evaluation mechanism does it for you.</p>
<p>It's not quite what you asked for, and it's not directly related to Haskell, but Bruce McAdam's paper <a href="http://www.lfcs.inf.ed.ac.uk/reports/97/ECS-LFCS-97-375/" rel="noreferrer">That About Wraps It Up</a> goes into this topic in substantial breadth and depth. Bruce's basic idea is to use an <strong>explicit knot-tying operator</strong> called WRAP instead of the <strong>implicit</strong> knot-tying that is done automatically in Haskell, OCaml, and some other languages. The paper has lots of <strong>entertaining examples</strong>, and if you are interested in knot-tying I think you will come away with a much better feel for the process.</p>
46,678
<p>When we add a variable to ASP.NET Session, where are those variables actually stored on the client side?</p>
<p>If you are using the default session in ASP.NET then it is stored in memory inside the ASP.NET worker process. It is a server side cache, nothing at all to do with the client. There are other session store options available such as dedicated session state machine or sql server. You can also roll your own session provider.</p> <p>All explained here <a href="http://msdn.microsoft.com/en-us/library/ms972429.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms972429.aspx</a></p>
<p>The session is stored on the web server and not the client. ASP.NET usually stores a key to the session in a cookie and uses this to identify your session next time you contact the web server.</p>
28,375
<p>How can I group by two different fields in a Crystal Report?</p> <p>Foe example :</p> <pre><code>val1|val2|val3|val6 val1|val12|val3|val7 val11|val2|val3|val8 val11|val12|val3|val9 </code></pre> <p>I want the report to look like </p> <pre><code>val1 : ======= val2 ---- val3|val6 val12 ------- val3|val7 val11 : ========= val2 ----- val3|val8 val12 : ------ val3|val9 </code></pre>
<p>The generic data provided is rather vague, so I will provide my own to demonstrate (with field names on the first line)</p> <pre>"EmployeeName","WeekNumber","DayOfWeek","HoursWorked" "John Doe",20,"Monday",8 "John Doe",20,"Tuesday",8 "John Doe",20,"Wednesday",8 "John Doe",21,"Thursday",8 "John Doe",21,"Friday",8 "Jane Doe",20,"Monday",8 "Jane Doe",20,"Tuesday",8 "Jane Doe",21,"Wednesday",8 "Jane Doe",21,"Thursday",8 "Jane Doe",21,"Friday",8 </pre> <p>Assuming that I read the question correctly, you would want the report to look like this:</p> <pre>John Doe Week: 20 Monday 8 hours Tuesday 8 hours Wednesday 8 hours Week: 21 Thursday 8 hours Friday 8 hours Jane Doe Week: 20 Monday 8 hours Tuesday 8 hours Week: 21 Wednesday 8 hours Thursday 8 hours Friday 8 hours</pre> <p>If this is the case, you would group by the "EmployeeName" field first, and then simply add another group for "WeekNumber" via the Insert menu using the Group option. This is pretty straightforward, and you can do summaries on the fields at various levels. The only thing that would get "hairy" with multiple tier of grouping would be if you were calculating fields within the group and wanted to return those calculations to a higher level of grouping for summation, which would require declaring global variables within the report.</p> <p>For what it's worth, I've been using Crystal Reports heavily for the past 7 years.</p>
<p>Not sure on best practices, but what I've used to do similar in the past was a sub report with it's own grouping, within the first group.</p> <p>So it would look something like this:</p> <p>MainReportHeader SubReport(?) SubreportHeader Values SubReportFooter MainReportFooter</p> <p>Again, not a crystal expert, just an idea and something I've used before. There is probably a much easier way.</p>
28,846
<p>In crontab, I can use an asterisk to mean every value, or "*/2" to mean every even value.</p> <p>Is there a way to specify every <strong>odd</strong> value? (Would something like "1+*/2" work?)</p>
<p>Depending on your version of cron, you should be able to do (for hours, say):</p> <pre><code> 1-23/2 </code></pre> <p>Going by the EXTENSIONS section in the crontab(5) manpage:</p> <pre><code> Ranges can include "steps", so "1-9/2" is the same as "1,3,5,7,9". </code></pre> <p>For a more portable solution, I suspect you just have to use the simple list:</p> <pre><code> 1,3,5,7,9,11,13,15,17,19,21,23 </code></pre> <p>But it might be easier to wrap your command in a shell script that will immediately exit if it's not called in an odd minute.</p>
<p>Works on Cronie Even with 5 minutes interval e.g.</p> <pre><code>3-58/5 * * * * /home/test/bin/do_some_thing_every_five_minute </code></pre>
14,900
<p>I'm a fan of extension methods in C#, but haven't had any success adding an extension method to a static class, such as <code>Console</code>.</p> <p>For example, if I want to add an extension to <code>Console</code>, called '<code>WriteBlueLine</code>', so that I can go:</p> <pre><code>Console.WriteBlueLine(&quot;This text is blue&quot;); </code></pre> <p>I tried this by adding a local, public static method, with <code>Console</code> as a '<code>this</code>' parameter... but no dice!</p> <pre><code>public static class Helpers { public static void WriteBlueLine(this Console c, string text) { Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine(text); Console.ResetColor(); } } </code></pre> <p>This didn't add a '<code>WriteBlueLine</code>' method to <code>Console</code>... am I doing it wrong? Or asking for the impossible?</p>
<p>No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper around the <code>ConfigurationManager</code> interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.</p> <pre><code> public static class ConfigurationManagerWrapper { public static ConfigurationSection GetSection( string name ) { return ConfigurationManager.GetSection( name ); } ..... public static ConfigurationSection GetWidgetSection() { return GetSection( "widgets" ); } } </code></pre>
<p>You CAN do this if you are willing to "frig" it a little by making a variable of the static class and assigning it to null. However, this method would not be available to static calls on the class, so not sure how much use it would be:</p> <pre><code>Console myConsole = null; myConsole.WriteBlueLine("my blue line"); public static class Helpers { public static void WriteBlueLine(this Console c, string text) { Console.ForegroundColor = ConsoleColor.Blue; Console.WriteLine(text); Console.ResetColor(); } } </code></pre>
30,976
<p>What needs to be done to have your .NET application show up in Window's system tray as icon?</p> <p>And how do you handle mousebutton clicks on said icon?</p>
<p>First, add a <a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.notifyicon" rel="nofollow noreferrer">NotifyIcon</a> control to the Form. Then wire up the Notify Icon to do what you want.</p> <p>If you want it to hide to tray on minimize, try this.</p> <pre class="lang-vb prettyprint-override"><code>Private Sub frmMain_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Resize If Me.WindowState = FormWindowState.Minimized Then Me.ShowInTaskbar = False Else Me.ShowInTaskbar = True End If End Sub Private Sub NotifyIcon1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick Me.WindowState = FormWindowState.Normal End Sub </code></pre> <p>I'll occasionally use the Balloon Text in order to notify a user - that is done as such:</p> <pre class="lang-vb prettyprint-override"><code> Me.NotifyIcon1.ShowBalloonTip(3000, "This is a notification title!!", "This is notification text.", ToolTipIcon.Info) </code></pre>
<p>To extend <a href="https://stackoverflow.com/a/158927/7444103">Tom's answer</a>, I like to only make the icon visible if the application is minimized.<br> To do this, set <code>Visible = False</code> for <a href="https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.notifyicon" rel="nofollow noreferrer">NotifyIcon</a> and use the below code.</p> <p>I also have code below to hide the icon during close the prevent the annoying <em>ghost</em> tray icons that persist after application close.</p> <pre class="lang-vb prettyprint-override"><code>Private Sub Form_Resize(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Resize If Me.WindowState = FormWindowState.Minimized Then Hide() NotifyIcon1.Visible = True NotifyIcon1.ShowBalloonTip(3000, NotifyIcon1.Text, "Minimized to tray", ToolTipIcon.Info) End If End Sub Private Sub NotifyIcon1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick Show() Me.WindowState = FormWindowState.Normal Me.Activate() NotifyIcon1.Visible = False End Sub Private Sub Form_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing NotifyIcon1.Visible = False Dim index As Integer While index &lt; My.Application.OpenForms.Count If My.Application.OpenForms(index) IsNot Me Then My.Application.OpenForms(index).Close() End If index += 1 End While End Sub </code></pre> <p>If you want to add a right click menu:</p> <p><a href="https://social.technet.microsoft.com/wiki/contents/articles/13319.vb-net-how-to-make-a-right-click-menu-for-a-tray-icon.aspx" rel="nofollow noreferrer">VB.NET: How to Make a Right Click Menu for a Tray Icon</a><br></p> <p>Per the article (with mods for context):</p> <p>Setting up the Form for hosting the tray icon context menu</p> <ul> <li>In the Properties set FormBorderStyle to None.</li> <li>Set ShowInTaskbar as False (because we don't want an icon appearing in taskbar when we right-click the tray icon!).</li> <li>Set StartPosition to Manual.</li> <li>Set TopMost to True.</li> <li>Add a ContextMenuStrip to your new Form, and name it whatever you want.</li> <li>Add items to the ContextMenuStrip (for this example just add one item called "Exit").</li> </ul> <p>The Form code behind will look like this:</p> <pre class="lang-vb prettyprint-override"><code>Private Sub Form_Deactivate(sender As Object, e As EventArgs) Handles Me.Deactivate Me.Close() End Sub Private Sub Form_Load(sender As Object, e As EventArgs) Handles MyBase.Load ContextMenuStrip1.Show(Cursor.Position) Me.Left = ContextMenuStrip1.Left + 1 Me.Top = ContextMenuStrip1.Top + 1 End Sub Private Sub ExitToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExitToolStripMenuItem.Click MainForm.NotifyIcon1.Visible = False End End Sub </code></pre> <p>I then change the notifyicon mouse event to this (<code>TrayIconMenuForm</code> is the name of my Form for providing the context menu):</p> <pre class="lang-vb prettyprint-override"><code>Private Sub NotifyIcon1_MouseClick(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles NotifyIcon1.MouseClick Select Case e.Button Case Windows.Forms.MouseButtons.Left Show() Me.WindowState = FormWindowState.Normal Me.Activate() NotifyIcon1.Visible = False Case Windows.Forms.MouseButtons.Right TrayIconMenuForm.Show() 'Shows the Form that is the parent of "traymenu" TrayIconMenuForm.Activate() 'Set the Form to "Active", that means that that will be the "selected" window TrayIconMenuForm.Width = 1 'Set the Form width to 1 pixel, that is needed because later we will set it behind the "traymenu" TrayIconMenuForm.Height = 1 'Set the Form Height to 1 pixel, for the same reason as above Case Else 'Do nothing End Select End Sub </code></pre>
19,223
<p>How do I hide the <strong>prev/today/next</strong> navigation in jQuery DatePicker?</p> <p>I'm happy with just the Month and Year drop down boxes.</p> <p>Also how do I disable the animations?</p> <p><a href="https://stackoverflow.com/questions/316147/how-do-i-hide-the-nexttodayprevious-navigation-in-jquery-datepicker-and-turn-of#316153">@tvanfosson</a> - I already tried <code>hideIfNoPrevNext</code> but that only works if you don't have a date range that spans two months. </p> <p>The duration option did the trick at turning off the animations though. </p> <p>Cheers.</p>
<p>You can find the options for the DatePicker control at <a href="http://docs.jquery.com/UI/Datepicker/datepicker#options" rel="noreferrer">http://docs.jquery.com/UI/Datepicker/datepicker#options</a>. Specifically, I think you want to set hideIfNoPrevNext to true and set duration to ''.</p> <pre><code> $('#cal').datepicker( { hideIfNoPrevNext: true, duration: '' } ); </code></pre>
<p>use this code, it will definitely work for stop navigation of next or prev button..</p> <pre><code>$("#cal").datepicker({ stepMonths: 0 )}; </code></pre>
40,818
<p>we have a template project we often copy. so we can costumize the copy and still have a common template.<br></p> <p>To optimize the "copy &amp; initial changes"-process, i though that i can write a little script, that does the following:</p> <ul> <li>copy the project-template (in svn) to another directory in the svn</li> <li>check-out the project and do some changes (change names in some files)</li> <li>check-in the customized project</li> </ul> <p>The question is: what's the best way to do this? any experience in this? which type of script (normal batch or java)? any example code?</p> <p>thanks for your answers</p>
<p>Here is something i put together with some information i found <a href="http://forums.devshed.com/unix-help-35/unix-find-and-replace-text-within-all-files-within-a-146179.html" rel="nofollow noreferrer">here</a>.</p> <pre><code>#!/bin/bash searchterm="&lt;ProjectName&gt;" replaceterm="New Project" srcsvnrepo="file:///svnrepoaddress" destsvnrepo="file:///data/newrepo" dumpfile="/home/&lt;user&gt;/repo.dump" tmpfolder="/home/&lt;user&gt;/tmp_repo" svnadmin dump $srcsvnrepo &gt; $dumpfile svnadmin create --fs-type fsfs $destsvnrepo svnadmin load $destsvnrepo &lt; $dumpfile svn co $destsvnrepo $tmpfolder for file in $(grep -l -R $searchterm $tmpfolder) do sed -e "s/$searchterm/$replaceterm/ig" $file &gt; /tmp/tempfile.tmp mv /tmp/tempfile.tmp $file echo "Modified: " $file done svn ci $tmpfolder --message "Initial Check-In" </code></pre> <p>Basically this will dump a backup of the specified source svn repo to a file, create a new repo, load the backup into it, check out the files, get a list of files that contain the string to search for, perform a regex on each of those files storing the new version in a temp location and then moving the temp file back to the original location, and finally checking the changes back into the new repo.</p> <p>I haven't fully tested this so some minor tweaking may be necessary, but the basic steps should be correct. Please let me know if i've made some gross miscalculation and this totally does not work.</p>
<p>Just a shell script would do.</p>
22,103
<p>I am not very good with Regex but I am learning.</p> <p>I would like to remove some html tag by the class name. This is what I have so far :</p> <pre><code>&lt;div class=&quot;footer&quot;.*?&gt;(.*?)&lt;/div&gt; </code></pre> <p>The first .*? is because it might contain other attribute and the second is it might contain other html stuff.</p> <p>What am I doing wrong? I have try a lot of set without success.</p> <h3>Update</h3> <p>Inside the DIV it can contain multiple line and I am playing with Perl regex.</p>
<p>You will also want to allow for other things before class in the div tag</p> <pre><code>&lt;div[^&gt;]*class="footer"[^&gt;]*&gt;(.*?)&lt;/div&gt; </code></pre> <p>Also, go case-insensitive. You may need to escape things like the quotes, or the slash in the closing tag. What context are you doing this in?</p> <p>Also note that HTML parsing with regular expressions can be very nasty, depending on the input. A good point is brought up in an answer below - suppose you have a structure like: </p> <pre><code>&lt;div&gt; &lt;div class="footer"&gt; &lt;div&gt;Hi!&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Trying to build a regex for that is a recipe for disaster. Your best bet is to load the document into a DOM, and perform manipulations on that.</p> <p>Pseudocode that should map closely to XML::DOM:</p> <pre><code>document = //load document divs = document.getElementsByTagName("div"); for(div in divs) { if(div.getAttributes["class"] == "footer") { parent = div.getParent(); for(child in div.getChildren()) { // filter attribute types? parent.insertBefore(div, child); } parent.removeChild(div); } } </code></pre> <p><hr> Here is a perl library, <a href="http://search.cpan.org/dist/HTML-DOM/" rel="noreferrer">HTML::DOM</a>, and another, <a href="http://search.cpan.org/src/ENNO/libxml-enno-1.02/html/XML/DOM/Node.html" rel="noreferrer">XML::DOM</a><br> .NET has built-in libraries to handle dom parsing.</p>
<p>why not <code>&lt;div class="footer".*?&lt;/div&gt;</code> I'm not a regex guru either, but I don't think you need to specify that last bracket for your open div tag</p>
28,020
<p>I'm trying to generate customized xml files from a template xml file in python. </p> <p>Conceptually, I want to read in the template xml, remove some elements, change some text attributes, and write the new xml out to a file. I wanted it to work something like this:</p> <pre><code>conf_base = ConvertXmlToDict('config-template.xml') conf_base_dict = conf_base.UnWrap() del conf_base_dict['root-name']['level1-name']['leaf1'] del conf_base_dict['root-name']['level1-name']['leaf2'] conf_new = ConvertDictToXml(conf_base_dict) </code></pre> <p>now I want to write to file, but I don't see how to get to ElementTree.ElementTree.write() </p> <pre><code>conf_new.write('config-new.xml') </code></pre> <p>Is there some way to do this, or can someone suggest doing this a different way? </p>
<p>I'm not sure if converting the info set to nested dicts first is easier. Using ElementTree, you can do this:</p> <pre><code>import xml.etree.ElementTree as ET doc = ET.parse("template.xml") lvl1 = doc.findall("level1-name")[0] lvl1.remove(lvl1.find("leaf1") lvl1.remove(lvl1.find("leaf2") # or use del lvl1[idx] doc.write("config-new.xml") </code></pre> <p>ElementTree was designed so that you don't have to convert your XML trees to lists and attributes first, since it uses exactly that internally.</p> <p>It also support as small subset of <a href="http://effbot.org/zone/element-xpath.htm" rel="nofollow noreferrer">XPath</a>.</p>
<p>Have you tried this?</p> <pre><code>print xml.etree.ElementTree.tostring( conf_new ) </code></pre>
15,526
<p>I am looking for the best method to run a Java Application as a *NIX daemon or a Windows Service. I've looked in to the <a href="http://wrapper.tanukisoftware.org/" rel="noreferrer">Java Service Wrapper</a>, the <a href="http://commons.apache.org/daemon/jsvc.html" rel="noreferrer">Apache Commons project 'jsvc'</a>, and the <a href="http://commons.apache.org/daemon/procrun.html" rel="noreferrer">Apache Commons project 'procrun'</a>. So far, the Java Service Wrapper looks like it's the best option... but, I'm wondering if there are any other "Open Source friendly" licensed products out there.</p>
<p>I've had great success with Java Service Wrapper myself. I haven't looked at the others, but the major strengths of ServiceWrapper are:</p> <ul> <li>Great x-platform support - I've used it on Windows and Linux, and found it easy on both</li> <li>Solid Documentation - The docs are clear and to the point, with great examples</li> <li>Deep per-platform support - There are some unique features in the window service management system that are supported perfectly by service wrapper (w/o restarting). And on Windows, you will even see your app name in the process list instead of just "java.exe".</li> <li>Standards Compliant - Unlike many ad-hoc Java init scripts, the scripts for service wrapper tend to be compliant with LSB standards. This can end up being very important if you ever want high availability management from something like Linux Heartbeat/HA.</li> </ul> <p>Anyway, just my 2 cents... :)</p>
<p>Are there any special attributes that you need to apply (like OS guided resource management) that you need to support? Otherwise, for Unix you should be able to daemonize your application by writing an appropriate init.d script and setting your app to start automatically.</p>
4,514
<p>Hi i am encountering problems trying to post a WebRequest under Https. </p> <p>i received the following errors</p> <h1>1.-The underlying connection was closed: Unable to connect to the remote server.</h1> <h1>2.-the operation TimeOut</h1> <h1>3-The underlying connection was closed: Could not establish secure channel for SSL/TLS.</h1> <p>i tried with about 3 or 4 different proxies of my company and the customer company and not even when i am directly with the ISP provider with no restrictions, i get the above errors when executing the following method</p> <pre><code>WebRequest.GetRequestStream() </code></pre> <p>this occurs behind a proxy or not, the request can only be succesfully post from one single PC which is behind a proxy. the proxy doesn't have a client certificate installed.</p> <p>this is under .net framework 1.1 and the request already contains network credentials.</p> <p>what could be?</p> <h1>Update</h1> <p>the inner exception the 3rd error is the following: The function completed successfully, but must be called again to complete the context</p> <p>according to iisper.h <a href="http://doc.ddart.net/msdn/header/include/issperr.h.html" rel="nofollow noreferrer">documentation</a> this error belongs to the </p> <pre><code>// // MessageId: SEC_I_CONTINUE_NEEDED // // MessageText: // // The function completed successfully, but must be called // again to complete the context // #define SEC_I_CONTINUE_NEEDED ((HRESULT)0x00090312L) </code></pre> <p>on <a href="http://msdn.microsoft.com/en-us/library/aa375924(VS.85).aspx" rel="nofollow noreferrer">MSDN</a> this refers to </p> <p>SEC_I_CONTINUE_NEEDED The client must send the output token to the server and wait for a return token. The returned token is then passed in another call to InitializeSecurityContext (Schannel). The output token can be empty.</p> <p>does this means the PC lacks a client certificate?</p>
<p>There are a whole number of things that could be complicating things, as far as inconsistencies with the SSL certs, etc. But first, you should do some basic debugging to rule out the obvious things:</p> <p>-- Did you try sending a simple web request to other servers? Try both (unsecured) http and (secured) https</p> <p>-- Did you try connecting from another computer, or from another network? You mentioned that the client is behind a proxy; try a computer w/o a proxy first, to rule that out.</p> <p>-- Are you making multiple WebRequests within the session? There is a hard-limit on the number of open requests, so make sure you're closing them after you get the WebResponse. Perhaps make a test program with just one request.</p> <p>If that doesn't narrow it down, then it's probably something more complicated, with their the server or the proxy. You can track outgoing network packets with a program such as netshark to try to track down where things are getting stuck.</p>
<p>The SSL certificate name probably doesn't match. This is often the case with selfsigned certificates.</p> <p>The solution is to write your own authentication routine where you either always return true or do the necessary authentication to make sure the certificate is valid.</p> <pre><code>// .NET 2.0+ ... ServicePointManager.ServerCertificateValidationCallback += MyValidationCallback ... public bool MyValidationCallback(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors err) { return true; } // .NET 1.1 public class MyCertificatePolicy : ICertificatePolicy { public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, int certificateProblem) { return true; } } ... ServicePointManager.CertificatePolicy = new MyCertificatePolicy(); ... </code></pre>
36,390
<p>I created a class derived from System.Configuration.Install for my installer.<br> But the code in Uninstall() is being called when I try to update the application.<br> How can I detect that the user is trying to update instead of uninstall?</p> <p>Maybe <a href="http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.dotnet.languages.csharp&amp;tid=a018d064-8bb8-441d-bccc-f5ce2cc665eb&amp;cat=&amp;lang=&amp;cr=&amp;sloc=&amp;p=1" rel="nofollow noreferrer">this post</a> explains it better than me:</p> <blockquote> <p>My problem boils down to: when the user performs an update (i.e. double clicks on MyAppVer2.msi when they already have MyAppVer1.msi installed) the Uninstall method inside my Installer is called first, but I have no apparent property to check from inside this method to detect that an update is being performed so that I can branch my code appropriately.</p> </blockquote>
<p>There is a setting in your setup project that will "uninstall" previous versions by default, turn this flag OFF, then you will not have to worry!</p>
<p>Blind guess here, but I'd start out by checking the <a href="http://msdn.microsoft.com/en-us/library/system.configuration.install.installer.context.aspx" rel="nofollow noreferrer">Installer.Context</a> property for a <a href="http://msdn.microsoft.com/en-us/library/system.configuration.install.installcontext.parameters.aspx" rel="nofollow noreferrer">parameter</a>. If that's no help, there may be something in the savedState parameter passed to <a href="http://msdn.microsoft.com/en-us/library/system.configuration.install.installer.uninstall.aspx" rel="nofollow noreferrer">Uninstall</a>.</p> <p>Last chance would be to <a href="http://msdn.microsoft.com/en-us/library/068e5k1w.aspx" rel="nofollow noreferrer">prompt the user</a>, and set the child installers as appropiate.</p>
19,294
<p>For a given table 'foo', I need a query to generate a set of tables that have foreign keys that point to foo. I'm using Oracle 10G.</p>
<p>This should work (or something close):</p> <pre><code>select table_name from all_constraints where constraint_type='R' and r_constraint_name in (select constraint_name from all_constraints where constraint_type in ('P','U') and table_name='&lt;your table here&gt;'); </code></pre>
<p>Download the Oracle Reference Guide for 10G which explains the data dictionary tables.</p> <p>The answers above are good but check out the other tables which may relate to constraints.</p> <pre><code>SELECT * FROM DICT WHERE TABLE_NAME LIKE '%CONS%'; </code></pre> <p>Finally, get a tool like Toad or SQL Developer which allows you to browse this stuff in a UI, you need to learn to use the tables but you should use a UI also.</p>
11,143
<p>What does the <code>volatile</code> keyword do? In C++ what problem does it solve?</p> <p>In my case, I have never knowingly needed it.</p>
<p><code>volatile</code> is needed if you are reading from a spot in memory that, say, a completely separate process/device/whatever may write to.</p> <p>I used to work with dual-port ram in a multiprocessor system in straight C. We used a hardware managed 16 bit value as a semaphore to know when the other guy was done. Essentially we did this:</p> <pre><code>void waitForSemaphore() { volatile uint16_t* semPtr = WELL_KNOWN_SEM_ADDR;/*well known address to my semaphore*/ while ((*semPtr) != IS_OK_FOR_ME_TO_PROCEED); } </code></pre> <p>Without <code>volatile</code>, the optimizer sees the loop as useless (The guy never sets the value! He's nuts, get rid of that code!) and my code would proceed without having acquired the semaphore, causing problems later on.</p>
<p>One use I should remind you is, in the signal handler function, if you want to access/modify a global variable (for example, mark it as exit = true) you have to declare that variable as 'volatile'.</p>
9,815
<p>How do SQL developers go about keeping up on current techniques and trends in the SQL world? Are there any blogs, books, articles, techniques, etc that are being used to keep up to date and in the know?</p> <p>There are a lot of opportunities out their for OO, procedural, and functional programmers to take part in a variety of open source projects, but it seems to me that the FOSS avenue is a bit more closed for SQL developers.</p> <p>Thoughts?</p>
<p>Find challenging questions that test your TRANSACT-SQL knowledge ... personally I enjoy <a href="https://rads.stackoverflow.com/amzn/click/com/0123735963" rel="noreferrer" rel="nofollow noreferrer">Joe Celko's SQL Puzzles and Answers</a>.</p> <p><a href="http://ecx.images-amazon.com/images/I/51DTJ099P7L._SL500_BO2,204,203,200_PIsitb-dp-500-arrow,TopRight,45,-64_OU01_AA240_SH20_.jpg" rel="noreferrer">Joe Celko&#39;s SQL Puzzles and Answers http://ecx.images-amazon.com/images/I/51DTJ099P7L._SL500_BO2,204,203,200_PIsitb-dp-500-arrow,TopRight,45,-64_OU01_AA240_SH20_.jpg</a></p>
<p>To be honest, I don't see much a need for extreme SQL skills. Once I can create transactions (for DB consistency) and basic triggers (for cross-table consistency), I'm usually fine keeping program logic... in the program, and not putting it into whatever database I'm using. I've not found much depth to SQL worth investigating for a lifetime, unlike general programming, which keeps expanding in depth.</p>
12,689
<p>I am researching companies that provide both SMS and voicemail services via an API call. I want to be able to contact users (most of whom are US-based) via both text-message and voicemail. The idea is that our web server would connect to the SMS/voicemail provider's server (e.g. using HTTP post) and then send the message to the recipient's phone. In the case of an SMS message we'd send the user a text message and for voicemail there would be a translation of the text message to a robot voice and it would then call the user's phone and recite the message.</p> <p>Are there any folks out there that have worked with companies that provide both SMS and voicemail? If so, can you recommend a provider? </p> <p>Thanks in advance.</p>
<p>I've used <a href="http://web21c.bt.com/" rel="nofollow noreferrer">BT's phone/sms services</a> in the past. It's a great service for sending sms as well as automating calls. I particularly like the fact that everything is open sourced, and they have wrappers for a lot of main stream languages, plus the API is quite simple.</p> <p>I was introduced to it in a course I took with the BT guys, and it took me a couple of days to have something not trivial running.</p>
<p>Update: the following US-based providers have both voicemail (including text-to-speech) and SMS services that are accessible via an API (web service type of model). </p> <p><a href="http://www.west.com/" rel="nofollow noreferrer">West Corporation</a> (based in Omaha, NE) </p> <p><a href="http://www.premiereglobal.com/" rel="nofollow noreferrer">Premier Global Services</a> (based in Atlanta, GA)</p> <p><a href="http://www.tfcci.com/" rel="nofollow noreferrer">Twenty First Century Communications</a> (based in Columbus, OH)</p> <p><a href="http://www.varolii.com/" rel="nofollow noreferrer">Varolii Corporation</a> (based in Seattle, WA)</p>
25,156