input
stringlengths
51
42.3k
output
stringlengths
18
55k
How do i print the columns of a JAMA matrix? <p>I use the JAMA.matrix package..how do i print the columns of a matrix </p>
<p>The easiest way would probably be to <a href="http://math.nist.gov/javanumerics/jama/doc/Jama/Matrix.html#transpose%28%29" rel="nofollow">transpose</a> the matrix, then print each row. Taking part of the example from the <a href="http://math.nist.gov/javanumerics/jama/doc/Jama/Matrix.html" rel="nofollow">API</a>:</p> <pre><code>double[][] vals = {{1.,2.,3},{4.,5.,6.},{7.,8.,10.}}; Matrix a = new Matrix(vals); Matrix aTransposed = a.transpose(); double[][] valsTransposed = aTransposed.getArray(); // now loop through the rows of valsTransposed to print for(int i = 0; i &lt; valsTransposed.length; i++) { for(int j = 0; j &lt; valsTransposed[i].length; j++) { System.out.print( " " + valsTransposed[i][j] ); } } </code></pre> <p>As duffymo pointed out in a comment, it <em>would</em> be more efficient to bypass the transposition and just write the nested for loops to print down the columns instead of across the rows. If you need to print both ways that would result in twice as much code. That's a common enough tradeoff (speed for code size) that I leave it to you to decide.</p>
How to get different timezones' current time in PHP? <p>Unfortunately I'm not using PHP 5. On the documentation of the <a href="http://php.net/date" rel="nofollow">date</a> function it has a timezone section which lets you specify the difference from the GMT tome. How can you use that to get the current/local time in a specified timezone, and does it with with daylights savings?</p>
<p>You can convert times to different timezones by using the PEAR Date package <a href="http://pear.php.net/package/Date" rel="nofollow">http://pear.php.net/package/Date</a></p> <p>Examples here <a href="http://pear.php.net/manual/en/package.datetime.date.examples.php" rel="nofollow">http://pear.php.net/manual/en/package.datetime.date.examples.php</a></p>
Keypress event is triggered twice for a single ENTER button press in Windows CE <p>During development i have observed that certain PDAs with Windows CE and possibly Windows Mobile too are sending the Enter key twice in the key pressed event thus i execute twice the code that lies under the control's key press event for the return button.</p> <p>I suspect that this is a hardware bug and i would like to ask how you resolved it without changing your application logic.</p>
<p>I don’t know if this will help but if you read the keyboard port Enter is seen as two bytes rather than one.</p>
How can I sum values in a MySQL query? <p>I am using MySQL.<br /> I have a P_id that should be able to find the max value. I want to show the sum of two formulas by following:</p> <pre><code> Then Sum(max(pval)*S_val*Estimate) Sum(max(pval)*P_val*Analyze) Finally sum the Both above </code></pre> <p>I used the following function but it gives me an error:</p> <pre> > id Display P_id P_val Analyze S_id S_val Estimate > 70 Data1 1 1 178 0 0 0 > 71 Data2 1 0 0 1 3 50 </pre> <pre><code>SELECT SUM( max(pval)*S_val*Estimate) + Sum( max(pval)* P_val * Analyze) from DATA where pid='1' </code></pre> <p>This results in:</p> <ul> <li>A: 1*178</li> <li>B: 1*3*50</li> <li>Sum(A+B): 328</li> </ul>
<p>You cannot nest aggregate functions - <code>SELECT SUM(MAX(x))</code> will always error.</p> <p>You can get the inner value in a subquery instead:</p> <pre><code>SELECT SUM(maxpval * S_val * Estimate), SUM(maxpval * P_val * Analyze) FROM yourTable JOIN ( SELECT MAX(P_val) AS maxpval FROM yourTable ) AS dt; </code></pre>
Get current MethodBase through reflection <p>Can I get the current method's MethodInfo somehow?</p>
<pre><code>System.Reflection.MethodBase.GetCurrentMethod() </code></pre> <p>Found it myself after some screwing around with the reflection namespace...</p>
Separating groups into nearly-equal stacks <p>I have a list of documents and I want to display them grouped by the first letter of their name on a web-page, over three columns.</p> <p>In short, something like this:</p> <pre><code>A | C | E A | D | F B | D | F B | D | F | D | </code></pre> <p>An important difference from say, the Windows Explorer view style is that I want letters to stay with each other. No breaking mid-group. To accommodate this, I don't care if one column is a couple of entries too tall.</p> <p>I've started by sorting the array of documents by name and splitting them into a nested array. So I know (or can easily find out):</p> <ul> <li>How many unique letters there are</li> <li>How many letters there are in each group</li> <li>How many entries there are in total</li> <li>The mean average of how many values there should be in each column (ideally but not neccessarily)</li> </ul> <p>I don't care what your answers come in. I'm looking for the algorithm rather than the implementation so you can code in anything you like (except perhaps Fortran). an explanation in HTML might be a toughie too.</p> <p>I invite somebody to go wild on the tags because I couldn't think of anything relevant and no, this isn't homework, so please don't mark it as such.</p>
<p>Perhaps it helps if you look at the problem like this:</p> <p>For your example, you have a string like this:</p> <pre><code>AA BB C DDDD E FFF </code></pre> <p>The space positions are the places where you could start a new column. Everywhere else you mustn't to keep same letters in the same column. So you actually can mark the space position like this:</p> <pre><code>AA1BB2C3DDDD4E5FFF </code></pre> <p>Now you have 5 positions where you can either break the column or not, as it's a binary decision, use a string of 0's and 1's for this and brute force every possible combination:</p> <pre><code>12345 00000 -&gt; no break at all, column count = 1, max. lines = 13 ... 01010 -&gt; your example, column count = 3, max. lines = 5 ... 11111 -&gt; breaks everywhere, column count = 6, max. lines = 4 </code></pre> <p>This is a brute force attempt, but you can easily see that the 1's count affects the column count (column count = number of 1's + 1) and you want to minimize max. lines, this should be possible to somehow calculate without having to test each combination.</p> <p>EDIT2: Didn't recognize you want 3 columns, this makes it easier as you know you will have only 3 1's, but it's still brute force.</p> <p>EDIT: Another approach I'd favorize:</p> <p>Write the letter counts like this:</p> <pre><code>A B C D E F 2 2 1 4 1 3 </code></pre> <p>You can now join letters that are next to each other. Always chose the two letters with the lowest count sum:</p> <pre><code>2 2 1 4 1 3 - lowest = "2 1" 2 3 4 1 3 - lowest = "1 3" 2 3 4 4 - lowest = "2 3" 5 4 4 - stop now, as we have 3 columns now Result: AABBC, DDDD, EFFF </code></pre> <p>This perhaps won't lead to the optimal solution, but it's a nice and easy way to solve your problem, I think.</p>
How to compile and run inter-dependent plugin jars <p>I have to build two eclipse-plugin projects into two separate jars with each one dependent on the other for compiling. Eclipse IDE complains about "cyclical dependency...". How do I build these plugin jars? I guess running these plugins by just putting them in the eclipse/plugin folder should be smooth.</p>
<p>If you have a cyclic dependency, you have two choices: </p> <ol> <li>You can get rid of it by putting them into one JAR. If they truly depend on each other, they really are just one entity.</li> <li>You can split out the packages that cause the cyclic dependency into a third JAR and deploy two plug-ins with two JARs each. </li> </ol>
How can I implement Nested Master Pages in ASP.NET MVC RC2? <p>I have a main MasterPage which has a single column layout for the web application I am currently designing. I want to re-use the existing MasterPage to implement a two column layout using Nested MasterPages which was possible on previous releases of the ASP.NET MVC Framework but I can't seem to get it to work in the RC2.</p> <p>The following is the code I am currently working on,</p> <pre><code>&lt;%@ Master Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewMasterPage" %&gt; &lt;%@ Import Namespace="RHP.WebMvcApplication.Library" %&gt; &lt;asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"&gt; &lt;asp:ContentPlaceHolder ID="TitleContent" runat="server"&gt; Member List &lt;/asp:ContentPlaceHolder&gt; &lt;/asp:Content&gt; &lt;asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"&gt; &lt;div id="mainLeftContent"&gt; &lt;h3&gt;Options&lt;/h3&gt; &lt;%= Html.MenuCurrentChildren(); %&gt; &lt;/div&gt; &lt;div id="mainContent"&gt; &lt;% Html.RenderPartial("MemberApplicationStateControl"); %&gt; &lt;asp:ContentPlaceHolder id="MainContent" runat="server"&gt; &lt;/asp:ContentPlaceHolder&gt; &lt;/div&gt; &lt;/asp:Content&gt; </code></pre>
<p>Nevermind! I had a bug in the page that was stopping the page from being rendered so it does work now.</p> <p>The bug was the (;):</p> <pre><code>&lt;div id="mainLeftContent"&gt; &lt;h3&gt;Options&lt;/h3&gt; &lt;%= Html.MenuCurrentChildren(); %&gt; &lt;/div&gt; </code></pre> <p>The fix was:</p> <pre><code>&lt;div id="mainLeftContent"&gt; &lt;h3&gt;Options&lt;/h3&gt; &lt;%= Html.MenuCurrentChildren() %&gt; &lt;/div&gt; </code></pre> <p>Its the little stuff that makes programming interesting.</p>
PHP and ?? operator <p>Like some people know, C# has very useful <code>??</code> operator which evaluates and returns expression on the right if expression on the left is null. It's very useful for providing default values, for example:</p> <pre><code>int spaces = readSetting("spaces") ?? 5; </code></pre> <p>If <code>readSetting</code> couldn't find <code>"spaces"</code> and returns null, variable <code>spaces</code> would hold default value of <code>5</code>.</p> <p>You could do almost the same in JavaScript and Ruby with <code>||</code> operator, as in</p> <pre><code>var spaces = readSetting("spaces") || 5; </code></pre> <p>although you couldn't have <code>0</code> as value of <code>spaces</code> in JavaScript in this case and <code>false</code> in both Ruby and JavaScript.</p> <p>PHP has <code>or</code> operator and although it doesn't work as <code>||</code> in a sense that it doesn't return expression from the right, it still could be useful here:</p> <pre><code>$spaces = readSetting('spaces') or $spaces = 5; </code></pre> <p>with the note that <code>""</code> and <code>"0"</code> are also treated like <code>false</code> in PHP in addition to <code>false, 0</code> and <code>null</code> in most languages.</p> <p>The question is, should I use the construction from above? Does it have side effects apart from treating large class of characters as false? And is there better construction that is usually used and recommended by PHP community this task?</p>
<p>It is a good idea to be more explicit in cases like this, especially in PHP since it has somewhat confusing type conversion rules (e.g. "0" is false as you pointed out).</p> <p>If you want to be strict, let your function <code>readSettings</code> return the correct setting or a well-defined value if no setting is found, e.g. <code>null</code>. Then you should use it as:</p> <pre><code>$spaces = readSettings('spaces'); if (null === $spaces) { $spaces = 5; } </code></pre> <p>If you want to be more generous and only want $spaces to be non-empty, use:</p> <pre><code>$spaces = readSettings('spaces'); if (empty($spaces)) { // or: if (!$spaces) { $spaces = 5; } </code></pre> <p>You could shorten it by the cost of a second function call or ugly constructs (not recommended):</p> <pre><code>$spaces = readSettings('space') ? readSettings('space') : 5; $spaces = ($x = readSettings('space')) ? $x : 5; // UGLY! </code></pre> <p>But watch out if you want <code>0</code> to be a valid value for <code>$spaces</code>!</p> <p>From the <a href="http://www.python.org/dev/peps/pep-0020/" rel="nofollow">Zen of Python</a>: </p> <blockquote> <p>Explicit is better than implicit.</p> </blockquote> <p>In your case I would recommend to just add a second paramter <code>$default</code> to <code>readSettings()</code>:</p> <pre><code>function readSettings($key, $default=null) { return isset($settings[$key]) ? $settings[$key] : $default; } $spaces = readSettings('spaces', 5); </code></pre>
CPU load from Java <p>Is there a way to get the current cpu load under Java without using the JNI?</p>
<p>Use the <a href="http://java.sun.com/javase/6/docs/api/java/lang/management/ManagementFactory.html"><code>ManagementFactory</code></a> to get an <a href="http://java.sun.com/javase/6/docs/api/java/lang/management/OperatingSystemMXBean.html"><code>OperatingSystemMXBean</code></a> and call <a href="http://java.sun.com/javase/6/docs/api/java/lang/management/OperatingSystemMXBean.html#getSystemLoadAverage%28%29"><code>getSystemLoadAverage()</code></a> on it.</p>
How do I display custom strings when multiple items are selected? <p>I have a property grid that helps me manage all of the controls on a form. These controls are for designer-type folks, so I'm not really worried that much about the user interface... until someone selects multiple objects.</p> <p>I have a UITypeEditor for the "EffectiveDiameter" property on these common objects. It keeps track of units (meters vs feet) and does some nice things on-the-fly. However, when someone selects two or three common objects, EffectiveDiameter is blank, even though it evaluates to the same text string.</p> <p>For example, in most controls, Microsoft has the "Anchor" property that has a text output of "Top, Right". When you pull it down it is an object with a nice UITypeEditor. Yet, when you select five objects on your form that all have the same Anchor setting you can still see the string "Top, Right" in the property grid.</p> <p><code></p> <pre><code>/// &lt;summary&gt; /// The default containing class for all Unit-Management Conversion classes. /// &lt;/summary&gt; [ Serializable, EditorAttribute(typeof(umConversionTypeEditor), typeof(UITypeEditor)), TypeConverter(typeof(umConversionTypeConverter)), ] public class umConversion { ... } public class umConversionTypeEditor : UITypeEditor { ... } // Now, in my designer class, I have ... private double _effectiveDiameter { get; set; } [DisplayName("Effective Diameter")] public virtual umConversion EffectiveDiameter { get { umConversion ret = new umConversion (_effectiveDiameter); ret.MeasureInSI = _si; return ret; } set { _effectiveDiameter = value.ImperialUnits; } } } </code></pre> <p></code></p> <p>If I select several of my custom objects -- all with the same effective diameter -- how do I get EffectiveDiameter to display in the PropertyGrid like Anchor does? Right now, that field is always blank.</p>
<p>Place a <code>TypeConverter</code> attribute on each property too..</p>
Converting indexed polygons to unindexed ones. Several problems have cropped up <p>Yet again I have some questions regarding polygon algorithms.</p> <p>I'll try to explain my problem:</p> <p>I am using a subset of a third party library called Geometric Tools(GT) to perform boolean operations on my polygons. To accomplish this I have to convert my internal polygon format to the format GT uses. </p> <p>Our internal polygon format consists of a vertex array, while the GT polygon consists of an indexed vertex array where each edge is represented by a pair of indices. </p> <p>Example of a square for clarification:</p> <p>Internal format:</p> <pre><code>vertices[0] = Vertex2D(1,0) -&gt; start vertices[1] = Vertex2D(1,1) vertices[2] = Vertex2D(0,1) vertices[3] = Vertex2D(0,0) vertices[4] = Vertex2D(1,0) -&gt; end </code></pre> <p>External format:</p> <pre><code>vertices[0] = Vertex2D(1,0) vertices[1] = Vertex2D(1,1) vertices[2] = Vertex2D(0,1) vertices[3] = Vertex2D(0,0) edges[0] = std::pair&lt;int,int&gt;(0,1) edges[1] = std::pair&lt;int,int&gt;(1,2) edges[2] = std::pair&lt;int,int&gt;(2,3) edges[3] = std::pair&lt;int,int&gt;(3,0) //There is also a BSP tree of the polygon which I don't care to depict here. </code></pre> <p>Now, I wrote an algorithm that works in most cases, but crashes and burns when two edges share the same starting vertex. Let me start by explaining how my current algorithm works.</p> <p>Make a std::map where the key is an integer representing the vertex index. The value represents where in the edge array there is an edge with the key-index as starting index. </p> <p>Mockup example:</p> <pre><code>std::vector&lt; std::pair&lt; int, int &gt; &gt; edge_array; edge_array.push_back( std::pair&lt; int, int &gt;( 0, 1 ) ); edge_array.push_back( std::pair&lt; int, int &gt;( 2, 3 ) ); edge_array.push_back( std::pair&lt; int, int &gt;( 1, 2 ) ); edge_array.push_back( std::pair&lt; int, int &gt;( 3, 0 ) ); std::map&lt; int, int &gt; edge_starts; for ( int i = 0 ; i &lt; edge_array.size(); ++i ) { edge_starts[ edge_array[i].first ] = i; } </code></pre> <p>To jump from correct edge to correct edge i can now just do the following inside a while loop:</p> <pre><code>while ( current_placed_index = first_index_in_polygon ) { int index_to_next_edge_to_be_traversed = edge_starts[ current_edge.second ]; } </code></pre> <p>Inside this loop there is done some optimization, and vertex indices are added to an array.</p> <p>Each time a polygon is closed i find the first untraversed edge and start making another polygon. I keep on doing this until there are no more untraversed edges in the GTPolygon.</p> <p>So each GTPolygon can result in several Polygon(internal) objects.</p> <p>The flaw in this algorithm is evident when there are two edges sharing the same vertex as a starting vertex. Example:</p> <pre><code>&lt;1,2&gt; &lt;1,3&gt; &lt;1,5&gt; </code></pre> <p>When traversing my edges, how will i know which of these edges belongs to the polygon I am currently traversing? I could try traversing the edges BACKWARDS when such a duplicate situation occurs. The problem then would be the possibility of the traversation going back and forth infinitely if another duplicate is found while reversing.</p> <p>My question is, how can I solve this? Is it solvable at all? Can I use the BSP tree to solve this in some way? The amount of corner cases is a bit daunting.</p> <p>Any help is greatly appreciated as 5 months of work depends on this working.</p> <p><strong>Edit:</strong> </p> <p>To clarify: I want to convert from the indexed representation of a polygon that Geometry Tools works with to our internal polygon format, which is just a series of connected vertices in a list.</p>
<p>You are effectively trying to find all <a href="http://en.wikipedia.org/wiki/Cycle%5F%28graph%5Ftheory%29" rel="nofollow">cycles</a> in an <a href="http://www.brpreiss.com/books/opus4/html/page529.html" rel="nofollow">undirected</a> <a href="http://en.wikipedia.org/wiki/Graph%5F%28mathematics%29" rel="nofollow">graph</a> where each cycle represents the edges of a unique polygon. <a href="http://www.me.utexas.edu/~bard/IP/Handouts/cycles.pdf" rel="nofollow">This paper</a> proposes a <a href="http://en.wikipedia.org/wiki/Depth-first%5Fsearch" rel="nofollow">depth-first search (DFS)</a> solution.</p>
Tool to upgrade SQL Express database after deployment <p>I have an app which uses SQL Express and my customers are mainly people who don't have a dedicated IT staff, so wouldn't know how to run scripts. So the deployment and upgrades has to be easy. The deployment part is all figured out. What I need to know is when version 2 of the product comes out and its time to update the database structure or data, is there a better way than the traditional method of scripts. Often times the problem with scripting methods is, you have a development database being used by a bunch of developers and there is not track of who made what changes, so as to be able to incorporate them into the deployment database.</p>
<p>Keep track, or else use a product like Red Gate's Compare tool to generate a script, then have your installer program run the upgrade script. The user will never need to do more than double-click setup.exe.</p>
Multiple versions of .NET CLR running concurrently <p>Let's say I have a .NET user application (.exe) running under Windows that was compiled in .NET Framework Version 3.0 (VS2008). If that application loads another .NET Assembly (.dll) that was compiled on a different computer using .NET Framework Version 2.0 (VS2005), will the loaded assembly use the existing 3.0 runtime (which will run in backwards compatibility mode)? Or will the .NET Framework 2.0 runtime load into the system's process space, and we now have two .NET runtimes running concurrently?</p> <p>Assertion: This is not using VS2008 multi-targeting.</p>
<p>There is no .NET 3.0 CLR. .NET 3.0 and 3.5 both use the .NET 2.0 CLR.</p> <p>Of course, if your .NET 3.0 application uses .NET 3.0 features, then .NET 3.0 will need to be installed.</p>
Save snapshot data to XML <p>I have 5 tables belonging to 2 different datasets, I use them to populate some grids in a page. I want to implement some snapshot functionality and I need to save the data in the tables in an XML in the database. I was thinking of simply serializing the tables to XML using the .Net XmlSerializer (deserializing also), but there is a lot of extra data, basically the table definition and some columns i don't need. My other option is to iterate through the tables and create by hand the XML; the structure is going to be quite complex, and in the page I will have to do the reverse, to iterate through the XML and add the data to the tables to which my grids are bound. How much of a performance penalty would the second approach involve, better to say, would it be noticeable (about 20 datarows per table, each table has about 4 columns)? Also, from other points of view (maintainability), what would you recommend? </p>
<p>With a DataSet, you can create the XML. You already are aware of this, based on your question. If you want to prune the data out a bit, you could build your own XML, but you can also create an XSLT file and transform the XML to the simplified XML you are looking at. It is a one-step process, unlike the looping necessary to create XML or prune out the XML document created.</p>
What is SVN? (PHP) <p>Basically i am quite new to PHP and recently i have had heard quite abit about SVN. After searching (googleing) for it, all i could really find was the SVN functions on the php.net website.</p> <p>Could someone please explain what SVN is, what its used for and is it worth learning? </p> <p>Thanks, Ben</p>
<p>I think you may be wondering how people use Subversion (SVN) in a PHP development environment. </p> <p>At the company I work for we develop PHP on Linux. We use subversion to track changes and help publish changes to live server. With subversion there is no file locking or check-in. Each developer has a working copy of the repository, he then makes changes to the files and commits the changes back to the repository. On our staging server all the changes are merged with the working copy on that server by using subversion update. Subversion merges all changes for each file and if any conflicts happen let's you resolve those conflicts manually. In my experience conflicts are very rare. We then test the app on the staging server. Once the app is tested we use subversion to update the live server in the same way as the staging server. The big benefit in using subversion is the ability to merge changes so that more than one developer can work on the same file. Version control is also a big benefit, since it allows you to revert the application back to a know good working copy with just a few commands, or retrieve a deleted file from a past version.</p>
How to implement Watir classes (e.g. PageContainer)? <p>I'm writing a sample test with Watir where I navigate around a site with the IE class, issue queries, etc.. That works perfectly.</p> <p>I want to continue by using <a href="http://wtr.rubyforge.org/rdoc/classes/Watir/PageContainer.html" rel="nofollow">PageContainer</a>'s methods on the last page I landed on. For instance, using its HTML method on that page.</p> <p>Now I'm new to Ruby and just started learning it for Watir.</p> <p>I tried asking this question on OpenQA, but for some reason the Watir section is restricted to normal members.</p> <p>Thanks for looking at my question.</p> <p><strong>edit:</strong> here is a simple example</p> <pre><code>require "rubygems" require "watir" test_site = "http://wiki.openqa.org/" browser = Watir::IE.new browser.goto(test_site) # now if I want to get the HTML source of this page, I can't use the IE class # because it doesn't have a method which supports that # the PageContainer class, does have a method that supports that # I'll continue what I want to do in pseudo code Store HTML source in text file # I know how to write to a file, so that's not a problem; # retrieving the HTML is the problem. # more specifically, using another Watir class is the problem. Close browser # end </code></pre>
<p>Currently, the best place to get answers to your Watir questions is the <a href="http://groups.google.com/group/watir-genera" rel="nofollow">Watir-General</a> email list.</p> <p>For this question, it would be nice to see more code. Is the application under test (AUT) opening a new window/tab that you were having trouble getting to and therefore wanted to try the PageContainer, or is it just navigating to a second page?</p> <p>If it is the first one, you want to look at <a href="http://wtr.rubyforge.org/rdoc/classes/Watir/IE.html#M000224" rel="nofollow">#attach</a>, if it is the second, then I would recommend reading the <a href="http://wiki.openqa.org/display/WTR/Quick%2BStart" rel="nofollow">quick start tutorial</a>.</p> <p><strong>Edit after code added above:</strong></p> <p>What I think you missed is that <a href="http://wtr.rubyforge.org/rdoc/classes/Watir/IE.html" rel="nofollow">Watir::IE</a> includes the Watir::PageContainer <a href="http://www.ruby-doc.org/core/classes/Module.html" rel="nofollow">module</a>. So you can call <code>browser.html</code> to get the html displayed on the page to which you've navigated.</p>
Oracle tables in one view <p>I have 2 tables in an oracle database, which has the same column-names and types. For example:</p> <p>Table1: id, name, comment<br> Table2: id, name, comment</p> <p>How can I show all data from both table in one view?</p>
<p>If you want 4 separate columns, simply use aliases, like you would any other select.</p> <pre><code>create or replace view vw_my_view as select t1.id t1_id ,t1.comment t1_comment ,t2.id t2_id ,t2.comment t2_comment from table1 t1 inner join table2 t2 on join condition where filter conditions </code></pre> <p><strong>EDIT</strong> Of course, your tables will relate to each other in some way, otherwise there is no way for a single row of your view to mean anything. You will therefore have a join condition to join the two tables, such as t1.id = t2.id</p> <p>If you want them in two columns, use Union</p> <pre><code>create or replace view vw_my_view as select id ,comment from table1 union all -- use ALL unless you want to lose rows select id ,comment from table2; </code></pre>
Converting Excel to PDF with VS2008 and Office2007 <p>I am trying to use Interop.Excell to save an Excel Workbook as a PDF file. I am using VS2008 and Office2007, and have downloaded and installed the SaveAsPDFandXPS.exe from Microsoft. This enabled me to save a Word document as a pdf using the following code: object frmt = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatPDF; wrd.ActiveDocument.SaveAs(ref dest, ref frmt, ref unknown, ref unknown,... Pretty cool excpet for the whole Interop thing.</p> <p>Anyway, I have been unsucsessful in finding a parallel in Interop.Excell for the Word.WdSaveFormat.wdFormatPDF. The Workbook.SaveAs takes a Interop.Excel.XlFileFormat, but there is no option for a pdf format. Has anyone done this or has experience in this area?</p>
<p>This question has been answered here:</p> <p><a href="http://stackoverflow.com/questions/738829/what-is-the-filetype-number-for-pdf-in-excel-2007-that-is-needed-to-save-a-file-a"><strong>What is the FileType number for PDF in Excel 2007 that is needed to save a file as PDF through the API?</strong></a></p> <p>You need to call the <a href="http://msdn.microsoft.com/en-us/library/bb238907.aspx"><code>Workbook.ExportAsFixedFormat</code></a> method:</p> <pre><code>ActiveWorkbook.ExportAsFixedFormat Type:=xlTypePDF FileName:=“sales.pdf” Quality:=xlQualityStandard DisplayFileAfterPublish:=True </code></pre> <p>This method should be preferred over using <code>SaveAs</code> because it also allows specifying all PDF / XPS options.</p> <p>Note: This method has been added to the Excel object model with Excel 2007 and requires the <a href="http://www.microsoft.com/downloads/details.aspx?FamilyID=4d951911-3e7e-4ae6-b059-a2e79ed87041">Save as PDF or XPS Add-in</a> for 2007 Microsoft Office programs (or SP2) to be installed.</p>
Safari force scroll <pre><code>html {overflow-y: scroll;height:101%;overflow-y:hidden;} </code></pre> <p>To force scrolling, when I view one my sites on my Mobile phone the bottom gets cut off, but looks fine in FirefoxF/IE.</p> <p>Any ideas?</p>
<p>It should be enough to say:</p> <pre><code>html { overflow-y: scroll; } </code></pre> <p>but I would also try</p> <pre><code>body { overflow-y: scroll; } </code></pre>
Incompatible pointer type: How can I use a CFType derived object within NSObject derived collection objects? <p>I'm trying to use ABRecordRef within an NSMutableArray, but it doesn't seem to work. I know that ABRecord is a C class, but I thought that ABRecordRef was the work around Objective-C class that allowed me to use it with NSObjects. What do I need to do to make this work?</p>
<p>What do you mean by "Not Working"? As in, you get compile or run-time errors?</p> <p>As I noted in the response to the other poster, you can't use the Objective-C API on the iPhone (There also is no true ABrecord class to brdge to).</p> <p>Generally it's a really good idea with the address book stuff on the iPhone to copy out elements you are interested in, and save the copied values off in something like a dictionary. If you need to save all the elements, you have to have code that reads every value as defined in the AddressBook.h header file, there's no API way to generically walk the records.</p> <p>Also remember that at any time, the user might change the address book if they quit your app and come back - so be careful about what you change after they relaunch the app if you are storing values!!</p>
SWT DropTargetListener has empty event data under Mac OS X <p>I'm currently experiencing a weird platform inconsistency between Mac OS X and Windows/Linux.</p> <p>I've implemented an SWT <code>DropTargetListener</code> and tried to analyze the data dropped in the <code>dragEnter</code> method. Unfortunately, the <code>data</code> attribute of the <code>TransferData</code> contained in the <code>DropTargetEvent</code> parameter is always <code>null</code> on OS X (but becomes valid in <code>DropTargetListener.drop</code> method where it's too late to give user feedback).</p> <p>It works fine under Windows and Linux.</p> <p>Can anybody help me out? Or is this a <em>known</em> limitation of SWT DND under OS X?</p>
<p>Since the <a href="https://bugs.eclipse.org/bugs/buglist.cgi?query%5Fformat=advanced&amp;short%5Fdesc%5Ftype=allwordssubstr&amp;short%5Fdesc=&amp;classification=Eclipse&amp;product=Platform&amp;component=SWT&amp;long%5Fdesc%5Ftype=allwordssubstr&amp;long%5Fdesc=TransferData&amp;bug%5Ffile%5Floc%5Ftype=allwordssubstr&amp;bug%5Ffile%5Floc=&amp;status%5Fwhiteboard%5Ftype=allwordssubstr&amp;status%5Fwhiteboard=&amp;keywords%5Ftype=allwords&amp;keywords=&amp;op%5Fsys=Mac%2BOS%2BX&amp;op%5Fsys=Mac%2BOS%2BX%2B-%2BCocoa&amp;emailtype1=substring&amp;email1=&amp;emailtype2=substring&amp;email2=&amp;bugidtype=include&amp;bug%5Fid=&amp;votes=&amp;chfieldfrom=&amp;chfieldto=Now&amp;chfieldvalue=&amp;cmdtype=doit&amp;order=Reuse%2Bsame%2Bsort%2Bas%2Blast%2Btime&amp;field0-0-0=noop&amp;type0-0-0=noop&amp;value0-0-0=" rel="nofollow">following bugzilla request</a> only returns one old bug, I am not sure it is an active bug when it comes to "TransferData".</p> <p>There is however a lot <a href="https://bugs.eclipse.org/bugs/buglist.cgi?query%5Fformat=advanced&amp;short%5Fdesc%5Ftype=allwordssubstr&amp;short%5Fdesc=&amp;classification=Eclipse&amp;product=Platform&amp;component=SWT&amp;long%5Fdesc%5Ftype=allwordssubstr&amp;long%5Fdesc=Drag&amp;bug%5Ffile%5Floc%5Ftype=allwordssubstr&amp;bug%5Ffile%5Floc=&amp;status%5Fwhiteboard%5Ftype=allwordssubstr&amp;status%5Fwhiteboard=&amp;keywords%5Ftype=allwords&amp;keywords=&amp;op%5Fsys=Mac%2BOS%2BX&amp;op%5Fsys=Mac%2BOS%2BX%2B-%2BCocoa&amp;emailtype1=substring&amp;email1=&amp;emailtype2=substring&amp;email2=&amp;bugidtype=include&amp;bug%5Fid=&amp;votes=&amp;chfieldfrom=&amp;chfieldto=Now&amp;chfieldvalue=&amp;cmdtype=doit&amp;order=Reuse%2Bsame%2Bsort%2Bas%2Blast%2Btime&amp;field0-0-0=noop&amp;type0-0-0=noop&amp;value0-0-0=" rel="nofollow">more bugs declared for DnD on Mac</a> like <a href="https://bugs.eclipse.org/bugs/show%5Fbug.cgi?id=267381" rel="nofollow">this one</a> which comes close to what you are describing.</p> <p>Could you add the exact version of eclipse and its SWT plugin you are using ?</p>
Visual Studio 2005 Build of Python with Debug .lib <p>I am looking for the Visual Studio 2005 build of Python 2.4, 2.5 or 2.6, I also need the python2x_d.lib (the debug version of the .lib) since I embed the interpreter into my app and the python libs implicitly link to the python2x_d.lib with pragmas (grrr).</p> <p>Any hints where I can find those builds ?</p> <p>Regards,</p> <p>Paul</p>
<p>I would recommend that you <a href="http://python.org/download/" rel="nofollow">download the Python source</a> (tgz and tar.bz2 zipped versions available) and compile it yourself. It comes with a VS2005 solution so it isn't difficult. I had to do this for a SWIG project I was working on.</p>
How to call a WCF service from FitNesse <p>When calling a WCF service from a console app, asp.net app, wpf/winform app, you have to have a app.config or web.config file for the WCF service endpoint information. But from FitNesse, I'm calling a fixture which is a .dll (class library) and this fixture is calling my WCF service. It can't call the service because I can't include the endpoint information that it needs - because DLLs can't have app.config files. Any ideas on how to call a WCF service from FitNesse.</p>
<p>Anything you can do with a config in WCF can also be done programmatically. Could you create the endpoints in code and then compile it?</p>
Selecting all empty text fields in Jquery <p>How can I find all text fields that have an empty value?</p> <pre><code>$(":text[value='']") </code></pre> <p>gives a JavaScript error</p> <p>I know I can do <code>$(":text")</code>, iterate through and return all fields with <code>$(this).val()==''</code></p> <p>I am looking for a cleaner method and using JQuery 1.3.1 It has to work if the element originally had a value when the page was loaded, and then the user cleared it. (<code>$("#elem").attr('value')</code> gives the original value in that place, though .val() works properly)</p>
<h2> Latest Answer: Upgrade to 1.3.2 </h2> <p>Here are various tests I ran via FireBug on <a href="http://docs.jquery.com/Downloading_jQuery">http://docs.jquery.com/Downloading_jQuery</a> </p> <p>Different jQuery versions are switched in at page-load with special greasemonkey scripts. </p> <pre><code>&gt;&gt;&gt; jQuery.prototype.jquery "1.3.2" &gt;&gt;&gt; jQuery(":text[value='']") [input#jq-primarySearch] Unknown pseudo-class or pseudo-element 'text'. &gt;&gt;&gt; jQuery(":text[value=]").get() [input#jq-primarySearch] &gt;&gt;&gt; jQuery.prototype.jquery "1.3.1" &gt;&gt;&gt; jQuery(":text[value='']") Syntax error, unrecognized expression: value=''] &gt;&gt;&gt; jQuery(":text[value=]").get() [input#jq-primarySearch] &gt;&gt;&gt; jQuery.prototype.jquery "1.3" &gt;&gt;&gt; jQuery(":text[value='']"); Object length=1 prevObject=Object context=document Unknown pseudo-class or pseudo-element 'text'. [Break on this error] undefined &gt;&gt;&gt; jQuery(":text[value=]").get() [input#jq-primarySearch] </code></pre> <p>Note that 1.3 and 1.3.2 handle it properly ( albeit with Firefox sending an error ) but they still get the node right. </p> <p><strong>Alternatively</strong>: you could use the <code>:text[value=]</code> notation, which appears to work everywhere I tried it. Its just a bit suspect thats all. </p> <p>( Ignore my Previous rantings, they're all bollocks, not having a good day -_-)</p>
WPF DataGrid Button Column Disable <p>Is it possible to disable a button in a DataGridTemplateColumn? I have a DataGridTemplate as follows:</p> <pre><code>&lt;toolkit:DataGridTemplateColumn Header="Timer" Width="50"&gt; &lt;toolkit:DataGridTemplateColumn.CellTemplate&gt; &lt;DataTemplate&gt; &lt;Button Content="Start" Click="Button_Click" CommandParameter="{Binding}" /&gt; &lt;/DataTemplate&gt; &lt;/toolkit:DataGridTemplateColumn.CellTemplate&gt; &lt;/toolkit:DataGridTemplateColumn&gt; </code></pre> <p>The purpose of the Button is to start a timer recorded to the object associated with that row. My timer code works fine but I would also like to disable the buttons of every other row so that you can only have one timer running.</p> <p>I used </p> <p><code>WorkItemGrid.Columns[WorkItemGrid.Columns.Count - 1].GetCellContent(item).IsEnabled = false</code></p> <p>to disable it and all the buttons correctly appear disabled but if you click on the button twice it will reenable and allow you to click on it a third time and trigger the Click event. Is it possible to actually disable the button?</p>
<p>I would have the object the Datagrid is bound to expose a "IsEnabled" boolean property I can bind the button to. Whenever the handler is called, simply get the other object from your original collection and have them change their property to false. This will automatically disable the other buttons.</p> <p>If your are not in control of the "timer" class, you can wrap it in your own class before databinding the grid to the collection of your objects.</p>
surfing with the same CookieContainer <p>How can you surf on a website assigning the same CookieContainer to each web request? </p>
<p>This is a class I wrote a few years back. It's not quite complete and was done before I fully understood how everything works (It doesn't properly encode complex POST data, for example), but it does work pretty well for the all the flaws and it will demonstrate how you can keep your cookiecontainer. It's also in VB.Net, but you can just build that into a separate assembly or run it through a translator if you need to:</p> <pre><code>Imports System.Net Imports System.Collections.Generic Public Class WebScraper Public Sub New() SetUserAgent(UserAgent.IE6SP1) ''//default agent End Sub #Region "Cookies" Private Cookies As New CookieContainer() Public Sub AddCookie(ByVal Name As String, ByVal data As String, Optional ByVal path As String = "", Optional ByVal domain As String = "") Dim ck As New Cookie(Name, data, path, domain) AddCookie(ck) End Sub Public Sub AddCookie(ByRef cookie As Cookie) Cookies.Add(cookie) End Sub Public Sub ResetSession() Cookies = New CookieContainer() ''//TODO: Add other session reset code here End Sub Public Function GetCookies(ByVal uri As System.Uri) As System.Net.CookieCollection Return Cookies.GetCookies(uri) End Function Public Function GetCookies(ByVal url As String) As Net.CookieCollection Dim url2 As Uri = Nothing If Uri.TryCreate(url, UriKind.Absolute, url2) Then Return Cookies.GetCookies(url2) Else Return Nothing End If End Function #End Region Public Property TimeOut() As UInteger Get Return _TimeOut End Get Set(ByVal value As UInteger) _TimeOut = value End Set End Property Private _TimeOut As UInteger = 100000 ''//100000 matches default used by httprequest if none is specified Public Property PageEncoding() As System.Text.Encoding Get Return _PageEncoding End Get Set(ByVal value As System.Text.Encoding) _PageEncoding = value End Set End Property Private _PageEncoding As System.Text.Encoding = System.Text.Encoding.UTF8 #Region "UserAgents" ''// TODO: Update this for FF3, add GoogleBot ''// TODO: Move to separate class with distinct sub-types (eg: UserAgents.IE.6XP or UserAgents.FF.2XP, classes that overload .ToString()) Public Enum UserAgent IE6SP1 IE7_XP IE7_Vista FF2_XP FF2_Vista FF2_Mac FF2_Linux Safari End Enum Public Sub SetUserAgent(ByVal UserAgent As UserAgent) Select Case UserAgent Case WebScraper.UserAgent.FF2_Linux Agent = "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.4) Gecko/20070713 Firefox/2.0.0.5" Case WebScraper.UserAgent.FF2_Mac Agent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en-US; rv:1.8.1) Gecko/20070713 Firefox/2.0.0.5" Case WebScraper.UserAgent.FF2_Vista Agent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.8.1.3) Gecko/20070713 Firefox/2.0.0.5" Case WebScraper.UserAgent.FF2_XP Agent = "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.3) Gecko/20070713 Firefox/2.0.0.5" Case WebScraper.UserAgent.IE6SP1 Agent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)" Case WebScraper.UserAgent.IE7_Vista Agent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)" Case WebScraper.UserAgent.IE7_XP Agent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)" Case WebScraper.UserAgent.Safari Agent = "Mozilla/5.0 (Macintosh; U; Intel Mac OS X; en) AppleWebKit/522.12.1 (KHTML, like Gecko) Safari/522.12.1" End Select End Sub Public Sub SetUserAgent(ByVal UserAgent As String) Agent = UserAgent End Sub ''//defaults to IE6 SP1 ''// TODO: Choose a better default Private Agent As String #End Region #Region "Get Page" Public Function GetPage(ByVal URL As Uri, Optional ByVal PostData As String = "") As String Dim reader As IO.StreamReader = Nothing Try reader = New System.IO.StreamReader(SendRequest(URL, PostData).GetResponseStream, PageEncoding) GetPage = reader.ReadToEnd() Catch GetPage = "" Finally Try reader.Close() Catch End Try End Try End Function Public Function GetPage(ByVal URL As String, Optional ByVal PostData As String = "") As String Dim URL2 As Uri = Nothing If Uri.TryCreate(URL, UriKind.Absolute, URL2) Then Return GetPage(URL2, PostData) Else Return "" End If End Function Public Function GetPage(ByVal URL As String, ByRef PostData As IEnumerable(Of KeyValuePair(Of String, String))) As String Return GetPage(URL, PrepPostData(PostData)) End Function Public Function GetPage(ByVal URL As Uri, ByRef PostData As IEnumerable(Of KeyValuePair(Of String, String))) As String Return GetPage(URL, PrepPostData(PostData)) End Function #End Region #Region "Get Response" Public Function GetResponse(ByVal URL As Uri, Optional ByVal Postdata As String = "") As Object Dim x As HttpWebResponse = SendRequest(URL, Postdata) If x.ContentType.Contains("text") Then Dim result As String Dim reader As IO.StreamReader = Nothing Try reader = New System.IO.StreamReader(x.GetResponseStream, System.Text.Encoding.UTF8) ''// TODO: figure out how to detect actual encoding result = reader.ReadToEnd() Catch result = "" Finally Try reader.Close() Catch End Try End Try Return result ElseIf x.ContentType.Contains("image") Then Dim result As Drawing.Image Try result = System.Drawing.Image.FromStream(x.GetResponseStream) Catch result = Nothing End Try Return result Else Return x.GetResponseStream End If End Function Public Function GetResponse(ByVal URL As Uri, ByRef PostData As IEnumerable(Of KeyValuePair(Of String, String))) As Object Return GetResponse(URL, PrepPostData(PostData)) End Function Public Function GetResponse(ByVal URL As String, ByRef PostData As IEnumerable(Of KeyValuePair(Of String, String))) As Object Return GetResponse(URL, PrepPostData(PostData)) End Function Public Function GetResponse(ByVal URL As String, Optional ByVal PostData As String = "") As Object Dim URL2 As Uri = Nothing If Uri.TryCreate(URL, UriKind.Absolute, URL2) Then Return GetResponse(URL2, PostData) Else Return Nothing End If End Function #End Region #Region "SaveResponseToFile" Function SaveResponseToFile(ByVal FullFileName As String, ByVal URL As Uri, Optional ByVal PostData As String = "") As Boolean Try Dim x As New IO.BinaryReader(SendRequest(URL, PostData).GetResponseStream) Dim y As New IO.FileStream(FullFileName, IO.FileMode.Create) Dim z As New IO.BinaryWriter(y) Try ''// TODO: I can do better here While True z.Write(x.ReadByte) End While Catch ''//continue End Try z.Flush() z.Close() Catch Return False End Try Return True End Function Function SaveResponseToFile(ByVal FullFileName As String, ByVal URL As String, Optional ByVal PostData As String = "") As Boolean Dim URL2 As Uri = Nothing If Uri.TryCreate(URL, UriKind.Absolute, URL2) Then Return SaveResponseToFile(FullFileName, URL2, PostData) Else : Return False End If End Function Function SaveResponseToFile(ByVal FullFileName As String, ByVal URL As String, ByRef PostData As IEnumerable(Of KeyValuePair(Of String, String))) As Boolean Return SaveResponseToFile(FullFileName, URL, PrepPostData(PostData)) End Function Function SaveResponseToFile(ByVal FullFileName As String, ByVal URL As Uri, ByRef PostData As IEnumerable(Of KeyValuePair(Of String, String))) As Boolean Return SaveResponseToFile(FullFileName, URL, PrepPostData(PostData)) End Function #End Region #Region "Get Image" Public Function GetImage(ByVal URL As String) As System.Drawing.Image Try GetImage = System.Drawing.Image.FromStream(SendRequest(URL).GetResponseStream) Catch GetImage = Nothing End Try End Function Public Function GetImage(ByVal URL As Uri) As System.Drawing.Image Try GetImage = System.Drawing.Image.FromStream(SendRequest(URL).GetResponseStream) Catch GetImage = Nothing End Try End Function #End Region #Region "PostToURL" Public Sub PostToURL(ByVal URL As String, Optional ByVal PostData As String = "") SendRequest(URL, PostData) End Sub Public Sub PostToURL(ByVal URL As Uri, Optional ByVal PostData As String = "") SendRequest(URL, PostData) End Sub Public Sub PostToURL(ByVal URL As String, ByRef PostData As Dictionary(Of String, String)) PostToURL(URL, PrepPostData(PostData)) End Sub Public Sub PostToURL(ByVal URL As Uri, ByRef PostData As Dictionary(Of String, String)) PostToURL(URL, PrepPostData(PostData)) End Sub #End Region #Region "Private Methods" Private Function PrepPostData(ByRef PostData As IEnumerable(Of KeyValuePair(Of String, String))) As String PrepPostData = "" ''// TODO: properly encode post data For Each pair As KeyValuePair(Of String, String) In PostData PrepPostData += pair.Key &amp; "=" &amp; pair.Value &amp; "&amp;" Next pair PrepPostData = PrepPostData.Remove(PrepPostData.Length - 1) End Function Private Function SendRequest(ByVal URL As String, Optional ByVal PostData As String = "") As HttpWebResponse Dim URL2 As Uri = Nothing If Uri.TryCreate(URL, UriKind.Absolute, URL2) Then Return SendRequest(URL2, PostData) Else Return Nothing End If End Function Private Function SendRequest(ByVal URL As Uri, Optional ByVal PostData As String = "") As HttpWebResponse Dim Request As HttpWebRequest = HttpWebRequest.Create(URL) Request.CookieContainer = Cookies Request.Timeout = TimeOut Request.UserAgent = Agent If PostData.Length &gt; 0 Then Request.Method = "POST" ''// TODO: allow explicitly setting METHOD and Content-type for request via properties Request.ContentType = "application/x-www-form-urlencoded" Dim sw As New IO.StreamWriter(Request.GetRequestStream()) sw.Write(PostData) sw.Close() End If Return Request.GetResponse() End Function #End Region End Class </code></pre>
Moving Selected rows Between Gridviews <p>I currently have Gridview1 which gets it's data from a database and displays a list of people.I also have a Gridview2 which is initially blank. I would like to add the functionality of adding/removing rows to gridview2 from gridview1. I've added a checkbox column to gridview1 to allow users to select the records they'd like to move. I've also added two buttons >> and &lt;&lt;. Does anyone have an example of how i can add/remove selected records from Gridview1 to Gridview2?</p> <p>thanks in advance!</p>
<pre><code> Gridview2.rows.add(Gridview1.rows[INDEXTOMOVE]); </code></pre>
Append an xml document to an xml node in C#? <p>How can I append an XML document to an xml node in c#?</p>
<p>An <code>XmlDocument</code> <em>is</em> basically an <code>XmlNode</code>, so you can append it just like you would do for any other <code>XmlNode</code>. However, the difference arises from the fact that <em>this</em> <code>XmlNode</code> does not belong to the target document, therefore you will need to use the ImportNode method <em>and then</em> perform the append.</p> <pre><code>// xImportDoc is the XmlDocument to be imported. // xTargetNode is the XmlNode into which the import is to be done. XmlNode xChildNode = xSrcNode.ImportNode(xImportDoc, true); xTargetNode.AppendChild(xChildNode); </code></pre>
ODBC Connection to iSeries Giving Odd Number of Results <p>I'm using UnixODBC with PHP 5.2.4 on Ubuntu 8.04 LTS and trying to pull all the results from a table sitting on an IBM i and replicate them to a local MySQL table. </p> <p>Code-wise it is working with no errors but I'm ending up with more rows that what is contained on the IBM i.</p> <p>I should end up with 25,613 rows but PHP reports that 25,630 rows are being inserted into the MySQL database:</p> <pre><code>$counter = 0; while($row = odbc_fetch_array($result)) { //Insert into MySQL using Zend Framework $counter++; } echo $counter; </code></pre> <p>When I look in the MySQL database some of the rows are actually duplicated. I saw a note on the <a href="http://us.php.net/manual/en/function.odbc-fetch-array.php#76627" rel="nofollow">odbc_fetch_array()</a> documentation about erratic behavior when accessing the IBM i, but trying that solution causes the script to run and run without ever seeming to finish.</p> <p>Any ideas on what to check?</p>
<p>Is it the same rows being duplicated each time? If so, is there anything unique about these records that could hint on why they are duplicated?</p> <p>Perhaps use another binding for getting results -- like <code>odbc_fetch_row()</code>. What does <code>odbc_num_rows()</code> say?</p> <p>These and other techniques might help you zone in on the bug.</p>
Mailing Exception logs in a live Grails webapp <p>I'd like my Grails web-app to send an e-mail for each exception that reaches the end-user.</p> <p>Basically I'm looking for a elegant way to achieve something equivalent to:</p> <pre><code> try { // ... all logic/db-access/etc required to render the page is executed here ... } catch (Exception e) { sendmail("exception@example.com", "An exception was thrown while processing a http-request", e.toString); } </code></pre>
<p>Turns out this exact question was <a href="http://www.nabble.com/How-to-send-email-on-unhandled-exception-td22247616.html" rel="nofollow">answered on the Grails mailing list</a> a couple of days ago.</p> <p>The solution is to add the following to the log4j-section of Config.groovy:</p> <pre><code>log4j { ... appender.mail='org.apache.log4j.net.SMTPAppender' appender.'mail.To'='email@example.com' appender.'mail.From'='email@example.com' appender.'mail.SMTPHost'='localhost' appender.'mail.BufferSize'=4096 appender.'mail.Subject'='App Error' appender.'mail.layout'='org.apache.log4j.PatternLayout' appender.'mail.layout.ConversionPattern'='[%r] %c{2} %m%n' rootLogger="error,stdout,mail" ... // rootLogger="error,stdout" (old rootLogger) } </code></pre> <p>Plus adding sun-javamail.jar and activation.jar to the lib/-folder.</p>
How to get the Join of Two One to Many associations? <p>I have two hibernate entities User and Blog. User can be interested in multiple Tags. Blog can belong to multiple Tags. For a User, How do i find the Blogs which belong to the Tags the User is interested in?</p> <p>I need something like </p> <pre><code>Select * from Blog where Blog.Tags IN User.Tags </code></pre> <p>except that SQL or HQL doesnt allow such comparisons in IN clause</p> <p>A solution which im using currently is: 1. Generate a VIEW USER_BLOGS which is the cartesian product of the join tables USER_TAGS and BLOG_TAGS. 2. Define an Entity UserBlog for the View and use it to filter Blogs in the HQL query:</p> <pre><code>Select * from Blog where Blog.id IN (Select blog_id from UserBlog where user_id = "CurrentUser") </code></pre> <p>Im sure this is a common scenario. Is there a pure Hibernate or HQL solution for this?</p>
<p>Are you looking for something like this?</p> <pre><code>select b.* from blog b join blog_tags bt on bt.blog_id = b.id join user_tags ut on ut.tag = bt.tag where ut.user_id = (this_user) </code></pre> <p>Contrary to the comment, I believe HQL does permit explicit joins (I may be wrong, but see <a href="http://www.hibernate.org/hib_docs/reference/en/html/queryhql-joins.html" rel="nofollow">http://www.hibernate.org/hib_docs/reference/en/html/queryhql-joins.html</a>). It could be done without explicit joins, in any case:</p> <pre><code>select b.* from blog b, blog_tags bt, user_tags ut where ut.user_id = (this_user) and bt.blog_id = b.id and ut.tag = bt.tag </code></pre>
GC.KeepAlive versus using <p>In his <a href="http://www.ai.uga.edu/~mc/SingleInstance.html">article about preventing multiple instances</a> of an application, Michael Covington presents this code:</p> <pre><code>static void Main() // args are OK here, of course { bool ok; m = new System.Threading.Mutex(true, "YourNameHere", out ok); if (! ok) { MessageBox.Show("Another instance is already running."); return; } Application.Run(new Form1()); // or whatever was there GC.KeepAlive(m); // important! } </code></pre> <p>He explains that the GC.KeepAlive(m) is required to prevent the garbage collector from collecting the mutex early, since there are no additional references to it.</p> <p>My question: will wrapping the mutex in a using do the same thing? That is, will the following also prevent the GC from pulling the rug out from under me?</p> <pre><code>static void Main() // args are OK here, of course { bool ok; using (var m = new System.Threading.Mutex(true, "YourNameHere", out ok)) { if (! ok) { MessageBox.Show("Another instance is already running."); return; } Application.Run(new Form1()); // or whatever was there } } </code></pre> <p>My gut reaction is that the using will work, since using is (supposed to be) equivalent to:</p> <pre><code>Mutex m = new System.Threading.Mutex(true, "YourNameHere", out ok); try { // do stuff here } finally { m.Close(); } </code></pre> <p>And I would think that the m.Close() there would be enough to signal to the JIT compiler that there's another reference, thus preventing premature garbage collection.</p>
<p>Wrapping the mutex in a <code>using</code> statement will indeed prevent it from being garbage collected, but will <em>also</em> dispose of it (it calls <code>Dispose</code>, not <code>Close</code>) at the end (whereas <code>GC.KeepAlive</code> won't, obviously).</p> <p>If the end of the method is genuinely going to be the end of the process, I don't believe it's likely to make any practical difference which you use - I prefer the <code>using</code> statement on the general principle of disposing of anything which implements <code>IDisposable</code>.</p> <p>If the mutex hasn't been disposed when the process exits, I suspect its finalizer will take care of it - so long as other finalizers don't hog the finalization thread beyond its timeout.</p> <p>If the finalizer doesn't take care of it, I don't know whether Windows itself will notice that the process can't possibly own the mutex any more, given that it (the process) doesn't exist any more. I suspect it will, but you'd have to check detailed Win32 documentation to know for sure.</p>
How to find a method in assembly code <p>From a memory leak log I have the following info: </p> <p>TestApp.exe! + 2238ch</p> <p>Let us say this means that method at offset '2238c' (hex value) is leaking. </p> <p>How can I locate the corresponding method in my source code? I have the linker map (testapp.map) but not sure how to use it. </p> <p>This is a C++ application compiled in VS2008. </p>
<p>Your map file will have a bunch of entries like these:</p> <pre> 0001:00000070 ??0logic_error@std@@QAE@ABV01@@Z 00401070 f i scratch.obj 0001:000000e0 _main 004010e0 f scratch.obj 0001:00000310 ??1?$list@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@V?$allocator@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@@std@@@std@@QAE@XZ 00401310 f i scratch.obj 0001:00000330 ??1?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@QAE@XZ 00401330 f i scratch.obj 0001:00000360 ?_Buynode@?$list@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@V?$allocator@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@@std@@@std@@IAEPAU_Node@?$_List_nod@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@V?$allocator@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@@std@@@2@XZ 00401360 f i scratch.obj 0001:00000380 ?clear@?$list@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@V?$allocator@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@@std@@@std@@QAEXXZ 00401380 f i scratch.obj 0001:000003f0 ?_Buynode@?$list@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@V?$allocator@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@@std@@@std@@IAEPAU_Node@?$_List_nod@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@V?$allocator@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@@std@@@2@PAU342@0ABV?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@@Z 004013f0 f i scratch.obj 0001:00000480 ?_Incsize@?$list@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@V?$allocator@V?$variant@V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@H_NUvoid_@0detail@boost@@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@U3045@@boost@@@std@@@std@@IAEXI@Z 00401480 f i scratch.obj </pre> <p>This shows you exactly how your code is laid out in memory. e.g. main() starts at E0 and ends at 30F in segment 1.</p> <p>You just need to go through the address list to see where the address you were given lands. One thing to look out for is there are usually multiple segments, but you can usually deduce which one has the code you're interested in.</p>
Inline output document selection using result document in XSLT 2.0 <p>Greetings,</p> <p>I'm looking for a method to do in-line result (output) document selecting in XSLT. I know of the method where one creates an <code>xsl:result-document</code> node to have one transformation apply to multiple documents. Usually this method uses several passes, such as:</p> <pre><code>&lt;xsl:template match="/"&gt; &lt;xsl:apply-templates select="*"/&gt; &lt;xsl:result-document href="test.xml"&gt; &lt;xsl:apply-templates select="*"/&gt; &lt;/xsl:result-document&gt; &lt;/xsl:template&gt; </code></pre> <p>I'm looking for a way to do this inline so I can build two output documents in a single pass. The reason is I have a temporary tree that is built as the transformation is run that I want to output to a file.</p> <pre><code>&lt;xsl:variable name="treeBase"&gt; &lt;Base/&gt; &lt;/xsl:variable&gt; &lt;xsl:template match="/"&gt; &lt;xsl:apply-templates select="*"/&gt; &lt;/xsl:template&gt; &lt;xsl:template match="these_elements"&gt; &lt;xsl:param name="temp" select="$treeBase"/&gt; &lt;/xsl:template&gt; &lt;xsl:template match="not_these_elements"&gt; &lt;xsl:param name="temp" select="$treeBase"/&gt; &lt;xsl:apply-templates select="@*|node()"&gt; &lt;xsl:with-param name="temp"&gt; &lt;Base&gt; &lt;xsl:copy-of select="$temp/Base/*"/&gt; &lt;Item&gt; &lt;xsl:value-of select="ThisItem"/&gt; &lt;/Item&gt; &lt;/Base&gt; &lt;/xsl:with-param&gt; &lt;/xsl:template&gt; </code></pre> <p><strong>Why would you want to do this?</strong> In my XSLT I'm building a temporary tree through recursive parameter calls. I want to output the temporary tree as it is being built to a separate document but still use the temporary tree built for flow of control. With the current method I'd have to run through a complex transformation twice.</p> <p>Is there a way to do this in XSLT or is it single-pass, single-document only?</p> <p>Thanks in advance.</p>
<p><strong>Here is a working example how to do this</strong>:</p> <p><strong>This transformation</strong>:</p> <pre><code>&lt;xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xs="http://www.w3.org/2001/XMLSchema"&gt; &lt;xsl:output omit-xml-declaration="yes" indent="yes"/&gt; &lt;!-- --&gt; &lt;xsl:template match="/*"&gt; &lt;xsl:variable name="vTop" select="."/&gt; &lt;!-- --&gt; &lt;xsl:for-each-group select="num" group-by="xs:integer(.) mod 2"&gt; &lt;xsl:result-document href="file:///C:/Temp/file{position()}.xml"&gt; &lt;xsl:element name="{name($vTop)}"&gt; &lt;xsl:copy-of select="current-group()"/&gt; &lt;/xsl:element&gt; &lt;/xsl:result-document&gt; &lt;/xsl:for-each-group&gt; &lt;/xsl:template&gt; &lt;/xsl:stylesheet&gt; </code></pre> <p><strong>when applied on this XML document</strong></p> <pre><code>&lt;nums&gt; &lt;num&gt;01&lt;/num&gt; &lt;num&gt;02&lt;/num&gt; &lt;num&gt;03&lt;/num&gt; &lt;num&gt;04&lt;/num&gt; &lt;num&gt;05&lt;/num&gt; &lt;num&gt;06&lt;/num&gt; &lt;num&gt;07&lt;/num&gt; &lt;num&gt;08&lt;/num&gt; &lt;num&gt;09&lt;/num&gt; &lt;num&gt;010&lt;/num&gt; &lt;/nums&gt; </code></pre> <p><strong>produces the wanted two files</strong>: <strong><em>file1.xml and file2.xml</em></strong>, which contain, correspondingly, the "num" elements with odd and with even values.</p> <p><strong>Do note</strong> that there are no "multiplr passes" and the code is "inline", as required.</p>
The Art of Computer Programming, Vol 4, Fascicle 2 typo? <p>At the bottom of page 5 is the phrase "changes <i>k</i> to <i>k</i> &oplus; (1<sup><i>j</i>+1</sup>)<sub>2</sub>". Isn't 1 to any power still 1 even in binary? I'm thinking this must be a typo. I sent an email to Dr. Knuth to report this, but I don't expect to hear back for months. In the meantime, I'm trying to figure out what this is supposed to be.</p>
<p>This can be resolved by using the convention that (...)<sub>2</sub> represents a bitwise representation. (1<sup>j+1</sup>)<sub>2</sub> then consists solely of j+1 ones, rather than referring to an exponentiation. You can see this convention explained more explicitly in TAOCP Volume 4 Fascicle 1 at page 8, for example:</p> <blockquote> <p>If x is almost any nonzero 2-adic integer, we can write its bits in the form</p> <p>x = (g01<sup>a</sup>10<sup>b</sup>)<sub>2</sub></p> <p>in other words, x consists of some arbitrary (but infinite) binary string g, followed by a 0, which is followed by a+1 ones and followed by b zeros, for some a >= 0 and b >= 0.</p> </blockquote> <p>[I have substituted the symbol alpha by g to save encoding problems]</p> <p>Going back to your original query; k ⊕(1<sup>j+1</sup>)<sub>2</sub> is equated with k ⊕ (2<sup>j+1</sup> - 1) implying that (1<sup>j+1</sup>)<sub>2</sub> = (2<sup>j+1</sup> - 1): this holds because the left-hand side is the integer whose significant bits are j+1 (contiguous) ones; the right-hand side is an exponentiation. For example, with j =3:</p> <p>(1<sup>4</sup>)<sub>2</sub> = (1111)<sub>2</sub> = (2<sup>4</sup> - 1)</p> <p>Hope that helps.</p>
mxmlc compiles differently under linux and windows? <p>I have a project which has several components loaded by a single preloader swf.</p> <p>The preloader swf is strictly AS3 (No flex) and uses Loaders to load two different swfs which both use the flex library (Statically compiled, not rsl). </p> <p>When I compile all three under linux and run the resulting preloader, one of the swfs fails to load properly, and the exception below (at the bottom of this post) is thrown.</p> <p>If I compile the same component using the same ant task in windows, the component loads just fine without error. The windows file is also 683 bytes smaller.</p> <p>This is true using the flex SDK 3.2.0 and 3.3.0 under linux and windows.</p> <p>Have you seen this type of behavior? Can you offer any suggestions for why it might be happening, or how to determine what is wrong?</p> <pre><code>TypeError: Error #1009: Cannot access a property or method of a null object reference. at mx.managers::FocusManager/activate() at mx.managers::SystemManager/activateForm() at mx.managers::SystemManager/activate() at mx.core::Application/initManagers() at mx.core::Application/initialize() at OC_Footer/initialize() at mx.managers::SystemManager/http://www.adobe.com/2006/flex/mx/internal::childAdded() at mx.managers::SystemManager/initializeTopLevelWindow() at mx.managers::SystemManager/http://www.adobe.com/2006/flex/mx/internal::docFrameHandler() at mx.managers::SystemManager/docFrameListener() </code></pre>
<p>So wait, are you using different version of the SDK in each platform? That would certainly account for some differences (at the very least in the size of the swf...)</p> <p>IIUC you get this error when you're loading the page in the browser, right? It's hard to tell from just the stack trace what's wrong, but I can tell you that I used to get a similar error on Windows and it had to do with keyboard events (e.g. using the tab key to move between elements when popups are visible, and similar stuff). Sorry I can't offer a more accurate diagnosis.</p>
Do asynchronous web service calls always call the AsyncCallback? <p>I'm making asynchronous web service calls from a C# app:</p> <pre><code>{ //Put UI in 'loading' state ... //Now call web service webServiceProxy.BeginMyMethod(param, new AsyncCallback(MyCallback), null); } private void MyCallback(IAsyncResult res) { ... //process result // Put UI back in normal state (yes I'm marshalling back to the UI thread) } </code></pre> <p>The main thread puts the app in a "waiting" mode, and then the end of the Callback function re-enables the controls. I'm seeing a bug that occasionally, the UI is stuck forever in the loading mode.</p> <p>Now there may just be a bug in the callback code (there's quite a bit there), but my question to the community here is this:</p> <p>Is "MyCallback" GUARANTEED to be called? Presuming that "BeginMyMethod" didn't throw an exception, can I be sure that MyCallback will be executed? I'm seeing a "CompletedSynchronously" and "IsCompleted" on the IAsyncResult returned by the BeginXXX functions, but I'm not sure if that's important or not.</p>
<p>Yes, the callback is guaranteed to be called. The callback is what permits asynchronous code using the <code>Begin*</code> / <code>End*</code> pattern to be written in a continuation-passing style.</p> <p>You must call the corresponding <code>End*</code> method in your callback (normally, the first thing in the callback), however. It is how the asynchronous method signals an exception that may have occurred during the call, for one thing, as well as the way to get a result out (if any).</p> <p>Coding the asynchronous pattern using anonymous delegates when using C# 2.0 is sometimes more elegant, and permits writing of the post-call continuation close to the initiation of the call, as well as permitting much easier data sharing through captured variables, providing that appropriate synchronization measures are used.</p> <p>Ref: <a href="http://msdn.microsoft.com/en-us/library/ms228972.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/ms228972.aspx</a>:</p> <blockquote> <p>Applications that can do other work while waiting for the results of an asynchronous operation should not block waiting until the operation completes. Use one of the following options to continue executing instructions while waiting for an asynchronous operation to complete:</p> <ul> <li>Use an AsyncCallback delegate to process the results of the asynchronous operation in a separate thread. This approach is demonstrated in this topic. </li> </ul> <p>[...]</p> </blockquote>
How can I handle fractional quantities in an e-store shopping cart? <p>I am building an e-store and I need to have the ability to add fractional quantities to the shopping cart. </p> <p>Admin would set a denominator per product (e.g. 8 would mean that the minimum purchase is 1/8 of a case)</p> <p>I currently use a <a href="http://jqueryui.com/demos/slider/" rel="nofollow">jQuery slider</a> and display the quantity in the <code>asp:Label</code> which works just fine on product pages, however it gets out of hand with multiple sliders in the cart (I need to allow the customer to adjust quantities in the cart).</p> <p>I really want to stay away from ugly dropdown lists.</p> <p>Any ideas?</p> <h3>EDIT:</h3> <p>Fixed denominator is out of the question ... 4/8 have to show as 1/2 ... </p> <h3>EDIT2:</h3> <p>Usability is important too, + 1/denominator increment per click won't work too well when a customer wants to go from 1/16th of a case to 3 cases</p> <h3>EDIT3:</h3> <p>@RichB: adding a SKU for a fraction of a case goes back to fixed denominator problem. if i add a SKU for 1/16th of a case, and a user wants 1/2 of a case, they would have to order 8x1/16th's [not cool]. If you want to add a SKU for every possible fraction (15 SKUs in this example - this will make my Product page and the CART way to cluttered.</p>
<p>One way would be for you to have your quantity textbox followed by a " / [denominator]" string that would allow them to say something like [4] / 8 to designate half a case of 8.</p> <p>Your only problem there is you're going to having a simple method to keep track of what those denominators are.</p>
Jump to function definition in vim <p>How can i jump to to a function definition using VIM? For example with Visual Assist i can type <kbd>Alt</kbd>+<kbd>g</kbd> under a function and it opens a context menu listing the files with definitions.</p> <p>How can i do something like this in vim?</p>
<p>Use ctags. Generate a tags file, and tell vim where it is using the :tags command. Then you can just jump to the function definition using <kbd>Ctrl</kbd>-<kbd>]</kbd></p> <p>There are more tags tricks and tips in <a href="http://stackoverflow.com/questions/563616/vimctags-tips-and-tricks">this question</a>.</p>
Why does glibc "timezone" global not agree with system time on DST? <p>I'm experiencing a bizarre issue where my system clock knows that it's daylight savings time, but glibc seems not to. This is an up-to-date Ubuntu installation, and I have checked /etc/localtime and it has the correct changeover time for last week's switch to DST.</p> <p>The current correct timezone for me is Pacific Daylight Time (UTC-7). When I ask my system what time zone I'm in, it tells me correctly:</p> <pre><code>$ date +%z -0700 </code></pre> <p>But when I run the following program:</p> <pre><code>#include &lt;time.h&gt; #include &lt;stdio.h&gt; int main() { tzset(); printf("%lu\n", timezone); return 0; } </code></pre> <p>The output is, incorrectly:</p> <pre><code>28800 </code></pre> <p>Which corresponds to UTC-8, or Pacific Standard Time. (And no, TZ is not set in my environment)</p> <p>I thought glibc and the date program would get their time zone information from the same source, but apparently either they don't or I'm misunderstanding how the glibc timezone global works.</p> <p>The basic questions are then:</p> <ol> <li><em>Why are these two outputs different</em></li> <li><em>How can I reliably detect the system UTC offset from a C program?</em></li> </ol>
<p>I don't think "timezone" changes with daylight time. Try the "daylight" variable. On my system:</p> <pre> The external variable timezone contains the difference, in seconds, between UTC and local standard time (for example, in the U.S. Eastern time zone (EST), timezone is 5*60*60). The external variable daylight is non-zero only if a summer time zone adjustment is specified in the TZ environment variable. </pre>
How to create a list from beginning number and end number <p>I have a set of numbers:</p> <pre><code> | A B -------------- 1| 100 102 2| 103 103 3| 104 105 4| 106 110 </code></pre> <p>Column A is the beginning number and Column B is the end number. We need to create a list (on a separate cell) of numbers using the beginning number and end number using column A &amp; B. E.g. based on the 1st set of data from Row 1(A1 &amp; B1) the 1st set of numbers will be: 100,101,102, then it will go to row 2, put 103 after 102 and move on to row 3, expanded the list and display 104 and 105, then to last row where it should list 105,106,107,108,109,110.</p> <p>We should be able to mark the beginning of the number for the list so that we know the start of each list. i.e. all the number listed in Column A should be marked.</p>
<p>Not sure I completely understand your question, but I think you want to turn this:</p> <pre> 100 102 103 103 104 105 106 110 </pre> <p>into this?</p> <pre> 100 102 100, 101, 102 103 103 103 104 105 104, 105 106 110 106, 107, 108, 109, 110 </pre> <p>If so, the following code will achieve this:</p> <pre> Private Sub getListsOfNumbers() Dim inputRange As String Dim x As Long Dim y As Long 'Get input range of data inputRange = InputBox("Enter input range", "Start", "A1:A4") 'Clear output range (two column offset) Range(inputRange).Offset(0, 2).ClearContents With Range(inputRange) 'Loop through input range For x = 1 To .Cells.Count 'Loop through difference between second column and first column For y = 0 To (.Cells(x, 2) - .Cells(x, 1)) 'Add value to output column .Cells(x, 3) = .Cells(x, 3) & (.Cells(x, 1) + y) & ", " Next y 'Tidy up output by removing trailling comma .Cells(x, 3) = CStr(Left(.Cells(x, 3), Len(.Cells(x, 3)) - 2)) Next x End With End Sub </pre> <p>If I've misread your request, please let me know.</p> <p>Edit: Just tried this for real and, with larger datasets, it would be as slow as one might predict. If your data has 100s/1000s of rows, and/or the difference between the numbers in columns A &amp; B is significantly larger than the example, then you'd probably want to look at minimising the delay by turning off calculation and screenUpdating at the beginning of the procedure and restoring once complete.</p> <p>The Excel help has the syntax and examples to help you if you need to implement this.</p>
Replacement for JAXMServlet? <p>I am maintaining an application that has classes (written in 2005) that extend <em>javax.xml.messaging.JAXMServlet</em>. While upgrading to a new app server that implements the latest J2EE standards, I discovered that <em>JAXMServlet</em> was removed in JWSDP 2.0 (Java Web Services Developer Pack), according to <a href="http://www.javaforums.info/java-programming-archive/jaxm-demise-jwsdp-and-t3283.html" rel="nofollow">this question</a> (and apparently JWSDP itself has been <a href="http://java.sun.com/webservices/downloads/previous/index.jsp" rel="nofollow">deprecated</a> too). The code it relies on has not significantly changed since it was written, and is part of a large-ish existing production system where this code is already tested and debugged, so I am reluctant to rewrite the classes from scratch due to the regression testing impact.</p> <p>Is there an 'easy' substitution for this class? Although Google has a lot of examples of using this code (dated from around 2003-2004), it is surprisingly mute about replacing it. Thanks.</p>
<p>Why replace it? Why not find the relevant libraries and use them?</p> <p><a href="http://java.sun.com/webservices/downloads/previous/webservicespack.jsp" rel="nofollow">http://java.sun.com/webservices/downloads/previous/webservicespack.jsp</a></p>
Inputs empty on post-back despite having values <p>I'm using a telerik RadGrid, with a UserControl edit form. When the InsertCommand event fires, I get the user control, and find edit controls on it, but there Text properties are all string.Empty. I suspect this has something to do with ViewState, but I don't know where to begin looking.</p> <pre><code>protected void jobGrid_InsertCommand(object source, GridCommandEventArgs e) { var editControl = e.Item.FindControl(GridEditFormItem.EditFormUserControlID) as JobEditControl; SqlJobProvider.InsertJob(GetFieldValues(editControl)); } private Dictionary&lt;string, object&gt; GetFieldValues(UserControl editControl) { string tb = (editControl.FindControl("aspText") as TextBox).Text; </code></pre>
<p>I believe your controls are empty because you are rebinding the grid before the inserted event. To avoid such behavior I suggest you populate RadGrid using the NeedDataSource event. It is fired whenever the grid needs rebinding.</p>
What is the best practice when implementing a data transfer object or POCO ? How should your POCOs look like? <p>Which of the following is the best way to implement a poco?</p> <p>Option 1:</p> <pre><code>public class PocoOption1 { public PocoOption1(int val1,string val2) { Val1=val1; Val2=val2; } public int Val1{get;private set;} public int Val2{get;private set;} } </code></pre> <p>Option 2:</p> <pre><code>public class PocoOption2 { public int Val1{get;set;} public int Val2{get;set;} } </code></pre> <p>What are the potential pro-cons of each approach?? Does it matter? Some people say that a DTO should be set only once. Is it a rule or just an opinion??</p>
<p>With the new C# syntax where you can do things like:</p> <pre><code>Customer customer = new Customer{ Id = 1, Name="Dave", City = "Sarasota" }; </code></pre> <p>you can safely use Option 2.</p> <p>Please check <a href="http://msdn.microsoft.com/en-us/library/bb384062.aspx" rel="nofollow">here</a>.</p>
Unobtrusive Javascript to insert element that contains a Rails RESTful URL? <p>I have a simple page with a single rendered iFrame. There's a link called "Add File" and unobtrusively I would like to attach an event to the "Add File" anchor so that when clicked, it inserts a new iFrame below the existing one with the ID of the iFrame incremented.</p> <p>An example of the iFrame would be:</p> <pre><code>&lt;iframe name="uploadForm1" id="uploadForm1" src="&lt;%= upload_file_url %&gt;" height="50" width="800" frameborder="0" scrolling="no"&gt;&lt;/iframe&gt; </code></pre> <p>Then when clicking the "Add File" button I would end up with:</p> <pre><code>&lt;iframe name="uploadForm1" id="uploadForm1" src="&lt;%= upload_file_url %&gt;" height="50" width="800" frameborder="0" scrolling="no"&gt;&lt;/iframe&gt; &lt;iframe name="uploadForm2" id="uploadForm2" src="&lt;%= upload_file_url %&gt;" height="50" width="800" frameborder="0" scrolling="no"&gt;&lt;/iframe&gt; </code></pre> <p>What would be the best approach (jQuery or Prototype) to accompish this?</p> <p>It seems very trivial, however, because of the fact that I need to render the upload_file_url route, I'm not too sure how to approach it without wasting a whole lot of time!</p> <p>Any assistance is appreciated!</p>
<p>This should do it for you:</p> <pre><code>var g_maxNum = 1; // The latest iframe number function copyIframe() { // Get the latest iframe var iframe = document.getElementById('uploadForm' + g_maxNum); g_maxNum++ // Create a new iframe by cloning the existing one var newIframe = iframe.cloneNode(true); // Update the properties newIframe.name = 'uploadForm' + g_maxNum; newIframe.id = newIframe.name // Insert it after the last iframe iframe.parentNode.insertBefore(newIframe, iframe.nextSibling); } </code></pre>
DD img different MD5's? <p>We have a smart media card with a linux install on it that we need to duplicate. We created an img with DD and then used dd to write the img back to a couple of new smart media cards. We have compared the MD5 checksum of both the original and the new copies and they are different. </p> <p>Here is what we used:</p> <p>dd if=/dev/sdb of=myimage.img</p> <p>dd if=myimage.img of=/dev/sdb</p> <p>dd if=/dev/sdb of=newimage.img</p> <p>Anyone have any ideas of why these come out different?</p>
<p>If the cards are different sizes, dd'ing the smaller image to a larger card will not "fill it up", and zeros will remain at the end of the card. An image made from this card will be different than the original image.</p> <p>It's also always possible that data was mis-written, mis-read, or otherwise corrupted in-transit. </p>
does adding new member function into d pointer class break binary compatibility? <p>Will adding new member function into d pointer class definition break binary compatibility?</p> <p>For example, will the new definition below break binary compatibility compared to the original? (side question, is there a tool that will tell me if a new .so breaks binary compatibility compared to the old .so? If not, how do I check manually?)</p> <p>Original:</p> <pre><code>#ifndef __TESTBC_H__ #define __TESTBC_H__ class APrivate; class A { public: int get() { d-&gt;update(); return _d-&gt;get(); } private: APrivate *_d; }; class APrivate { public: int get() { return _val; } void update() { _val = 1; } private: int _val; }; #endif </code></pre> <p>New:</p> <pre><code>#ifndef __TESTBC_H__ #define __TESTBC_H__ class APrivate; class A { public: int get() { _d-&gt;update(); return _d-&gt;get(); } private: APrivate *_d; }; class APrivate { public: int get() { return _val; } void update() { _val = 1; multiply(); } void multiply() { _val = _val * 10; } private: int _val; }; #endif </code></pre> <p>FYI: I understand d pointer class should be specified in the cc file instead of header. above example is contrived to focus on binary compatibility issue.</p>
<p>No it does not.</p> <p>You should understand how C++ builds its objects.</p> <p>In your case it is just almost "POD" class with non-virtual member functions. These functions do not affet the representation of object in memory. Thus new version is binary compatible with old.</p> <p>More then that, if you do not expose your "APrivate" class to user. (Not giving a header just forward declaration), you would not brake an API even if you do much bigger changes.</p> <p>Meaning:</p> <pre><code>#ifndef YOUR_PUBLIC_API #define YOUR_PUBLIC_API class bar; class foo { public: // member functions using bar private: bar *bar_; }; #endif </code></pre> <p>You do not even expose <code>bar</code> so you may change it in any way you wish. it is the best way to make C++ libraries ABI compatible.</p>
Calling a method and waiting for a return value <p>How do I call a method that returns a bool, but inside that method in order to determine the value of the bool, it calls a web service asyncronously? </p> <pre><code>bool myBool = GetABoolean(5); public bool GetABoolean(int id) { bool aBool; client.CallAnAsyncMethod(id); // value is returned in a completed event handler. Need to somehow get that value into aBool. return aBool; // this needs to NOT execute until aBool has a value } </code></pre> <p>So what I need is for the GetABoolean method to wait until CallAnAsyncMethod has completed and returned a value before returning the bool back to the calling method.</p> <p>I'm not sure how to do this.</p>
<p>Most asyncronous methods return IAsyncResult.</p> <p>If yours does, you can use the IAsyncResult.AsyncWaitHandle to block (IAsyncResult.AsyncWaitHandle.WaitOne) to block until the operation completes.</p> <p>ie:</p> <p><code><pre> bool aBool;</p> <p>IAsyncResult res = client.CallAnAsyncMethod(id); res.AsyncWaitHandle.WaitOne(); // Do something here that computes a valid value for aBool! return aBool; </pre></code></p>
When learning Ruby on Rails, should I focus on just learning Rails or learn associated technologies along with it? <p>I'm planning on taking the time to actually learn Ruby on Rails in-depth (I've previously done some very minor dabbling with it) so I can hopefully reinvent myself as a Rails developer.</p> <p>The issue I run into though is that there are a fair bit of related technologies that are currently used in the Rails community, and I'm not sure if I should learn the whole shebang or focus on learning Rails with the defaults first, and then branch out into the additional stuff.</p> <p>For example:</p> <ul> <li>Templates. I took a look at <strong>Haml</strong> and it looks really cool (shouldn't be hard to learn either).</li> <li>Testing. I've wanted to learn test driven development for a while now, but the "next big thing" in Rails-land seems to be behavior driven development with <strong>RSpec</strong></li> <li>Javascript. I'm not sure if I should stick with <strong>RJS</strong> or use something like <strong>jQuery</strong> which seems to be converting people.</li> <li>I've never really used version control much. Rails seems to be using <strong>Git</strong> for most of it's projects.</li> </ul> <p>Basically I want to learn Rails "right", but there seems to be a lot of different ways that I could go. Should I ignore the "variants" and focus on the Core stuff until I've written an application or three (e.g. core, unmodified Rails; RJS w/Prototype and Scriptaculous for Ajax, regular Test::Unit for testing, ERB for templating, Git for version control), or should I try to pick up some of the variants along the way?</p>
<p>If you want to do well in the rails world you should plan on learning (and relearning) things on a regular basis. It isn't as hard as it might sound, but it is important. I'd suggest you make a list of things to learn, and just work your way down it doing by getting an hour or so of hands-on-time with something new each day. If you feel like there's more to learn (or that the subject is in flux) throw it back on the tail of the list to revisit another day.</p> <p>A starter list (yours plus a few you didn't mention), in no particular order:</p> <ul> <li>erb</li> <li>gems</li> <li>acts_as...</li> <li>test driven development</li> <li>git</li> <li>rspec &amp; behavior driven testing</li> <li>javascript</li> <li>prototype.js</li> <li>jquery</li> <li>sql</li> <li>rail's finders</li> <li>rake</li> <li>the rails console</li> <li>plain old ruby</li> <li>duck typing</li> <li>ruby's metaprogramming facilities (how the magic is done)</li> <li>css</li> <li>rails generators</li> </ul> <p>And so on and so forth. As you're going through one and come across something interesting, throw it on the list.</p> <p>The point is, if you try to take a narrow view you will probably make life harder on yourself and learn slower than if you make a commitment to perpetually, steadily expanding your horizons.</p>
How do you make a webpage change its width automatically? <p>In HTML, is there a way to make a webpage expand to the user's monitor? Like say I have a 15inch, but someone else has a 24 inch. The webpage would be small on their screen, but would fit on min. How would I make the page expand to 100%, or maybe 95%?</p>
<p>Fluid-width is achieved by using percentage units or em units. It's all about crafting a site layout based on grids and containers. <a href="http://www.maxdesign.com.au/presentation/liquid/" rel="nofollow">Read more</a>.</p>
Finding out what caused equals() to return false <p>How can I find out what caused equals() to return false?</p> <p>I'm not asking about a sure-way, always right approach, but of something to aid in the development process. Currently I have to step into the equals() calls (usually a tree of them) until one of them is false, then step into it, ad nauseam.</p> <p>I thought about using the object graph, outputting it to xml and comparing the two objects. However, XMLEncoder requires default constructors, jibx requires pre-compilation, x-stream and simple api are not used in my project. I don't mind copying a single class, or even a package, into my test area and using it there, but importing a whole jar for this just isn't going to happen.</p> <p>I also thought about building an object graph traverser myself, and I might still do it, but I'd hate to start dealing with special cases (ordered collections, non-ordered collections, maps...)</p> <p>Any idea how to go about it?</p> <p>Edit: I know adding jars is the normal way of doing things. I know jars are reusable units. However, the bureaucracy needed (at my project) for this doesn't justify the results - I'd keep on debugging and stepping into.</p>
<p>It's presumably not a full graph comparison... unless your equals include every property in each class ... (you could try == :))</p> <p>Try <a href="http://code.google.com/p/hamcrest/" rel="nofollow">hamcrest matchers</a> - you can compose each matcher in an "all of" matcher:</p> <pre><code>Matcher&lt;MyClass&gt; matcher = CoreMatchers.allOf( HasPropertyWithValue.hasProperty("myField1", getMyField1()), HasPropertyWithValue.hasProperty("myField2", getMyField2())); if (!matcher.matches(obj)){ System.out.println(matcher.describeFailure(obj)); return false; } return true; </code></pre> <p>It will say things like: 'expected myField1 to have a value of "value" but was "a different value"'</p> <p>Of course you can inline the static factories. This is a bit heavier than using <a href="http://commons.apache.org/lang/api/org/apache/commons/lang/builder/EqualsBuilder.html" rel="nofollow">apache-commons EqualsBuilder</a>, but it does give you an accurate description of exactly what failed.</p> <p>You can create your own specialised matcher for quickly creating these expressions. It would be wise to copy <a href="http://commons.apache.org/lang/api/org/apache/commons/lang/builder/EqualsBuilder.html" rel="nofollow">apache-commons EqualsBuilder</a> here.</p> <p>BTW, the hamcrest basic jar is 32K (including source!) giving you the option of reviewing the code and saying to your bosses "I'll stand by this as my own code" (which I presume is your import problem).</p>
EJBs and Storing Objects in a Data Structure (Map, List, etc) <p>Is it possible to have objects stored in a data structure for the duration of an App Server's uptime? Basically I want an EJB that interfaces with this Data Structure, but does not require a full fledged database solution.</p> <p>As an example I made this dummy animal object:</p> <pre><code>package com.test.entities; public class Animal implements java.io.Serializable { private static final long serialVersionUID = 3621626745694501710L; private Integer id; private String animalName; public Integer getId() { // TODO Auto-generated method stub return id; } public void setId(Integer id){ this.id=id; } public String getAnimalName(){ return animalName; } public void setAnimalName(String animalName){ this.animalName=animalName; } } </code></pre> <p>So here is the <strong>EJB Remote</strong> Interface:</p> <pre><code>package com.test.beans; import java.util.Map; import javax.ejb.Remote; import com.test.entities.Animal; @Remote public interface MapBeanRemote { public void addAnimal(Animal a); public void removaAnimal(Integer id); public Animal getAnimalById(Integer id); Map&lt;Integer, Animal&gt; getAllAnimals(); } </code></pre> <p>Here is the Session Bean:</p> <pre><code>package com.test.beans; import java.util.ConcurrentHashMap; import java.util.Map; import javax.annotation.PostConstruct; import javax.ejb.Stateless; import com.test.entities.Animal; @Stateless(mappedName="ejb/MapBean") public class MapBean implements MapBeanRemote{ Map&lt;Integer, Animal&gt; animalStore; @PostConstruct public void initialize(){ animalStore = new ConcurrentHashMap&lt;Integer,Animal&gt;(); } @Override public void addAnimal(Animal a) { if(a.getId()!=null){ animalStore.put(a.getId(), a); } } @Override public Animal getAnimalById(Integer id) { return animalStore.get(id); } @Override public void removaAnimal(Integer id) { animalStore.remove(id); } @Override public Map&lt;Integer, Animal&gt; getAllAnimals() { return animalStore; } } </code></pre> <p>So basically I want any client who wants to manipulate the Animal Map to go through this EJB and have each client accessing the same exact Map of objects.</p> <p>This example does not work good enough. After a while all of the animals are erased (I'm assuming when the EJB gets replaced from the bean pool) Could this somehow be injected as a resource?</p>
<p>This can be accomplished by putting the Map in a Singleton and accessing this singleton from the beans. That way there is a single instance for all the EJB instances (since they share the same classloader). Different Session beans in different EAR's would not work though as they would each have their own classloader, but that doesn't appear to be your scenario.</p> <p>Your existing usage of ConcurrentHashMap will sufficiently handle most of your cases but you still need synchronization around the addAnimal method since you need the map to be consistent between the two method calls.</p>
Java Component.show() / hide() are deprecated ... why? <p>Anyone know the reason (just curious)</p>
<p>JDK 1.1 introduced Java Beans. Java Beans rely in reflection and introspection to determine what the properties of a Bean are (a Bean is a "component"). Properties are then displayed in a Property Sheet. </p> <p>By default beans use the following foormat:</p> <pre><code>boolean isXXX() &lt;type&gt; getXXX() void setXXX(&lt;type&gt;) </code></pre> <p>(going from memory on these next two... they are for indexed properties)</p> <pre><code>&lt;type&gt; getXXX(int) void setXXX(&lt;type&gt;, int) </code></pre> <p>You can override the defaults, but rather than do that most things just rely on the naming pattern.</p> <p>So show/hide didn't conform to the naming pattern and were replaced with setVisible(boolean) which did.</p>
Silverlight MessageBox.Show blocking WCF service call in BackgroundWorker <p>When a MessageBox is being displayed from Silverlight, any calls to a WCF service being executed in a BackgroundWorker are blocked. The OpenFileDialog.ShowDialog allows these calls to go through. Is the browser (IE7) blocking network access during a MessageBox? </p> <p>We can create our own modal window, but this causes developer code to change as it must be asynchronous. (developer code does not stop while custom "MessageBox" is displayed)</p> <p>Any ideas how to work around this?</p>
<p>Can you design your application in such a way as to avoid the use of a modal messagebox? Perhaps use a Popup - you can make these act as a modal dialog by covering the entire app in a grid and forcing keyboard navigation to cycle within the popup.</p> <p>See <a href="http://wildermuth.com/2008/05/01/Creating%5Fa%5FPseudo-Dialog%5Fwith%5FSilverlight%5Fs%5FPopup%5FControl.aspx" rel="nofollow">Shawn Wildermuth's page</a> for all the details.</p>
Is there any Java equivalent of PHP's http_build_query function? <p>I have a Map with my data and want to build a query string with it, just like I would with http_build_query on PHP. I'm not sure if this code is the best implementation of it or if I'm forgetting something?</p> <pre><code>public String toQueryString(Map&lt;?, ?&gt; data) throws UnsupportedEncodingException { StringBuffer queryString = new StringBuffer(); for (Entry&lt;?, ?&gt; pair : data.entrySet()) { queryString.append ( URLEncoder.encode ( (String) pair.getKey (), "UTF-8" ) + "=" ); queryString.append ( URLEncoder.encode ( (String) pair.getValue (), "UTF-8" ) + "&amp;" ); } if (queryString.length () &gt; 0) { queryString.deleteCharAt ( queryString.length () - 1 ); } return queryString.toString (); } </code></pre>
<p>look at the <a href="http://code.google.com/p/workingonit/source/browse/addenda/src/main/java/org/workingonit/addenda/http/QueryStringBuilder.java" rel="nofollow">QueryStringBuilder</a> class and its <a href="http://code.google.com/p/workingonit/source/browse/addenda/src/test/java/org/workingonit/addenda/http/QueryStringBuilderTest.java" rel="nofollow">test class</a> :</p> <pre><code>private String httpBuildQuery(Map&lt;String, String&gt; data) throws UnsupportedEncodingException { QueryStringBuilder builder = new QueryStringBuilder(); for (Entry&lt;String, String&gt; pair : data.entrySet()) { builder.addQueryParameter(pair.getKey(), pair.getValue()); } return builder.encode("UTF-8"); } </code></pre>
What scenarios are possible where the VS C# compiler would not compile a reference of a reference? <p>I'm probably asking this question wrong (and that may be why Google isn't helping), but here goes:</p> <p>In Visual Studio I am compiling a C# project (let's call it Project A, the startup project) which has a reference to Project B. Project B has a reference to a Project C, so when A gets built, the dlls for B gets placed in the bin directory of A, as does the dll for C (because B requires C, and A requires B). However, I have apparently made some change recently so that the dll for Project C does not go into the bin directory of Project A when rebuilding the solution. I have no idea what I've done to make this happen. </p> <p>I have not modified the setup of the solution itself, and I have only added additional references to the project files. Code wise, I have commented out most of the actual code in Project B that references classes in Project C, but did not remove the reference from the project itself (I don't think this matters). I was told that perhaps the C# compiler was optimizing somehow so that it was not building Project C, but really I'm out of ideas. I would think someone has run into something similar before</p> <p>Any thoughts? Thanks!</p>
<p>Have you changed your build configuration? In Visual Studio 2008, the default Solution Configurations are Debug and Release while the default Solution Platform is Any CPU. My experience suggests the Solution Configuration/Platform pair has a unique build configuration. In other words, <em>Debug/Any CPU</em> and <em>Release/Any CPU</em> are two independent build configurations, each with their own settings. If you've selected a different configuration, the settings for the original configuration do not automatically apply; you'll need to set the dependencies for all of your configurations, as well as any new projects you add to your solution, in order to seemlessly switch between them.</p>
Mac OSX - Xcode Installation Directory <p>After Xcode has finished building is there a way to make it copy the executable to specific directory</p> <blockquote> <p>~/Sites/cgi-bin/</p> </blockquote> <p>I have the target <code>Installation Directory</code> set to the correct folder, with <code>skip installation</code> <strong>unchecked</strong>, but no luck.</p> <p>Is there something i'm missing?</p>
<p>Check the "Deployment Postprocessing" build setting in your target's Release configuration. Installation is normally done only with a command-line xcodebuild install, but setting Deployment Postprocessing makes it install on every build.</p> <p>Ensure your user account has write privileges in the directory you want to install in, because the IDE normally doesn't run with root privileges. </p>
Register DLL in GAC without Assembly Manifest <p>I have a DLL I wish to register with my GAC. I enter the command:</p> <pre><code>gacutil /i c:\temp\msvcr100.dll </code></pre> <p>and I get the error: <PRE>Failure adding assembly to the cache: The module was expected to contain an as sembly manifest.</PRE></p> <p>All I have is the DLL. Is there a way to create / fake / bypass it?</p> <p>For those interested, I am attempting to extract the Visual Studio 2010 &amp; .NET 4.0 CTP from the VHD and run it on my physical box. As a side note, has this been attempted?</p>
<p>Is this actually a GAC-able DLL? It doesn't seem like it. Maybe it's just reg-able? Why do you want to GAC it?</p>
Best UI Library to use with jQuery <p>What do you guys recommend for a UI library to use with jQuery. <a href="http://jqueryui.com/">jQuery UI</a> seems to have less widgets compared to other frameworks. I've been playing around lately with the <a href="http://www.dojotoolkit.org/">Dojo Toolkit</a> which seems pretty nice so far, and I know that there is always the <a href="http://developer.yahoo.com/yui/">Yahoo! User Interface</a>, but is there anything else? </p> <p>I also need to consider licensing, something that can be distributed with Open Source software licensed under the BSD license as well as internal-use software.</p>
<p>Those other "ui libraries" depend on entire other frameworks. If you're using Prototype, choose Scriptaculous. If you're using Dojo, use Dijit.</p> <p>If you're using jQuery, really, use jQuery UI. You can style the jQuery UI "widgets" a number of different ways; take a look at the Theme Roller Gallery: <a href="http://themeroller.com/" rel="nofollow">http://themeroller.com/</a></p> <p>What do you mean by lack of maturity and polish?</p>
AJAX not working with ASP.NET HTTP Handler <p>I'm doing something stupid, I suppose. I swear I've done this before without issues but right now I can't get it to work. I have an HTTP handler written in ASP.NET that I want to invoke via AJAX (using jQuery). In my web.config, I register the handler like this...</p> <pre><code> &lt;httpHandlers&gt; &lt;add verb="GET" path="~/getPage.axd" type="Handlers.GetPage"/&gt; &lt;/httpHandlers&gt; </code></pre> <p>The handler is just setup to test right now...</p> <pre><code>Namespace Handlers Public Class GetPage Implements IHttpHandler Public Sub ProcessRequest(ByVal context As System.Web.HttpContext) Implements System.Web.IHttpHandler.ProcessRequest With context.Response .Clear() .Write("ID: " &amp; context.Request.QueryString("id")) .End() End With End Sub Public ReadOnly Property IsReusable() As Boolean Implements System.Web.IHttpHandler.IsReusable Get Return False End Get End Property End Class End Namespace </code></pre> <p>And I have the following jQuery to invoke it...</p> <pre><code>$.get('http://localhost:81/getPage.axd?id=0', function(data) { alert(data); }); </code></pre> <p>I know the URL used to make the request is correct. IIS is setup to route the axd path to the ASP.NET ISAPI filter. I have verified that my handler is <em>not</em> getting invoked (I changed handler to print log message and nothing was printed. Event viewer shows nothing).</p> <p>Any ideas?</p> <p><strong>EDIT:</strong> When I try to navigate directly to the handler in the browser, I get a 404 error.</p>
<p>Got it. I had my path wrong in web.config</p> <pre><code>&lt;httpHandlers&gt; &lt;add verb="GET" path="getPage.axd" type="Handlers.GetPage"/&gt; &lt;/httpHandlers&gt; </code></pre>
wxPython or pygame for a simple card game? <p>I have been playing around with writing some simple card games in Python for fun and I would like to add a graphical user interface (GUI) to the games. Which library would you recommend for writing the GUI for a simple card game?</p>
<p>If all you want is a GUI, wxPython should do the trick.</p> <p>If you're looking to add sound, controller input, and take it beyond a simple card game, then you may want to use pygame.</p>
Powershell Add-Content <p>So Im being a bit anal here but I cant get add-content to add both a string and the output of a cmdlet so it would look something like this;</p> <pre><code>Add-content -path $logfile -value "This is my text"+(Get-Date) </code></pre> <p>I realise I can just add another line to set a variable to the result of get-date but and then pass the variable into my add-content command but I just wondered if I could do it in a single line, like a said Im being anal lol</p> <p>Cheers</p> <p>Andy</p>
<p>Try <code>"This is my text $(Get-Date)"</code></p> <p>In PowerShell, strings in double quotes can contain variables and expressions. If it's not a simple expression (e.g. <code>"This is a $value"</code>), then you need to wrap the expression in <code>$()</code> (e.g. <code>"This is a $($value + 1)"</code>).</p> <p>Note that strings in single quotes are "verbatim strings" and do not allow escape characters or expressions.</p>
Lowercase constraint - Sql Server <p>I'm not sure if this should be a constraint or not, but I want the "UserName" column of a table to ignore the value that is set when an insert or update is executed and instead, store the value of "DisplayUserName" column converted to lowercase. And if "DisplayUserName" is changed, "UserName" should be updated as well to "DisplayUserName" lowered.</p> <p>Thanks!</p>
<p>it sounds like you're looking for a computed column. Something like:</p> <pre><code>CREATE TABLE [dbo].[SampleTable]( [ID] [int] IDENTITY(1, 1) NOT NULL, [DisplayUserName] [varchar](100) NOT NULL, [UserName] AS (lower([DisplayUserName])) ) ON [PRIMARY] </code></pre> <p>This way, you would never have to set the UserName, it is by definition the lowercase value from DisplayUserName.</p>
"Access Denied" when trying to connect to remote IIS server - C# <p>I receive an "Access Deined" COMException when I try to connect to a remote IIS 6 server from my C# application that is running under IIS 5.1.</p> <p>Any ideas? I am experiencing all the same issues with the original questions.</p> <p><b>Update - 4/1/09</b></p> <p>I found this solution (<a href="http://www.codeproject.com/KB/cs/Start_Stop_IIS_Website.aspx" rel="nofollow">http://www.codeproject.com/KB/cs/Start_Stop_IIS_Website.aspx</a>) that consists of a window application connecting to an IIS server to start and stop web sites. I am able to run it on my workstation and connect to the IIS server.</p> <p>Ugh....why can I run this stand alone application but not my ASP.NET application?</p> <p><b>Original</b></p> <p>I receive an "Access Denied" COMException when I try to connect to IIS from a remote machine using the DirectoryEntry.Exist method to check to see if the IIS server is valid.</p> <pre><code>string path = string.Format("IIS://{0}/W3SVC", server); if(DirectoryEntry.Exist(path)) { //do something is valid.... } </code></pre> <p>I am a member of an active directory group that has been added to the Administrators groups to the IIS server I am trying to connect to.</p> <p>Has anyone experience this issue and know how to resolve it?</p> <p><b>UPDATE:</b> </p> <p>@Kev - It is an ASP.NET application. Also, I can connect without an username and password to the remote server through IIS6 Manager.</p> <p>@Chris - I am trying to connect to the remote server to display the number of virtual directorys and determine the .NET framework version of each directory. See <a href="http://stackoverflow.com/questions/636569/how-do-i-determine-the-asp-net-version-of-a-virtual-directory-or-website-using-c">this</a> SO question.</p> <p>@dautzenb - My ASP.NET application is running under IIS 5.1 trying to connect to an IIS 6 server. I can see fault audits in the security log for my local ASPNET account on the remote server. When I try to debug the application, I am running under my domain account and still get the Access is denied.</p> <p><b>UPDATE 2:</B></p> <p>@Kev - I was able to establish to create a DirectoryEntry object using the following overload:</p> <pre><code>public DirectoryEntry ( string path, string username, string password ) </code></pre> <p>But, all of the properties contain a " threw an exception of type 'System.Runtime.InteropServices.COMException'" while I debug the app.</p> <p>Also, the AuthenticationType property is set to Secure.</p> <p><b>UPDATE 3:</b></p> <p>The following two failure audit entries were in the remote IIS server's security event log every time I tried to establish a connection:</p> <p>First event:</p> <p>Event Category: Account Logon<br /> Event ID: 680<br /> Log attempt by: MICROSOFT_AUTHENTICATION_PACKAGE_V1_0<br /> Logon account: ASPNET<br /> Source Workstation: <br /> Error Code: 0xC0000234<br /></p> <p>Second event:</p> <p>Event Category: Logon/Logoff<br /> Event ID: 529<br /> Logon Failure:<br /> Reason: Unknown user name or bad password<br /> User Name: ASPNET<br /> Domain: (MyDomain)<br /> Logon Type: 3<br /> Logon Process: NtLmSsp<br /> Authentication Package: NTLM<br /> Workstation Name: (MyWorkstationId)<br /> Caller User Name: -<br /> Caller Domain: -<br /> Caller Logon ID: -<br /> Caller Process ID: -<br /> Transited Services: -<br /> Source Network Address: 10.12.13.35<br /> Source Port: 1708<br /></p> <p>Impersonation is set to true and the username and password are blank. It is using the ASPNET account on the remote IIS server.</p>
<p>If it is an identity problem, you could try setting your IIS 5.1 application to use <a href="http://www.microsoft.com/technet/prodtechnol/WindowsServer2003/Library/IIS/5f8fe119-4095-4094-bba5-7dec361c7afe.mspx?mfr=true" rel="nofollow">Integrated Windows Authentication</a>, and then add the following to you web.config on your IIS5.1 web site under system.web to enable <a href="http://msdn.microsoft.com/en-us/library/72wdk8cc%28VS.71%29.aspx" rel="nofollow">impersonation</a>.</p> <pre><code>&lt;identity impersonate="true"/&gt; &lt;authentication mode="Windows" /&gt; </code></pre>
Java: Reading a pdf file from URL into Byte array/ByteBuffer in an applet <p>I'm trying to figure out why this particular snippet of code isn't working for me. I've got an applet which is supposed to read a .pdf and display it with a pdf-renderer library, but for some reason when I read in the .pdf files which sit on my server, they end up as being corrupt. I've tested it by writing the files back out again.</p> <p>I've tried viewing the applet in both IE and Firefox and the corrupt files occur. Funny thing is, when I trying viewing the applet in Safari (for Windows), the file is actually fine! I understand the JVM might be different, but I am still lost. I've compiled in Java 1.5. JVMs are 1.6. The snippet which reads the file is below.</p> <pre><code>public static ByteBuffer getAsByteArray(URL url) throws IOException { ByteArrayOutputStream tmpOut = new ByteArrayOutputStream(); URLConnection connection = url.openConnection(); int contentLength = connection.getContentLength(); InputStream in = url.openStream(); byte[] buf = new byte[512]; int len; while (true) { len = in.read(buf); if (len == -1) { break; } tmpOut.write(buf, 0, len); } tmpOut.close(); ByteBuffer bb = ByteBuffer.wrap(tmpOut.toByteArray(), 0, tmpOut.size()); //Lines below used to test if file is corrupt //FileOutputStream fos = new FileOutputStream("C:\\abc.pdf"); //fos.write(tmpOut.toByteArray()); return bb; } </code></pre> <p>I must be missing something, and I've been banging my head trying to figure it out. Any help is greatly appreciated. Thanks.</p> <p><hr /></p> <p><strong>Edit:</strong> To further clarify my situation, the difference in the file before I read then with the snippet and after, is that the ones I output after reading are significantly smaller than they originally are. When opening them, they are not recognized as .pdf files. There are no exceptions being thrown that I ignore, and I have tried flushing to no avail. </p> <p>This snippet works in Safari, meaning the files are read in it's entirety, with no difference in size, and can be opened with any .pdf reader. In IE and Firefox, the files always end up being corrupted, consistently the same smaller size. </p> <p>I monitored the len variable (when reading a 59kb file), hoping to see how many bytes get read in at each loop. In IE and Firefox, at 18kb, the in.read(buf) returns a -1 as if the file has ended. Safari does not do this.</p> <p>I'll keep at it, and I appreciate all the suggestions so far.</p>
<p>Just in case these small changes make a difference, try this:</p> <pre><code>public static ByteBuffer getAsByteArray(URL url) throws IOException { URLConnection connection = url.openConnection(); // Since you get a URLConnection, use it to get the InputStream InputStream in = connection.getInputStream(); // Now that the InputStream is open, get the content length int contentLength = connection.getContentLength(); // To avoid having to resize the array over and over and over as // bytes are written to the array, provide an accurate estimate of // the ultimate size of the byte array ByteArrayOutputStream tmpOut; if (contentLength != -1) { tmpOut = new ByteArrayOutputStream(contentLength); } else { tmpOut = new ByteArrayOutputStream(16384); // Pick some appropriate size } byte[] buf = new byte[512]; while (true) { int len = in.read(buf); if (len == -1) { break; } tmpOut.write(buf, 0, len); } in.close(); tmpOut.close(); // No effect, but good to do anyway to keep the metaphor alive byte[] array = tmpOut.toByteArray(); //Lines below used to test if file is corrupt //FileOutputStream fos = new FileOutputStream("C:\\abc.pdf"); //fos.write(array); //fos.close(); return ByteBuffer.wrap(array); } </code></pre> <p>You forgot to close <code>fos</code> which may result in that file being shorter if your application is still running or is abruptly terminated. Also, I added creating the <code>ByteArrayOutputStream</code> with the appropriate initial size. (Otherwise Java will have to repeatedly allocate a new array and copy, allocate a new array and copy, which is expensive.) Replace the value 16384 with a more appropriate value. 16k is probably small for a PDF, but I don't know how but the "average" size is that you expect to download.</p> <p>Since you use <code>toByteArray()</code> twice (even though one is in diagnostic code), I assigned that to a variable. Finally, although it shouldn't make any difference, when you are wrapping the <strong>entire</strong> array in a ByteBuffer, you only need to supply the byte array itself. Supplying the offset <code>0</code> and the length is redundant.</p> <p>Note that if you are downloading <strong>large</strong> PDF files this way, then ensure that your JVM is running with a large enough heap that you have enough room for several times the largest file size you expect to read. The method you're using keeps the whole file in memory, which is OK as long as you can afford that memory. :)</p>
Porting code from using timers to scheduledexecutorservice <p>I am trying to port code from using java <a href="http://java.sun.com/j2se/1.3/docs/api/java/util/Timer.html" rel="nofollow">timers</a> to using <a href="http://java.sun.com/j2se/1.5.0/docs/api/java/util/concurrent/ScheduledExecutorService.html" rel="nofollow">scheduledexecutorservice</a></p> <p>I have the following use case </p> <pre><code>class A { public boolean execute() { try { Timer t = new Timer(); t.schedule (new ATimerTask(), period, delay); } catch (Exception e) { return false; } } } class B { public boolean execute() { try { Timer t = new Timer(); t.schedule (new BTimerTask(), period, delay); } catch (Exception e) { return false; } } } </code></pre> <p>Should I just replace Timer instances in class A and class B with ScheduledExecutorService and make the ATimerTask and BTimerTask class to a Runnable class , for e.g</p> <pre><code>class B { public boolean execute() { try { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); scheduler.scheduleWithFixedDelay (new BRunnnableTask(), period, delay); } catch (Exception e) { return false; } } } </code></pre> <p>Is this correct.</p> <p>EDIT: One of the primary motivation of porting is since runtime exceptions thrown in TimerTask kill that one thread and it cannot be scheduled further. I want to avoid the case so that ieven if I have runtime exception the thread should keep on executing and not halt. </p>
<p><strong>NOTE: The way you did this will leak threads!</strong></p> <p>If your class <code>B</code> will be kept around and <em>each instance</em> will eventually be closed or shut down or released, I would do it like this:</p> <pre><code>class B { final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1); public boolean execute() { try { scheduler.scheduleWithFixedDelay(new BRunnnableTask(), period, delay); return true; } catch (Exception e) { return false; } } public void close() { scheduler.shutdownNow(); } } </code></pre> <p>If you will not do this kind of cleanup on each instance, then I would instead do this:</p> <pre><code>class B { static final ScheduledExecutorService SCHEDULER = Executors.newCachedThreadPool(); public boolean execute() { try { SCHEDULER.scheduleWithFixedDelay(new BRunnnableTask(), period, delay); return true; } catch (Exception e) { return false; } } } </code></pre> <p>Each <code>ExecutorService</code> you allocate in your code allocates a single <code>Thread</code>. If you make many instances of your class <code>B</code> then each instance will be allocated a <code>Thread</code>. If these don't get garbage collected quickly, then you can end up with many thousands of threads allocated (but not used, just allocated) and you can crash your whole server, starving every process on the machine, not just your own JVM. I've seen it happen on Windows and I expect it can happen on other OS's as well.</p> <p>A static Cached thread pool is very often a safe solution when you don't intend to use lifecycle methods on the individual object instances, as you'll only keep as many threads as are actually <em>running</em> and not one for each instance you create that is not yet garbage collected.</p>
SQL: filter on a combination of two column values <p>I have a table <code>balances</code> with the following columns:</p> <pre><code>bank | account | date | amount </code></pre> <p>I also have a table <code>accounts</code> that has <code>bank</code> and <code>account</code> as its composite primary key.</p> <p>I want to do a query like the following pseudocode:</p> <pre><code>select date, sum(amount) as amount from balances where bank and account in (list of bank and account pairs) group by date </code></pre> <p>The list of bank-account pairs is supplied by the client. How do I do this? Create a temp table and join on it?</p> <p>I'm using Sybase</p>
<p>It may be helpful to have some more information.</p> <p>If you have criteria that are driving your particular list of bank and account entities then you should be joining on these tables. </p> <p>You do have a Bank table and an Account table don't you?</p> <p>Assuming you have the information in the accounts table that narrow down the specific accounts you want to reference, for example suppose your Accounts table has an IsActive char(1) NOT NULL field and you want the balances for inactive accounts you would write something like this: </p> <pre><code>SELECT date, sum( amount ) AS amount FROM Balances b INNER JOIN Accounts a ON b.Bank = a.Bank AND b.Account = a.Account WHERE a.IsActive = 'N' </code></pre> <p>From a design perspective your should probably have created an artificial key to remove replication of non-identifying data across tables. This would give you something like this:</p> <pre><code>CREATE TABLE Accounts ( AccountId int identity(1,1) NOT NULL, Bank nvarchar(15) NOT NULL, Account nvarchar(15) NOT NULL ) CREATE TABLE Balances ( AccountId int, Date datetime, Amount money ) </code></pre> <p>This allows errors in the Bank or Account fields to be edited without having to cascade these changes to the Balances table as well as a slightly simpler query.</p> <pre><code>SELECT date, sum( amount ) AS amount FROM Balances b INNER JOIN Accounts a ON b.AccountId = a.AccountId WHERE a.IsActive = 'N' </code></pre>
Django: Uploaded file locked. Can't rename <p>I'm trying to rename a file after it's uploaded in the model's save method. I'm renaming the file to a combination the files primary key and a slug of the file title.</p> <p>I have it working when a file is first uploaded, when a new file is uploaded, and when there are no changes to the file or file title.</p> <p>However, when the title of the file is changed, and the system tries to rename the old file to the new path I get the following error:</p> <pre><code>WindowsError at /admin/main/file/1/ (32, 'The process cannot access the file because it is being used by another process') </code></pre> <p>I don't really know how to get around this. I've tried just coping the file to the new path. This works, but I don't know I can delete the old version.</p> <p>Shortened Model:</p> <pre><code>class File(models.Model): nzb = models.FileField(upload_to='files/') name = models.CharField(max_length=256) name_slug = models.CharField(max_length=256, blank=True, null=True, editable=False) def save(self): # Create the name slug. self.name_slug = re.sub('[^a-zA-Z0-9]', '-', self.name).strip('-').lower() self.name_slug = re.sub('[-]+', '-', self.name_slug) # Need the primary key for naming the file. super(File, self).save() # Create the system paths we need. orignal_nzb = u'%(1)s%(2)s' % {'1': settings.MEDIA_ROOT, '2': self.nzb} renamed_nzb = u'%(1)sfiles/%(2)s_%(3)s.nzb' % {'1': settings.MEDIA_ROOT, '2': self.pk, '3': self.name_slug} # Rename the file. if orignal_nzb not in renamed_nzb: if os.path.isfile(renamed_nzb): os.remove(renamed_nzb) # Fails when name is updated. os.rename(orignal_nzb, renamed_nzb) self.nzb = 'files/%(1)s_%(2)s.nzb' % {'1': self.pk, '2': self.name_slug} super(File, self).save() </code></pre> <p>I suppose the question is, does anyone know how I can rename an uploaded file when the uploaded file isn't be re-uploaded? That's the only time it appears to be locked/in-use.</p> <p><hr /></p> <p><strong>Update:</strong></p> <p>Tyler's approach is working, except when a new file is uploaded the primary key is not available and his technique below is throwing an error.</p> <pre><code>if not instance.pk: instance.save() </code></pre> <p>Error:</p> <pre><code>maximum recursion depth exceeded while calling a Python object </code></pre> <p>Is there any way to grab the primary key?</p>
<p>I think you should look more closely at the upload_to field. This would probably be simpler than messing around with renaming during save.</p> <p><a href="http://docs.djangoproject.com/en/dev/ref/models/fields/#filefield" rel="nofollow">http://docs.djangoproject.com/en/dev/ref/models/fields/#filefield</a></p> <blockquote> <p>This may also be a callable, such as a function, which will be called to obtain the upload path, including the filename. This callable must be able to accept two arguments, and return a Unix-style path (with forward slashes) to be passed along to the storage system. The two arguments that will be passed are:</p> </blockquote>
nHibernate (w/ Castle ActiveRecord) with C# interfaces (esp for DTO's) <p>Any using nHibernate with a Domain object &amp; DTO object implemented from a common interface? I'm trying to separate all of my nHibernate attributes into the Domain object, leaving my DTO's and interface clean.</p> <p>The problem comes with nHibernate throwing errors when it tries to associate the interfaces with the concrete classes.</p> <p><strong>NHibernate.MappingException: Association references unmapped class: IContact</strong></p> <p>I understand why its complaining about the use of the non-hibernated interface, but I'm struggling to visual a way to restructure around it. A skeleton reproduction of my code is set out as below, any ideas for how to structure my code better?</p> <pre><code>public interface ICompany { IList&lt;IContact&gt; Contacts { get; set; } } public class CompanyDTO : ICompany { private IList&lt;IContact&gt; contacts; public IList&lt;IContact&gt; Contacts { get { return this.contacts; } set { this.contacts = value; } } } [ActiveRecord] public class Company : ActiveRecordBase&lt;Company&gt;, ICompany { private IList&lt;IContact&gt; contacts; [HasMany(Inverse=true, Table="Contact", ColumnKey="CompanyId")] [ScriptIgnore] public IList&lt;IContact&gt; Contacts { get { return this.contacts; } set { this.contacts = value; } } } </code></pre> <p>Edit:</p> <p>I want to have a common interface so that I can ensure they are keeping the same fields (ie. leaning on the compiler to keep them consistent). It also allows me to use the DTO's in the view part of my application, but casts them to domain objects for business and data access. Also, alex's solution does not work because ICompany's Contacts is of type IList, not IList. I would like to keep it as IContact so my DTO object has no knowledge of the Contact Domain object. </p>
<p>In your concrete case you should just add <code>Type = typeof(Contact)</code> to the mapping attribute, like so:</p> <pre><code>[HasMany(Inverse=true, Table="Contact", ColumnKey="CompanyId", Type=typeof(Contact))] </code></pre>
How to pass arguments when debugging a dot net application <p>I have an command line that uses arguments, I have no problem with this, but each time I want to test the application, I need to compile it, run the CMD, call the application with the parameters from the CMD, because I didn't find any solution that let me dynamically pass arguments to the console in Visual Studio Any idea about that? Thanks a lot!!</p>
<p>Goto <code>Project-&gt;Properties</code> and click the <code>Debug</code> Tab. </p> <p>There is a section for command line arguments:</p> <p><img src="http://i.stack.imgur.com/40c4M.png" alt="enter image description here"></p>
Unable to call system commands and shell scripts from PHP Fedora 10 <p>I am working on an application that runs locally on a Fedora 10 machine through PHP and Apache. It depends on a process that runs in the background.</p> <p>The higher-ups want to be able to start/stop/restart the process, through the browser. I was trying to get this to work by having PHP make calls to the system using exec() and shell_exec, but it doesn't seem to work.</p> <p>When I try to start the process using "exec('processName')", nothing happens.</p> <p>When I try to use "exec('killall processName')", SELinux starts constantly popping up warnings that the process was permitted (because I put it into permissive mode), however it doesn't actually kill the process! But this seems to go on even after the page is fully loaded!?!?</p> <p>I AM able to call another script in a similar fashion: "exec('/var/www/cgi-bin/ControlProgram START')". So I'm not really sure what the major differences are between the two calls/commands.</p> <p>I also put the script call into the /etc/rc.local file to have the script run at login. However, will I be able to kill this script from PHP since its run by... the system?</p> <p>I'm not a guru when it comes to permissions/SELinux, so don't spare on the gory details! Thanks in advance!</p>
<p>If you have administrative control over this system you will want to check the PHP configuration (make sure it is the config profile for the web server).</p> <p>Safe_Mode will prevent PHP from executing anything outside a particular folder. In a shared hosting environment, this usually means you can only execute things that are relative to your home/www folder--which seems to be the case based on your notes.</p>
How to use Apache HWPF to extract text and images out of a DOC file <p>I downloaded the <a href="http://poi.apache.org/hwpf/index.html" rel="nofollow">Apache HWPF</a>. I want to use it to read a doc file and write its text into a plain text file. I don't know the HWPF so well.</p> <p>My very simple program is here:</p> <p>I have 3 problems now:</p> <ol> <li><p>Some of packages have errors (they can't find apache hdf). How I can fix them?</p></li> <li><p>How I can use the methods of HWDF to find and extract the images out?</p></li> <li><p>Some piece of my program is incomplete and incorrect. So please help me to complete it.</p></li> </ol> <p>I have to complete this program in 2 days.</p> <p>once again I repeat Please Please help me to complete this.</p> <p>Thanks you Guys a lot for your help!!!</p> <p>This is my elementary code :</p> <pre><code>public class test { public void m1 (){ String filesname = "Hello.doc"; POIFSFileSystem fs = null; fs = new POIFSFileSystem(new FileInputStream(filesname ); HWPFDocument doc = new HWPFDocument(fs); WordExtractor we = new WordExtractor(doc); String str = we.getText() ; String[] paragraphs = we.getParagraphText(); Picture pic = new Picture(. . .) ; pic.writeImageContent( . . . ) ; PicturesTable picTable = new PicturesTable( . . . ) ; if ( picTable.hasPicture( . . . ) ){ picTable.extractPicture(..., ...); picTable.getAllPictures() ; } } </code></pre>
<p><a href="http://tika.apache.org/" rel="nofollow">Apache Tika</a> will do this for you. It handles talking to POI to do the HWPF stuff, and presents you with either XHTML or Plain Text for the contents of the file. If you register a recursing parser, then you'll also get all the embedded images too.</p>
Modifying my website to allow anonymous comments <p>I write the code for my own website as an educational/fun exercise. Right now part of the website is a blog (like every other site out there :-/) which supports the usual basic blog features, including commenting on posts. But I only have comments enabled for logged-in users; I want to alter the code to allow anonymous comments - that is, I want to allow people to post comments without first creating a user account on my site, although there will still be some sort of authentication involved to prevent spam.</p> <p>Question: what information should I save for anonymous comments? I'm thinking at least display name and email address (for displaying a Gravatar), and probably website URL because I eventually want to accept OpenID as well, but would anything else make sense?</p> <p>Other question: how should I modify the database to store this information? The schema I have for the comment table is currently</p> <pre><code>comment_id smallint(5) // The unique comment ID post_id smallint(5) // The ID of the post the comment was made on user_id smallint(5) // The ID of the user account who made the comment comment_subject varchar(128) comment_date timestamp comment_text text </code></pre> <p>Should I add additional fields for name, email address, etc. to the comment table? (seems like a bad idea) Create a new "anonymous users" table? (and if so, how to keep anonymous user ids from conflicting with regular user ids) Or create fake user accounts for anonymous users in my existing users table?</p> <p>Part of what's making this tricky is that if someone tries to post an anonymous comment using an email address (or OpenID) that's already associated with an account on my site, I'd like to catch that and prompt them to log in.</p>
<p>The whole point of anonymous comments is that users don't have to login, right? </p> <p>My personal taste is to not force the user to enter anything, not even their name! The only requried field is the comment text itself. If they don't want to give out their name or email, fine, who cares? </p> <p>If they provide an email that already exists, there's a chance that they registered a looong time ago and don't even remember their password. </p> <p>Again, don't force the user to login in that case. Just give them a choice to either login or leave email field blank (or change its content). Or, just show a warning box telling them that the comment will be sent without the email address, with "ok" and "cancel" options.</p> <p>So, what to store with the anonymous comment?</p> <p>I'd say store their name and email (of course, don't display their email to the public), but make them optional fields, not mandatory. </p> <p>You can also store their website, although I personally don't know what's the point of that, other than maybe self-advertising for the anonymous poster!</p>
C# clearing the thread principal <p>How do you clear the thread principal in c#.</p> <p>I have a background thread that does a</p> <pre><code>Membership.ValidateUser(username, password); </code></pre> <p>which then copies the resulting Principal back to the main thread</p> <pre><code>AppDomain.CurrentDomain.SetThreadPrincipal(Thread.CurrentPrincipal); </code></pre> <p>this works fine. But, if I log off I want to clear the principal, if I set it to null it does nothing Thread.CurrentPrincipal = null; if I try and set it again via</p> <pre><code>AppDomain.CurrentDomain.SetThreadPrincipal(Thread.CurrentPrincipal); </code></pre> <p>I get the error </p> <pre><code>Default principal object cannot be set twice. </code></pre> <p>Any ideas?</p>
<p>I don't think you can reset the principal without shutting down the AppDomain and recreating it. You only get one shot at calling SetThreadPrincipal. </p> <p>Assuming that you are using your own custom principal object that you create after ValidateUser; you can probably put a "Logout" method on your principal that resets its internal state to an unauthenticated user. </p>
Is current graphic only available in view's drawRect:? <p>I tried invoking UIGraphicsGetCurrentContext() in other places other than in drawRect. It give me a NULL. Is it true that I can can only get current context in UIView's drawRect: only?</p>
<p>Yes, outside of drawRect, the default context is nil. Before drawRect is called, a view will push its context onto the stack, and pop it after drawRect ends.</p>
Export contact list from Gmail, Hotmail, Yahoo, LinkedIn, Facebook <p>I'm looking for library/API to retrieve contact list (emails address to which user had sent mail to, regardless whether user had explicitly added it as contact). Does anybody know such library/API available there?</p>
<p>Please have a look at socialauth. This Java library will help you get the contacts from most of the networks.</p> <p><a href="http://code.google.com/p/socialauth" rel="nofollow">http://code.google.com/p/socialauth</a></p>
SQL: How to SELECT tablename.* <p>I tried doing this but it failed.</p> <pre><code>SELECT table2.ID, table1.* FROM table2 LEFT JOIN table1 ON table1.ID = table2.table1ID </code></pre> <p>How do you select all columns from a table?</p> <p>EDIT: There is no error in the above query. I don't know what caused the error but the code is now working.</p>
<p>You had field names conflict as both tables have ID field. You must to </p> <pre><code> SELECT table2.ID as t2_id, table1.* FROM table2 LEFT JOIN table1 ON table1.ID = table2.table1ID </code></pre>
REST on IIS <p>I'm wondering how many folks using the Microsoft development stack (IIS and/or ASP.NET) are actually using REST? If so, what forms of rest are being used?</p> <p>REST can be categorized a zillion ways, but for the purpose of this question I'll categorize it as follows:</p> <ol> <li>Radically REST: Using all the HTTP methods PUT/POST/GET/DELETE</li> <li>Moderate REST: Using GET/POST </li> <li>REST Hybrid: Uses just the GET or POST HTTP method, but follows RESTful principles of addressability and state.</li> </ol> <p>In a class I'm teaching we've been trying to implement a "radically RESTful" service on IIS, but we've been having difficulty implementing the PUT method. There doesn't seem to be a lot of buzz on implementing PUT on IIS so I'm wondering how many people are actually using full blown REST? Are you using REST?</p>
<p>I'm involved in a project that uses WCF REST on IIS, but of course I'd recommend having a look at the framework I built: OpenRasta is a .net open-source stack that makes implementing REST much easier.</p> <p>Google is your friend. The main site is <a href="http://trac.caffeine-it.com/openrasta">http://trac.caffeine-it.com/openrasta</a>.</p>
MSSQL Server - get a whole part of a decimal value in the computed column <p>Here's my simplified table (SQL Server 2005):</p> <pre><code>table1: col1 int, col2 int, col3 cast(col1/col2 as int) [computed column] </code></pre> <p>for some reason the above doesn't work. i just want to save a WHOLE part of col1/col2, how do i do that?</p> <pre><code>example: col1 = 5, col2 = 3 ... col3 should be 1 </code></pre>
<p>One option would be to use the <a href="http://msdn.microsoft.com/en-us/library/ms178531.aspx" rel="nofollow">floor function</a>:</p> <p>FLOOR(col1/col2)</p> <p>or</p> <p>CONVERT(int, FLOOR(col1/col2)) -- Might be overkill</p>
ASP.NET TextBox filter <p>is there a simple way to suppress certain keystrokes within a textbox? for example if i only want to allow numbers.</p>
<p>There's nothing built-in, you will need to <a href="http://www.w3schools.com/jsref/jsref%5Fonkeydown.asp" rel="nofollow">write some JavaScript</a> to capture and ignore the keys you want to disallow.</p> <p>Or you can use this <a href="http://www.asp.net/AJAX/AjaxControlToolkit/Samples/FilteredTextBox/FilteredTextBox.aspx" rel="nofollow">FilteredTextBox</a> control extender, from the <a href="http://www.asp.net/AJAX/AjaxControlToolkit/" rel="nofollow">ASP .NET AJAX Control Toolkit</a></p>
How do you get the top-right corner of an image in Flex <p>I want to get the top-right corner of an image in flex .... so far i can just get the x and y which are top-left by default .... sorry im a noob and if this is a dumb question</p>
<p>Have you tried adding the image width to x?</p>
Memory Consumption? <p>I have a piece of code where </p> <pre><code>for ( ; ; ) { char *buf; /* Some code */ } </code></pre> <p>The question here will the code allocate memory every time when it cycles through the loop . I mean atleast 4 bytes will be reserved for the pointer when it cycles .</p>
<p>Space for the pointer will be allocated on the stack, but it will be popped off at the end of every iteration, so you don't need to worry about it.</p>
Problem with SafeArray access using CComVariant <p>I have following block of code</p> <pre><code> ///////////////////////////////////// CComVariant newVal; //pass the CComVariant and get the strings array!!! GetStrList(newVal); USES_CONVERSION; if (((newVal.vt &amp; VT_ARRAY) == VT_ARRAY) &amp;&amp; ((newVal.vt &amp; VT_BSTR) == VT_BSTR)) { SAFEARRAY* paArray = newVal.parray; BSTR * str = NULL; SafeArrayAccessData(paArray, (void**)&amp;str); SafeArrayUnaccessData(paArray); long lLBound = 0; long lUBound = 0; long nCount = 0; if (FAILED(SafeArrayGetLBound(paArray, 1, &amp;lLBound)) || FAILED(SafeArrayGetUBound(paArray, 1, &amp;lUBound))) { ASSERT(false); return FALSE; } nCount = ( lUBound - lLBound + 1 ); for (int i = 0 ; i &lt; nCount ; i++) { m_cstrList.AddString(W2T(str[i])); } //SafeArrayDestroy(paArray); ---&gt; is it required here??? } ///////////////////////////////////// </code></pre> <p>method returing the safe arrays</p> <pre><code> HRESULT GetStrList(VARIANT *pVal) { USES_CONVERSION; if (!pVal) return E_FAIL; SAFEARRAYBOUND bound[1]; //single dimension array bound[0].lLbound = 0; bound[0].cElements = 10; SAFEARRAY * A = SafeArrayCreate(VT_BSTR, 1, bound); BSTR * str = NULL; SafeArrayAccessData(A, (void**)&amp;str); //user wants the NT view OPC drivers list. for (int i=0;i&lt;10;i++) { str[i] = SysAllocString(T2W(mystrings[i])); } VariantInit(pVal); pVal-&gt;vt = VT_ARRAY | VT_BSTR; pVal-&gt;parray = A; SafeArrayUnaccessData(A); A = NULL; return S_OK; } </code></pre> <p>My doubt is, above first block of code has any memory leaks? Does the <code>CComVariant</code> itself handle every thing about the cleaning? or do i also manually do <code>SafeArrayDestroy(paArray);</code></p> <p>Thanks in Advance!</p>
<p>CComVariant destructor calls VariantClear() which frees whatever the variant was incapsulating, arrays included.</p> <p>One caveat: the array should not be locked at the time when VariantClear() is called. This means that if an exception is thrown after SafeArrayAccessData() but before SafeArrayUnaccessData() the latter will not be called and VariantClear() will not free resources.</p> <p>Therefore you better write a bracket class for pairing SafeArrayAccessData() and SafeArrayUnaccessData() calls.</p>
What happens when I reboot an EC2 instance? <p>When I reboot an EC2 instance, do I get the initial image again, or is the state of the hard disk before the reboot kept?</p> <p>And what happens with billing, does the hour start again, or do I continue with the fraction of the hour I was in when I rebooted?</p>
<p>Rebooting an instance is like rebooting a PC. The hard disk isn't affected. You don't return to the image's original state, but the contents of the hard disks are those before the reboot.</p> <p>Rebooting isn't associated with billing. Billing starts when you instantiate an image and stops when you terminate it. Rebooting in between hasn't any effect.</p>
Showing page count with ReportLab <p><br /> I'm trying to add a simple "page x of y" to a report made with ReportLab.. I found <a href="http://two.pairlist.net/pipermail/reportlab-users/2002-May/000020.html">this old post</a> about it, but maybe six years later something more straightforward has emerged? ^^;<br /> I found <a href="http://code.activestate.com/recipes/546511/">this recipe</a> too, but when I use it, the resulting PDF is missing the images..</p>
<p>I was able to implement the NumberedCanvas approach from ActiveState. It was very easy to do and did not change much of my existing code. All I had to do was add that NumberedCanvas class and add the canvasmaker attribute when building my doc. I also changed the measurements of where the "x of y" was displayed:</p> <pre><code>self.doc.build(pdf) </code></pre> <p>became </p> <pre><code>self.doc.build(pdf, canvasmaker=NumberedCanvas) </code></pre> <p><strong>doc</strong> is a BaseDocTemplate and <strong>pdf</strong> is my list of flowable elements.</p>
geographic location uri scheme <p>I'd like to use a URI scheme to enable the users of one of my apps to share geographic locations.</p> <p>I don't want to invent my own URI scheme and "geo" seems the most appropriate but there are only two Internet Drafts on the subject (<a href="http://tools.ietf.org/html/draft-mayrhofer-geo-uri-01" rel="nofollow">draft-mayrhofer-geo-uri-01</a>, <a href="http://tools.ietf.org/html/draft-mayrhofer-geo-uri-02" rel="nofollow">draft-mayrhofer-geo-uri-02</a>), both expired and wildly different in the way they approach the standard.</p> <p>Is there an URI that's suited for encoding latitude and longitude and that made it as an RFC? Should I use a generic URI such as <a href="http://www.faqs.org/rfcs/rfc4151.html" rel="nofollow">the tag URI scheme</a>?</p>
<p>final note: The draft is now in the RFC Editors queue within the IETF, so it should become an RFC within the next 3 - 5 months. </p> <p><a href="http://tools.ietf.org/html/draft-ietf-geopriv-geo-uri-07" rel="nofollow">http://tools.ietf.org/html/draft-ietf-geopriv-geo-uri-07</a></p>
how to send signal from one program to another? <p>i am using message queue as an ipc between 2 programs. Now i want to send data from one program to another using message queue and then intimate it through a signal SIGINT.</p> <p>I dont know how to send a signal from one program to another . Can anybody pls provide a sample code if they have the solution.</p>
<pre><code>#include &lt;sys/types.h&gt; #include &lt;signal.h&gt; int kill(pid_t pid, int sig); </code></pre>
How to conditionally compile VC6 resources <p>depending on a compile switch (values are <code>COMPILE_A</code> or <code>COMPILE_B</code>), which is set in the form of an envorinment variable, I want to compile my application with different settings, like application name and splash screen.</p> <p>I got this far:</p> <ol> <li><p>In "Project / Settings / C/C++ / Preprocessor Definitions" I added <code>$(COMPILESWITCH)</code> (results in command line option <code>/D "$(COMPILESWITCH)"</code>).</p></li> <li><p>In stdafx.h I can use the following code, which means I correctly defined the preprocessor definition via the command line parameter:</p></li> </ol> <pre><code> #if defined COMPILE_A # define IDB_SPLASH IDB_SPLASH_A # elif defined COMPILE_B # define IDB_SPLASH IDB_SPLASH_B # else # error Unknown or undefined target compile switch; cannot compile! # endif </code></pre> <p>But I've noticed the "Condition" property under "ResourceView / [right-click] / Properties"... The help text says this:</p> <blockquote> Condition <p>Determines the inclusion of the resource. For example, if the condition is _DEBUG, this resource would be included only in debug builds.</p> </blockquote> <p>This looks like the elegant way of doing it, right?</p> <p>Specifiying <code>_DEBUG</code> as condition works. So as <code>_DEBUG</code> is specified via <code>/D _DEBUG</code> my <code>$(COMPILESWITCH)</code> should also work, right?<br /> For some reason it doesn't; why?</p> <p>Or is there even another, better way to achieve what I want?</p>
<p>I guess I just solved my problem...</p> <p>The resource compiler uses its own preprocessor.<br /> Therefore the same preprocessor definition has to be added under "Project / Settings / Resources / Preprocessor Definitions".</p> <h3>Edit: String Resources</h3> <p>The above doesn't work for string resources as they don't have a "condition" property...</p> <p>I chose to use the <code>res\&lt;projectname&gt;.rc2 custom resource file which won't be touched by the resource editor. The content looks like this</p> <pre> #if defined(COMPILE_A) STRINGTABLE DISCARDABLE BEGIN IDR_MAINFRAME "AppTitle A" END #else # if defined(COMPILE_B) STRINGTABLE DISCARDABLE BEGIN IDR_MAINFRAME "AppTitle B" END # else # error Compile switch not defined or unknown; cannot compile! # endif #endif </code></pre>
Getprivateprofilestring Bug <p>I encrypted some text and put it in a INI file. Then I used getprivateprofilestring() to retrieve the value but some of the end characters are missing. I suspect it may be a new line character causing it to be incomplete. Writing to the INI file is OK. Opening the INI file and looking at the sections and keys - everything is in order. Its just the retrieving part that causes the bug. </p> <p>Please any help would be appreciated.</p> <p>Thanks Eddie</p>
<p>First off when encrypting strings, make sure that they are converted to Base64 before dumping them into the INI file.</p> <p>Most likely, the encrypted string created an ascii character which is not handled very well by the INI related APIs. </p>
BPEL switch-case in Netbeans <p>I'm using netbeans to develop some BPEL but can't figure out how to add a switch-case block, it's not in the palette anywhere. I'm using netbeans 6.5. Any ideas?</p> <p>Switch is definitely a valid element: <a href="http://charltonb.typepad.com/weblog/2003/08/bpel4ws_switch_.html" rel="nofollow">http://charltonb.typepad.com/weblog/2003/08/bpel4ws_switch_.html</a> It's also mentioned in the course materials I'm running through.</p>
<p>Have you tried just inserting the switch in the xml source itself? Not sure if Netbeans would support it but it is defined in the standard for BPEL markup.</p>
Continuous build with .NET and Java projects on a single machine <p>Is it possible to set up continuous build of projects written in .NET and Java on single build server with single set of applications?</p> <p>I've seen CruiseControl has support for both world but as far as I know these are two separate applications. Should I go with a separate machine to build Java projects (a machine for .NET projects is already set up)?</p>
<p><a href="http://hudson-ci.org/" rel="nofollow">Hudson</a> has support for both Ant (out of the box IIRC) and <a href="http://wiki.hudson-ci.org/display/HUDSON/NAnt+Plugin" rel="nofollow">NAnt</a> (through plugin) so that's an option for you.</p>
if/else and if/elseif <p>If I have a statement block like this:</p> <pre><code>if (/*condition here*/){ } else{ } </code></pre> <p>or like this: </p> <pre><code>if (/*condition here*/) else if (/*condition here*/) {} else if (/*condition here*/) {} </code></pre> <p>What is the difference?</p> <p>It seems that with if/else, if part is for true state and the else part is for all other possible options (false). An else-if would be useful for a number of conditions. This is my understanding, is there anything more I should be aware of?</p>
<p>Without "elseif" syntax you would have to write chain if-statements for processing one of several possible outcomes this way:</p> <pre><code>if( str == "string1" ) { //handle first case } else { if( str == "string2" ) { //handle second case } else { if( str == "string3" ) { //handle third case } else { //default case } } } </code></pre> <p>instead you can write</p> <pre><code>if( str == "string1" ) { //handle first case } else if( str == "string2" ) { //handle second case } else if( str == "string3" ) { //handle third case } else { //default case } </code></pre> <p>which is completely the same as the previous one, but looks much nicer and is much easier to read.</p>
How to change prompt_alternatives_on flag in prolog from .plrc? <p>I can change <code>prompt_alternatives_on</code> flag in the REPL. </p> <ol> <li>But how do I change this flag in .plrc?</li> </ol> <p>Then I get</p> <pre><code> permission to modify static_procedure `set_prolog_flag/2' </code></pre> <p>Goal: To not get the "More?" text for all the answers all the time. By changing the flag.</p>
<p>Put :- (a colon and a hypen) in front of the line to execute it when the file is loaded.</p> <pre><code>:- set_prolog_flag(key, value). </code></pre> <p>This is true of any line of code in any source file that you want to have evaluated when the file is loaded instead of considered a new fact or rule (which causes the error because it attempts to redefine set_prolog_flag/2).</p>
How to calculate or approximate the median of a list without storing the list <p>I'm trying to calculate the median of a set of values, but I don't want to store all the values as that could blow memory requirements. Is there a way of calculating or approximating the median without storing and sorting all the individual values?</p> <p>Ideally I would like to write my code a bit like the following</p> <pre><code>var medianCalculator = new MedianCalculator(); foreach (var value in SourceData) { medianCalculator.Add(value); } Console.WriteLine("The median is: {0}", medianCalculator.Median); </code></pre> <p>All I need is the actual MedianCalculator code!</p> <p><strong>Update:</strong> Some people have asked if the values I'm trying to calculate the median for have known properties. The answer is yes. One value is in 0.5 increments from about -25 to -0.5. The other is also in 0.5 increments from -120 to -60. I guess this means I can use some form of histogram for each value.</p> <p>Thanks</p> <p>Nick</p>
<p>If the values are discrete and the number of distinct values isn't too high, you could just accumulate the number of times each value occurs in a histogram, then find the median from the histogram counts (just add up counts from the top and bottom of the histogram until you reach the middle). Or if they're continuous values, you could distribute them into bins - that wouldn't tell you the exact median but it would give you a range, and if you need to know more precisely you could iterate over the list again, examining only the elements in the central bin.</p>
How can I convert non-ASCII characters encoded in UTF8 to ASCII-equivalent in Perl? <p>I have a Perl script that is being called by third parties to send me names of people who have registered my software. One of these parties encodes the names in UTF-8, so I have adapted my script accordingly to decode UTF-8 to ASCII with Encode::decode_utf8(...). </p> <p>This usually works fine, but every 6 months or so one of the names contains cyrillic, greek or romanian characters, so decoding the name results in garbage characters such as "ПодражанÑкаÑ". I have to follow-up with the customer and ask him for a "latin character version" of his name in order to issue a registration code. </p> <p>So, is there any Perl module that can detect whether there are such characters and automatically translates them to their closest ASCII representation if necessary? </p> <p>It seems that I can use Lingua::Cyrillic::Translit::ICAO plus Lingua::DetectCharset to handle Cyrillic, but I would prefer something that works with other character sets as well. </p>
<p>I believe you could use <a href="http://search.cpan.org/dist/Text-Unidecode/">Text::Unidecode</a> for this, it is precisely what it tries to do.</p>
Profiling C++ multi-threaded applications <p>Have you used any profiling tool like Intel Vtune analyzer? </p> <p>What are your recommendations for a C++ multi threaded application on Linux and windows? I am primarily interested in cache misses, memory usage, memory leaks and CPU usage. </p> <p>I use valgrind (only on UNIX), but mainly for finding memory errors and leaks. </p>
<p>Following are the good tools for multithreaded applications. You can try evaluation copy.</p> <ol> <li>Runtime sanity check tool <ul> <li>Thread Checker -- Intel Thread checker / VTune, <a href="https://software.intel.com/en-us/articles/intel-thread-checker-documentation" rel="nofollow">here</a></li> </ul></li> <li>Memory consistency-check tools (memory usage, memory leaks) - Memory Validator, <a href="http://www.softwareverify.com/cpp/memory/index.html" rel="nofollow">here</a></li> <li>Performance Analysis. (CPU usage) - AQTime , <a href="http://www.softpedia.com/get/Programming/Other-Programming-Files/AQtime.shtml" rel="nofollow">here</a></li> </ol> <p><strong>EDIT</strong>: Intel thread checker can be used to diagnose Data races, Deadlocks, Stalled threads, abandoned locks etc. Please have lots of patience in analyzing the results as it is easy to get confused.</p> <p>Few tips:</p> <ol> <li>Disable the features that are not required.(In case of identifying deadlocks, data race can be disabled and vice versa.)</li> <li>Use Instrumentation level based on your need. Levels like "All Function" and "Full Image" are used for data races, where as "API Imports" can be used for deadlock detection)</li> <li>use context sensitive menu "Diagnostic Help" often.</li> </ol>
Ruby on Rails versus Python <p>I am in the field of data crunching and very soon might make a move to the world of web programming. Although I am fascinated both by Python and Ruby as both of them seem to be having every similar styles when it comes to writing business logic or data crunching logic.</p> <p>But when I start googling for web development I start inclining towards Ruby on Rails my question is why is the web world obsessed with ruby on rails and active records so much?</p> <p>There seem to be so many screencasts to learn Ruby on Rails and plethora of good books too why is Python not able to pull the crowd when it comes to creating screencasts or ORM's like active record.</p>
<p>Ruby and Python are languages.</p> <p>Rails is a framework.</p> <p>So it is not really sensible to compare Ruby on Rails vs Python.</p> <p>There are Python Frameworks out there you should take a look at for a more direct comparison - <a href="http://wiki.python.org/moin/WebFrameworks">http://wiki.python.org/moin/WebFrameworks</a> (e.g. I know <a href="http://www.djangoproject.com/">Django</a> gets a lot of love, but there are others)</p> <p>Edit: I've just had a google, there seem to be loads of <a href="http://www.google.co.uk/search?rlz=1C1GGLS%5FenGB291GB304&amp;aq=f&amp;sourceid=chrome&amp;ie=UTF-8&amp;q=django%2Bscreencast">Django Screencasts</a>.</p>
Why does this take so long to compile in VCC 2003? <p>My team need the "Sobol quasi-random number generator" - a common RNG which is famous for good quality results and speed of operation. I found <a href="http://people.scs.fsu.edu/~burkardt/cpp%5Fsrc/sobol/sobol%5Fold.C" rel="nofollow">what looks like a simple C implementation on the web</a>. At home I was able to compile it almost instantaneously using my Linux GCC compiler. </p> <p>The following day I tried it at work: If I compile in Visual Studio in debug mode it takes about 1 minute. If I were to compile it in release mode <strong>it takes about 40 minutes.</strong> </p> <p>Why?</p> <p>I know that "release" mode triggers some compiler optimization... but how on earth could a file this small take so long to optimize? It's mostly comments and static-data. There's hardly anything worth optimizing.</p> <p>None of these PCs are particularly slow, and in any case I know that the compile time is consistent across a range of Windows computers. I've also heard that newer versions of Visual Studio have a faster compile time, however for now we are stuck with Visual Studio.Net 2003. Compiling on GCC (the one bundled with Ubuntu 8.04) always takes microseconds.</p>
<p>I'm using VC++ 2003 and it compiled instantly in both debug/release modes.</p> <p><strong>Edit:</strong></p> <p>Do you have the latest service pack installed on your systems?</p>
In SQL how can I convert a money datatype to a decimal? <p>I want to convert a money datatype to a decimal, because I want to record the results to 8 decimal places.</p> <p>For example, in a currency rate table I see the rate stored as 2871047428.20 as a money datatype; using Microsoft SQL Management Studio, I want to divide that by 10000000 in order to achieve the result 287.10474282; however the result I am actually getting is 287.1047.</p> <p>I believe the reason I am getting only the 4 decimal places is because it is money datatype, and therefore I think the way forward is to convert this to a decimal datatype.... </p>
<p>Here a comparison left column the decimal value, right column the calculated money value:</p> <pre><code>DECLARE @money AS money SET @money = 2871047428.20 SELECT CAST(@money AS decimal(34,4)) / 10000000, @money / 10000000 </code></pre> <p>See also here on Stack Overflow:</p> <ul> <li><a href="http://stackoverflow.com/questions/532351/how-do-i-convert-from-a-money-datatype-in-sql-server">How do I convert from a money datatype in SQL server?</a></li> <li><a href="http://stackoverflow.com/questions/391117/sql-server-2005-varchar-loses-decimal-places-converting-to-a-decimal">SQL Server 2005 varchar loses decimal places converting to a decimal</a></li> </ul>