instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I'm rather confused about this. </p> <p>And what's their relationship(e.g., how one can be used in the context of the other)? Much thanks!!</p>
<p>Is <a href="http://www.xemacs.org/Documentation/beta/html/internals_22.html" rel="nofollow noreferrer">this what you are looking for</a> ?</p> <p>A symbol is basically just an object with four fields: </p> <ul> <li>a name (a string), </li> <li>a value (some Lisp object), </li> <li>a function (some Lisp object), and </li> <li>a property list (usually a list of alternating keyword/value pairs). </li> </ul> <p>What makes symbols special is that there is usually only one symbol with a given name, and the symbol is referred to by name. This makes a symbol a convenient way of calling up data by name, i.e. of <em>implementing variables</em>. (The variable's value is stored in the value slot.) </p> <p>Similarly, functions are referenced by name, and the definition of the function is stored in a symbol's function slot. This means that there can be a distinct function and variable with the same name. </p> <p>The property list is used as a more general mechanism of associating additional values with particular names, and once again the namespace is independent of the function and variable namespaces.</p>
<p>The concept of symbols is a little bit hard to understand. (Even I'm not sure I got it :) )</p> <p>You can look at symbols as special variables which behave like constants. There is only one instance in memory, no matter how often you used it.</p> <p>The benefits are conserving memory and one can see if a value is used in a constant-like manner. (Improves code readability)</p> <p>You can do <em>similar</em> things in C/C++ with <code>typdef</code>, in Java with <code>static final</code> or in Delphi/Pascal/VB with <code>const</code>, but be careful, in those and many other languages "symbol" means something different. </p>
30,524
<p>I got a webservice which creates a PNG-file and returns a link to it. Then this graphic is used by a website (ASP.NET).</p> <p>IE7 &amp; Firefox 3 can't show this image but in Opera 9.5 it works fine.</p> <p>Did anyone run across the same problem before?</p> <p>Edit: Content-type is set to image/png. The image is created with the library from a 3rd party vendor which is not available to the public.</p> <p>Any chance to check the png-file for compliance to the standard?</p>
<p>In principle, both IE7 and FF can display PNG images. As it seems your PNG is not fully compliant to the rendering engines of these browsers (or to the standard?).</p> <p>It is hard to tell where the problem lies exactly without knowing how the image was created. Which lib are you using? Do you have sample code?</p> <p>EDIT (After reading the comment by Yuval A): You could also check whether the HTTP response sent by your web server has the correct content type set for PNG images. This might be needed by browsers to display the image correctly.</p>
<p>Check how your web service is "returning the link" to it. Is it represented correctly on the HTML response? (i.e. in an <strong>IMG</strong> tag with a correct <strong>src</strong>?)</p>
44,347
<p>All the blower fans for part cooling I've seen rotate counter-clockwise when viewed from the intake side. I'm looking to replace mine on an Ender 3 with something stronger, and one of the worst parts of the stock design is that it's offset by about 20 mm versus the nozzle position, requiring awkward duct paths that reduce the flow to get uniform coverage around the newly extruded material. A fan that rotates in the opposite direction, with air exiting on the right-hand size when viewed from the intake side, would be exactly right. Are there such models available, and if so, what is the right terminology to search for them by? Or is there a simple way to modify a fan to reverse its direction?</p>
<p>I see that you have a minimum support angle of 60 degrees -- that may mean Cura Slicer isn't generating supports for that chin. Try changing this minimum to a lower figure -- 51 degrees or lower. From what I've read, most filaments and settings will allow 60 degrees with PLA, but this is the easy first thing to try to get that chin supported.</p> <p>On looking at the photo again, I also wonder if what looks like a bad overhang print is actually supports that didn't separate as they should -- perhaps you only need to adjust your Z skip for supports to get them to come off the actual part better.</p> <p>Following up, I saw a likely cause for this on one of my own prints yesterday -- coincidentally on the chin of a sculpture part. What I observed is that supports for this region, which trailed up the body (as would those for your dragon's chin), likely due to their slenderness, repeatedly got knocked over. The support structure &quot;healed&quot; over several layers after each such incident, but in a very fragile condition that would again get knocked off by a nozzle brush. The solution to this is either to enable Z-hop on retraction (so travel doesn't brush the nozzle across supports printed in the same layer), or to reorient the part so the problem support is shorter and doesn't run right alongside the actual body wall. Z-hop has less effect on other areas of the print.</p>
<p>You need to zoom in on the layers where the support is being generated and check if there is actually support being generated under that area.</p> <p>Additionally, I noticed your support generation setting is &quot;Touching build plate only&quot;. You should change this setting to 'everywhere' because it could be that build plate support cannot directly reach the area in question (so a portion of it is residing over an already printed surface). With this setting changed though, double check the rest of your print is not generating unecesssary supports, and if it is, use support blocker feature to get rid of them.</p> <p>And as a last thought, after changing the setting i mentioned above, also play around with overhang angle and carefully observe how the rendering of the support structures changes (like, really zoom in those gaps and check).</p>
1,958
<p>Are there any good, cross platform (SBCL and CLISP at the very least) easy to install GUI libraries?</p>
<p><a href="http://www.peter-herth.de/ltk/" rel="noreferrer">Ltk</a> is quite popular, very portable, and reasonably well documented through the Tk docs. Installation on SBCL is as easy as saying:</p> <pre><code>(require :asdf-install) (asdf-install:install :ltk) </code></pre> <p>There's also <a href="http://common-lisp.net/project/cells-gtk/" rel="noreferrer">Cells-Gtk</a>, which is reported to be quite usable but may have a slightly steeper learning curve because of its reliance on Cells.</p> <p>EDIT: Note that ASDF-INSTALL is integrated this well with SBCL <em>only</em>. Installing libraries from within other Lisp implementations may prove harder. (Personally, I always install my libraries from within SBCL and then use them from all implementations.) Sorry about any confusion this may have caused.</p>
<p>There's also <a href="http://www.wxcl-project.org/" rel="nofollow noreferrer">wxCL</a>, providing CFFI bindings for <a href="http://www.wxwidgets.org/" rel="nofollow noreferrer">wxWidgets</a>.</p>
13,347
<p>Receiving the following error when attempting to run a CLR stored proc. Any help is much appreciated.</p> <pre><code>Msg 10314, Level 16, State 11, Line 1 An error occurred in the Microsoft .NET Framework while trying to load assembly id 65752. The server may be running out of resources, or the assembly may not be trusted with PERMISSION_SET = EXTERNAL_ACCESS or UNSAFE. Run the query again, or check documentation to see how to solve the assembly trust issues. For more information about this error: System.IO.FileLoadException: Could not load file or assembly 'orders, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. An error relating to security occurred. (Exception from HRESULT: 0x8013150A) System.IO.FileLoadException: at System.Reflection.Assembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark&amp; stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) at System.Reflection.Assembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, Assembly locationHint, StackCrawlMark&amp; stackMark, Boolean throwOnFileNotFound, Boolean forIntrospection) at System.Reflection.Assembly.InternalLoad(AssemblyName assemblyRef, Evidence assemblySecurity, StackCrawlMark&amp; stackMark, Boolean forIntrospection) at System.Reflection.Assembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark&amp; stackMark, Boolean forIntrospection) at System.Reflection.Assembly.Load(String assemblyString) </code></pre>
<p>Ran the SQL commands below and the issue appears to be resolved.</p> <pre><code>USE database_name GO EXEC sp_changedbowner 'sa' ALTER DATABASE database_name SET TRUSTWORTHY ON </code></pre>
<pre><code>ALTER AUTHORIZATION ON DATABASE::mydb TO sa; ALTER DATABASE [myDB] SET TRUSTWORTHY ON GO </code></pre>
9,792
<p>I am having dependency troubles. I have two classes: <code>Graphic</code> and <code>Image</code>. Each one has its own .cpp and .h files. I am declaring them as the following: </p> <p><code>Graphic.h</code>: </p> <pre><code> #include "Image.h" class Image; class Graphic { ... }; </code></pre> <p><code>Image.h</code>:<br> <pre><code> #include "Graphic.h" class Graphic; class Image : public Graphic { ... };</code></pre></p> <p>When I try to compile, I get the following error: </p> <pre> Image.h:12: error: expected class-name before ‘{’ token </pre> <p>If I remove the forward declaration of <code>Graphic</code> from <code>Image.h</code> I get the following error: </p> <pre> Image.h:13: error: invalid use of incomplete type ‘struct Graphic’ Image.h:10: error: forward declaration of ‘struct Graphic’ </pre>
<p>This worked for me:</p> <p>Image.h:</p> <pre><code>#ifndef IMAGE_H #define IMAGE_H #include "Graphic.h" class Image : public Graphic { }; #endif </code></pre> <p>Graphic.h:</p> <pre><code>#ifndef GRAPHIC_H #define GRAPHIC_H #include "Image.h" class Graphic { }; #endif </code></pre> <p>The following code compiles with no error:</p> <pre><code>#include "Graphic.h" int main() { return 0; } </code></pre>
<p>First remove this, you must always have the complete class definition available in order to inherit from a class:</p> <pre><code>class Graphic; </code></pre> <p>Second, remove all references to Image from Graphic.h. The parent will usually not need to know of its childs.</p>
31,571
<p>I'm creating a CSS editor and am trying to create a regular expression that can get data from a CSS document. This regex works if I have one property but I can't get it to work for all properties. I'm using preg/perl syntax in PHP.</p> <h3>Regex</h3> <pre><code>(?&lt;selector&gt;[A-Za-z]+[\s]*)[\s]*{[\s]*((?&lt;properties&gt;[A-Za-z0-9-_]+)[\s]*:[\s]*(?&lt;values&gt;[A-Za-z0-9#, ]+);[\s]*)*[\s]*} </code></pre> <h3>Test case</h3> <pre><code>body { background: #f00; font: 12px Arial; } </code></pre> <h3>Expected Outcome</h3> <pre><code>Array( [0] =&gt; Array( [0] =&gt; body { background: #f00; font: 12px Arial; } [selector] =&gt; Array( [0] =&gt; body ) [1] =&gt; Array( [0] =&gt; body ) [2] =&gt; font: 12px Arial; [properties] =&gt; Array( [0] =&gt; font ) [3] =&gt; Array( [0] =&gt; font ) [values] =&gt; Array( [0] =&gt; 12px Arial [1] =&gt; background: #f00 ) [4] =&gt; Array( [0] =&gt; 12px Arial [1] =&gt; background: #f00 ) ) ) </code></pre> <h3>Real Outcome</h3> <pre><code>Array( [0] =&gt; Array ( [0] =&gt; body { background: #f00; font: 12px Arial; } [selector] =&gt; body [1] =&gt; body [2] =&gt; font: 12px Arial; [properties] =&gt; font [3] =&gt; font [values] =&gt; 12px Arial [4] =&gt; 12px Arial ) ) </code></pre> <p>Thanks in advance for any help - this has been confusing me all afternoon!</p>
<p>That just seems too convoluted for a single regular expression. Well, I'm sure that with the right extentions, an advanced user could create the right regex. But then you'd need an even more advanced user to debug it.</p> <p>Instead, I'd suggest using a regex to pull out the pieces, and then tokenising each piece separately. e.g.,</p> <pre><code>/([^{])\s*\{\s*([^}]*?)\s*}/ </code></pre> <p>Then you end up with the selector and the attributes in separate fields, and then split those up. (Even the selector will be fun to parse.) Note that even this will have pains if }'s can appear inside quotes or something. You could, again, convolute the heck out of it to avoid that, but it's probably even better to avoid regex's altogether here, and handle it by parsing one field at a time, perhaps by using a recursive-descent parser or yacc/bison or whatever.</p>
<p>Try this</p> <pre><code>function trimStringArray($stringArray){ $result = array(); for($i=0; $i &lt; count($stringArray); $i++){ $trimmed = trim($stringArray[$i]); if($trimmed != '') $result[] = $trimmed; } return $result; } $regExp = '/\{|\}/'; $rawCssData = preg_split($regExp, $style); $cssArray = array(); for($i=0; $i &lt; count($rawCssData); $i++){ if($i % 2 == 0){ $cssStyle['selectors'] = array(); $selectors = split(',', $rawCssData[$i]); $cssStyle['selectors'] = trimStringArray($selectors); } if($i % 2 == 1){ $attributes = split(';', $rawCssData[$i]); $cssStyle['attributes'] = trimStringArray($attributes); $cssArray[] = $cssStyle; } } //return false; echo '&lt;pre&gt;'."\n"; print_r($cssArray); echo '&lt;/pre&gt;'."\n"; </code></pre>
29,318
<p>What parts of your application are not coded? I think one of the most obvious examples would be DB credentials - it's considered bad to have them hard coded. And in most of situations it is easy to decide if you want something to be externalized or coded.For me the rules are simple. Some part of the application should be externalized if: </p> <ol> <li>it can and should be changed by non-developer, but not so often to be included in application settings defined in UI (DB credentials, service URLs, etc)</li> <li>it does not require programming language and seems unnatural being coded (localization)</li> </ol> <p>Do you have anything to add?</p> <p>This is a little related to <a href="https://stackoverflow.com/questions/131975/what-are-benefits-of-dependency-injection-container">this question about spring cfg</a>. Spring configuration seems less obvious example for me, because in my practice it is never modified by anyone except the developer. And the road of externalizing can take you far away, to the entire project being "configured", not coded - so where to stop?</p> <p>So please post here some examples from your experience, when you got benefit from having something configured, not coded - like dependency injection configuration in spring, etc. And if you use spring - how often is configuration changed without recompiling?</p>
<p>Anything that needs to differ between different deployments of your application. That is, anything specific to the environment.</p> <p>Examples include:</p> <ul> <li>Database connection strings</li> <li>URLs for web or WCF services</li> <li>Logging configuration</li> </ul>
<p>paths and server names/addresses come to mind..</p>
16,322
<p>I would like to compare two collections (in C#), but I'm not sure of the best way to implement this efficiently.</p> <p>I've read the other thread about <a href="https://stackoverflow.com/questions/43500/is-there-a-built-in-method-to-compare-collections-in-c">Enumerable.SequenceEqual</a>, but it's not exactly what I'm looking for.</p> <p>In my case, two collections would be equal if they both contain the same items (no matter the order).</p> <p>Example:</p> <pre><code>collection1 = {1, 2, 3, 4}; collection2 = {2, 4, 1, 3}; collection1 == collection2; // true </code></pre> <p>What I usually do is to loop through each item of one collection and see if it exists in the other collection, then loop through each item of the other collection and see if it exists in the first collection. (I start by comparing the lengths).</p> <pre><code>if (collection1.Count != collection2.Count) return false; // the collections are not equal foreach (Item item in collection1) { if (!collection2.Contains(item)) return false; // the collections are not equal } foreach (Item item in collection2) { if (!collection1.Contains(item)) return false; // the collections are not equal } return true; // the collections are equal </code></pre> <p>However, this is not entirely correct, and it's probably not the most efficient way to do compare two collections for equality.</p> <p>An example I can think of that would be wrong is:</p> <pre><code>collection1 = {1, 2, 3, 3, 4} collection2 = {1, 2, 2, 3, 4} </code></pre> <p>Which would be equal with my implementation. Should I just count the number of times each item is found and make sure the counts are equal in both collections?</p> <hr> <p>The examples are in some sort of C# (let's call it pseudo-C#), but give your answer in whatever language you wish, it does not matter.</p> <p><strong>Note:</strong> I used integers in the examples for simplicity, but I want to be able to use reference-type objects too (they do not behave correctly as keys because only the reference of the object is compared, not the content).</p>
<p>It turns out Microsoft already has this covered in its testing framework: <a href="http://msdn.microsoft.com/en-us/library/ms243779.aspx" rel="noreferrer">CollectionAssert.AreEquivalent</a></p> <blockquote> <p>Remarks</p> <p>Two collections are equivalent if they have the same elements in the same quantity, but in any order. Elements are equal if their values are equal, not if they refer to the same object.</p> </blockquote> <p>Using reflector, I modified the code behind AreEquivalent() to create a corresponding equality comparer. It is more complete than existing answers, since it takes nulls into account, implements IEqualityComparer and has some efficiency and edge case checks. plus, it's <em>Microsoft</em> :)</p> <pre><code>public class MultiSetComparer&lt;T&gt; : IEqualityComparer&lt;IEnumerable&lt;T&gt;&gt; { private readonly IEqualityComparer&lt;T&gt; m_comparer; public MultiSetComparer(IEqualityComparer&lt;T&gt; comparer = null) { m_comparer = comparer ?? EqualityComparer&lt;T&gt;.Default; } public bool Equals(IEnumerable&lt;T&gt; first, IEnumerable&lt;T&gt; second) { if (first == null) return second == null; if (second == null) return false; if (ReferenceEquals(first, second)) return true; if (first is ICollection&lt;T&gt; firstCollection &amp;&amp; second is ICollection&lt;T&gt; secondCollection) { if (firstCollection.Count != secondCollection.Count) return false; if (firstCollection.Count == 0) return true; } return !HaveMismatchedElement(first, second); } private bool HaveMismatchedElement(IEnumerable&lt;T&gt; first, IEnumerable&lt;T&gt; second) { int firstNullCount; int secondNullCount; var firstElementCounts = GetElementCounts(first, out firstNullCount); var secondElementCounts = GetElementCounts(second, out secondNullCount); if (firstNullCount != secondNullCount || firstElementCounts.Count != secondElementCounts.Count) return true; foreach (var kvp in firstElementCounts) { var firstElementCount = kvp.Value; int secondElementCount; secondElementCounts.TryGetValue(kvp.Key, out secondElementCount); if (firstElementCount != secondElementCount) return true; } return false; } private Dictionary&lt;T, int&gt; GetElementCounts(IEnumerable&lt;T&gt; enumerable, out int nullCount) { var dictionary = new Dictionary&lt;T, int&gt;(m_comparer); nullCount = 0; foreach (T element in enumerable) { if (element == null) { nullCount++; } else { int num; dictionary.TryGetValue(element, out num); num++; dictionary[element] = num; } } return dictionary; } public int GetHashCode(IEnumerable&lt;T&gt; enumerable) { if (enumerable == null) throw new ArgumentNullException(nameof(enumerable)); int hash = 17; foreach (T val in enumerable) hash ^= (val == null ? 42 : m_comparer.GetHashCode(val)); return hash; } } </code></pre> <p>Sample usage:</p> <pre><code>var set = new HashSet&lt;IEnumerable&lt;int&gt;&gt;(new[] {new[]{1,2,3}}, new MultiSetComparer&lt;int&gt;()); Console.WriteLine(set.Contains(new [] {3,2,1})); //true Console.WriteLine(set.Contains(new [] {1, 2, 3, 3})); //false </code></pre> <p>Or if you just want to compare two collections directly:</p> <pre><code>var comp = new MultiSetComparer&lt;string&gt;(); Console.WriteLine(comp.Equals(new[] {&quot;a&quot;,&quot;b&quot;,&quot;c&quot;}, new[] {&quot;a&quot;,&quot;c&quot;,&quot;b&quot;})); //true Console.WriteLine(comp.Equals(new[] {&quot;a&quot;,&quot;b&quot;,&quot;c&quot;}, new[] {&quot;a&quot;,&quot;b&quot;})); //false </code></pre> <p>Finally, you can use your an equality comparer of your choice:</p> <pre><code>var strcomp = new MultiSetComparer&lt;string&gt;(StringComparer.OrdinalIgnoreCase); Console.WriteLine(strcomp.Equals(new[] {&quot;a&quot;, &quot;b&quot;}, new []{&quot;B&quot;, &quot;A&quot;})); //true </code></pre>
<p><a href="https://stackoverflow.com/users/3474/erickson">erickson</a> is almost right: since you want to match on counts of duplicates, you want a <a href="http://commons.apache.org/collections/api-3.1/org/apache/commons/collections/HashBag.html" rel="nofollow noreferrer">Bag</a>. In Java, this looks something like:</p> <pre><code>(new HashBag(collection1)).equals(new HashBag(collection2)) </code></pre> <p>I'm sure C# has a built-in Set implementation. I would use that first; if performance is a problem, you could always use a different Set implementation, but use the same Set interface.</p>
7,273
<p>How do i backup a SQL database using PHP.</p> <p>Is there a vendor agnostic way to do this that conforms to ANSI SQL?</p> <p>If not maybe you can list how to do it for each of the database vendors?</p>
<p>Every database system comes with some program for dumping its contents.</p> <ul> <li>PostgreSQL: <a href="http://www.postgresql.org/docs/8.0/interactive/backup.html" rel="noreferrer"><code>pg_dump</code></a></li> <li>MySQL: <a href="http://dev.mysql.com/doc/refman/5.0/en/mysqldump.html" rel="noreferrer"><code>mysqldump</code></a></li> <li>...</li> </ul> <p>You can simply call that program from PHP using <a href="http://php.net/manual/en/function.system.php" rel="noreferrer"><code>system()</code></a> or <a href="http://php.net/manual/en/function.shell-exec.php" rel="noreferrer"><code>shell_exec()</code></a>.</p> <p>For example, if you use PostgreSQL with enabled <a href="http://www.postgresql.org/docs/8.0/interactive/auth-methods.html#AUTH-IDENT" rel="noreferrer">Ident authentication</a> and want to dump the Database <code>test</code> directly as SQL text to the browser, it's as simple as: <code><pre> &lt;?php header('Content-type: text/plain'); system('pg_dump test'); ?&gt; </pre></code></p> <p>When using MySQL with database user and password stored into <a href="http://dev.mysql.com/doc/refman/5.0/en/option-files.html" rel="noreferrer"><code>~/.my.cnf</code></a>, it is also very simple: <code><pre> &lt;?php header('Content-type: text/plain'); system('mysqldump test'); ?&gt; </pre></code></p> <p>However, <b>don't do this:</b> <code><pre> &lt;?php header('Content-type: text/plain'); system('mysqldump -utestuser -p<b>testpassword</b> test'); ?&gt; </pre></code> because transmitting a password as command line argument is <a href="http://dev.mysql.com/doc/refman/5.0/en/password-security.html" rel="noreferrer">very insecure</a>.</p>
<p>It's a pretty complicated process. I recommend you use phpmyadmin or similar.</p>
32,049
<p>In a installation of WebSphere Application Server with Network Deployment, a node is:</p> <ol> <li>a physical machine</li> <li>an instance of operative system</li> <li>a logical set of WAS instances that is independent of physical machine or OS instance</li> </ol>
<p>Basically,<br> <br> A <b>server</b> is a runtime environment, a process of execution.<br> A <b>node</b> is a grouping of servers that share common configuration. It is a physical machine.<br> A <b>cell</b> is a grouping of nodes into a sigle administrative domain. For websphere, it mean that if you group several servers within a cell, then you can administer them with one Websphere admin console<br> <br> Hope this helps!<br></p>
<p>A Cell is a virtual unit that is built of a Deployment Manager and one or more Nodes. A Node is another virtual unit that is built of a Node Agent and one or more Server instances.</p> <p><a href="http://itdevworld.wordpress.com/2009/05/03/websphere-concepts-cell-node-cluster-server/" rel="nofollow">Here</a> you can find more details including a diagram.</p>
2,677
<p>I am working on an application that detects the most prominent rectangle in an image, then seeks to rotate it so that the bottom left of the rectangle rests at the origin, similar to how IUPR's <a href="http://demo.iupr.org/oscar/oscar.php" rel="noreferrer" title="OSCAR">OSCAR</a> system works. However, once the most prominent rectangle is detected, I am unsure how to take into account the depth component or z-axis, as the rectangle won't always be "head-on". Any examples to further my understanding would be greatly appreciated. Seen below is an example from IUPR's OSCAR system.</p> <p><a href="http://quito.informatik.uni-kl.de/oscar/oscar.php?serverimage=img_0324.jpg&amp;montage=use" rel="noreferrer" title="Rotation Example">alt text http://quito.informatik.uni-kl.de/oscar/oscar.php?serverimage=img_0324.jpg&amp;montage=use</a></p>
<p>You don't actually need to deal with the 3D information in this case, it's just a mappping function, from one set of coordinates to another.</p> <p>Look at affine transformations, they're capable of correcting simple skew and perspective effects. You should be able to find code somewhere that will calculate a transform from the 4 points at the corners of your rectangle.</p> <p>Almost forgot - if "fast" is really important, you could simplify the system to only use simple shear transformations in combination, though that'll have a bad impact on image quality for highly-tilted subjects.</p>
<p>Actually, I think you can get away with something much simpler than <a href="https://stackoverflow.com/questions/122886/fast-plane-rotation-algorithm#122937">Mark's approach</a>.</p> <ol> <li><p>Once you have the 2D coordinates on the skewed image, re-purpose those coordinates as texture coordinates.</p></li> <li><p>In a renderer, draw a simple rectangle where each corner's vertices are texture mapped to the vertices found on the skewed 2D image (normalized and otherwise transformed to your rendering system's texture coordinate plane).</p></li> </ol> <p>Now you can rely on hardware (using OpenGL or similar) to do the correction for you, or you can write your own texture mapper:</p> <p>The aspect ratio will need to be guessed at since we are disposing of the actual 3D info. However, you can get away with just taking the max width and max height of your skewed rectangle.</p> <p><a href="http://www.gamers.org/dEngine/quake/papers/checker_texmap.html" rel="nofollow noreferrer">Perspective Texture Mapping by Chris Hecker</a></p>
14,957
<p>I am writing a batch file, in which I call an EXE to execute. Now, statements after the call to the EXE should not execute till the EXE completes its execution. How can I do it in the batch file (on Windows)?</p>
<pre><code>START /WAIT First.exe START /WAIT Second.exe </code></pre>
<p>You can use</p> <pre><code>PAUSE </code></pre> <p>In batch scripting, but I don't understand your question.</p>
45,388
<p>I've been spending some time looking at Phil Haack's article on <a href="http://haacked.com/archive/2008/11/04/areas-in-aspnetmvc.aspx" rel="noreferrer">Grouping Controllers</a> very interesting stuff.</p> <p>At the moment I'm trying to figure out if it would be possible to use the same ideas to create a plug-in/modular architecture for a project I'm working on.</p> <p>So my question is: Is it possible to have the Areas in Phil's article split across multiple projects?</p> <p>I can see that the name spaces will work themselves out, but I'm concerned about the views ending up in the right place. Is it something that can be sorted out with build rules?</p> <p>Assuming that the above is possible with multiple projects in a single solution, does anyone have any ideas about the best way to make it possible with a separate solution and coding to a predefined set of interfaces? Moving from an Area to a plug-in.</p> <p>I have some experiences with plug-in architecture but not masses so any guidance in this area would be useful.</p>
<p>I did a proof of concept a few weeks ago where I put a complete stack of components: a model class, a controller class and their associated views into a DLL, added/tweaked <a href="https://stackoverflow.com/questions/236972/using-virtualpathprovider-to-load-aspnet-mvc-views-from-dlls">one of the examples</a> of the VirtualPathProvider classes that retrieve the views so they'd address those in the DLL appropriately.</p> <p>In the end, I just dropped the DLL into an appropriately configured MVC app and it worked just like if it had been part of the MVC app from the start. I pushed it a bit further and it worked with 5 of these little mini-MVC plugins just fine. Obviously, you have to watch your references and config dependencies when shuffling it all around, but it did work.</p> <p>The exercise was aimed at plugin functionality for an MVC-based platform I'm building for a client. There are a core set of controllers and views that are augmented by more optional ones in each instance of the site. We're going to be making those optional bits into these modular DLL plugins. So far so good.</p> <p>I wrote up an overview of my prototype and a <a href="http://www.wynia.org/wordpress/2008/12/aspnet-mvc-plugins/" rel="nofollow noreferrer">sample solution for ASP.NET MVC plugins</a> on my site.</p> <p>EDIT: 4 years on, I've been doing quite a few ASP.NET MVC apps with plugins and no longer use the method I describe above. At this point, I run all of my plugins through MEF and don't put controllers into plugins at all. Rather, I make generic controllers that use the routing information to select MEF plugins and hand the work off to the plugin, etc. Just thought I'd add since this answer gets hit a fair bit.</p>
<p>I guess it is possible to leave your views in the plug-in projects. </p> <p>That's my idea: you need a ViewEngine that would call the plugin (probably through an interface) and request the view (IView). The plugin would then instantiate the view not through its url (as an ordinary ViewEngine does - /Views/Shared/View.asp) but through its name of the view )for example via reflection or DI/IoC container).</p> <p>The returning of the view in the plugin might me even hardcoded (simple example follows):</p> <pre><code>public IView GetView(string viewName) { switch (viewName) { case "Namespace.View1": return new View1(); case "Namespace.View2": return new View2(); ... } } </code></pre> <p>...this was just an idea but I hope it could work or just be a good inspiration.</p>
44,186
<p>I'm working on a real time application implemented using in a SOA-style (read loosely coupled components connected via some messaging protocol - JMS, MQ or HTTP).</p> <p>The architect who designed this system opted to use JMS to connect the components. This system is real time so there no need to queue up messages should one component fail (the transaction will simply time out). Further, there is no need for guaranteed delivery or rollback.</p> <p>In this instance, is there any benefit to using JMS over something like an HTTP web service (speed, resource footprint, etc)?</p> <p>One thing that I'm thinking is since the JMS approach requires us to set a thread pool size (the number of components listening to a JMS topic/queue), wouldn't a HTTP service be a better fit since this additional configuration is not needed (a new thread is created for each HTTP request making the application scalable to an "unlimited" number of requests until the server runs out of resources).</p> <p>Am I missing something?</p>
<p>I don't disagree with the points made by S.Lott at all, but here are a couple of points to consider regarding HTTP web services: </p> <ul> <li><p>Your clients only need to know how to communicate via HTTP - a protocol well supported by just about every modern langauge in one form or another. JMS, though popular, is more specialist than HTTP, and so restricts the languages your interconnected systems can use. Perhaps not an issue for your system at the moment, but will you need to plug in other systems later that might struggle to support JMS connectivity? </p></li> <li><p>Standards like WSDL and SOAP which you could levarage for your services are well supported by many langauges and there are plenty of tools around that will generate code to implement both ends of the pipeline (client and server) for you from a WSDL file, reducing the amount of dev you'll have to do. These standards also make it relatively simple to define and publish the specification of the data you'll be passing between your systems, something you'll presumably have to do by hand using a queueing technology like JMS. </p></li> <li><p>On the downside, as pointed out by S.Lott, JMS gives you functionality that you throw away using the (stateless) HTTP protocol: guaranteed ordering &amp; reliability; monitoring; scalability; etc. Are you sure you don't need these, and won't need these going forward? </p></li> </ul> <p>Great question, btw. </p>
<p>I don't know enough about your requirements, but you may be overlooking Manageability, Flexibility and Performance.</p> <p>JMS allows you to monitor and manage the queue. These are features HTTP lacks, and you'd have to build rather than buy from a vendor.</p> <p>Also, There are queues and topics in JMS, allowing multiple subscribers to a single publisher. Not possible in HTTP.</p> <p>While you may not need those things in release 1.0, you might want them in the future.</p> <p>Also, JMS may be able to use other transport mechanisms like named sockets, which reduces the overheads if there isn't all that socket negotiation going on with (almost) every request.</p>
30,322
<p>Is it possible to get the value from the first page to the second page, BUT without <code>FORM</code>?</p> <p>Shall we use</p> <pre><code>window.parent.document.getElementById(&quot;&quot;).value.. </code></pre> <p>But this is working in <code>popup</code> window, but I need this for between two pages which redirecting from the first page to the second page.</p>
<p>If you are redirecting from one page to another, you MUST use form elements to pass from page to page or use a querystring value. That is it, Javascript does NOT have any knowledge of the structure of the previous page..</p>
<p>You could also simply use GET variables by calling <code>site.com/index.php?info=value</code> and escaping the contents of <code>value</code>. The URL can be changed dinamically, like so:</p> <pre><code>&lt;input type="text" id="the_value" /&gt; &lt;a href="#" onclick="return updateURL()" id="the_link"&gt;Click me&lt;/a&gt; &lt;script type="text/javascript"&gt; function updateURL() { document.getElementById('the_link').href = 'site.com/index2.php?info=' + encodeURIComponent(document.getElementById('the_value')); return true; } &lt;/script&gt; </code></pre>
37,684
<p>Accidentally I may forget to describe some parameters or exception throwing (or something else) when documenting methods or classes, etc.</p> <p>Is it possible to run javadoc in such a way that it warns me about missing documentation items?</p> <p>(I use ant script for generating documentation)</p>
<p>I do not know of any javadoc option that will issue a warning about non-documented items.</p> <p>However, if You happen to use Eclipse, take a look at the settings in</p> <p>Window -> Preferences -> Java -> Compiler -> Javadoc</p> <p>There, You can tell Eclipse to issue warnings on undocumented items.</p>
<p>Yes it is, in Eclipse you have incorporate check for everything what you define, so it is possible to put this missing into "warnings" and than you will e able to see where you make mistakes.</p>
29,500
<p>I want a query that returns a list of all the (user) stored procedures in a database by name, with the number of lines of code for each one.</p> <p>i.e.</p> <pre><code>sp_name lines_of_code -------- ------------- DoStuff1 120 DoStuff2 50 DoStuff3 30 </code></pre> <p>Any ideas how to do this?</p>
<pre><code>select t.sp_name, sum(t.lines_of_code) - 1 as lines_ofcode, t.type_desc from ( select o.name as sp_name, (len(c.text) - len(replace(c.text, char(10), ''))) as lines_of_code, case when o.xtype = 'P' then 'Stored Procedure' when o.xtype in ('FN', 'IF', 'TF') then 'Function' end as type_desc from sysobjects o inner join syscomments c on c.id = o.id where o.xtype in ('P', 'FN', 'IF', 'TF') and o.category = 0 and o.name not in ('fn_diagramobjects', 'sp_alterdiagram', 'sp_creatediagram', 'sp_dropdiagram', 'sp_helpdiagramdefinition', 'sp_helpdiagrams', 'sp_renamediagram', 'sp_upgraddiagrams', 'sysdiagrams') ) t group by t.sp_name, t.type_desc order by 1 </code></pre> <p>Edited so it should also now work in SQL Server 2000- 2008 and to exclude Database Diagram-related sprocs and funcs (which appear like user created objects).</p>
<pre><code>select * from sysobjects where type = 'p' </code></pre>
37,192
<p>Are there any free (non-GPL) libraries for .NET that provide IMAP4 server side functionality?</p> <p>E.g. handles the socket level and message handshaking so that an IMAP4 client (such as outlook) can retrieve, read, edit and/or delete messages. </p> <p>I am not trying to connect to an IMAP4 server, I'd like the assistance to implement one.</p>
<p>I know I'm answering my own question, but after yet more searching I think I may have found something matching my needs:</p> <p><a href="http://nmailserver.sourceforge.net/index.php/Main_Page" rel="nofollow noreferrer">NMail</a></p> <p>Features</p> <ul> <li>NMail is a 100% .net application.</li> <li>A Windows installer and setup wizard.</li> <li>ASP.net Webmail.</li> <li>An ASP.net administration site.</li> </ul> <p>IMAP Server Features</p> <ul> <li>Support for ACLs.</li> <li>NTLM authentication (Secure Password Authentication (SPA) under Outlook and Outlook Express).</li> <li>Support for SSL/TLS encryption.</li> <li>SASL plain authentication support (when using an encrypted session).</li> </ul> <p>SMTP Server Features</p> <ul> <li>Support for SSL/TLS encryption.</li> <li>Flexible API for filtering and altering messages. E.g. To remove spam or to rewrite addresses, etc.</li> </ul>
<p>I'm not sure if you have tried Indy (previously a set of Delphi components) - although I am not sure if they do IMAP4 as their web page is a bit blank, as is their CodePlex hub. Go to <a href="http://indy-project.org" rel="nofollow noreferrer">their website</a>. Other than that I'm not sure - even <a href="http://google.co.uk/search?q=c#+imap4+server" rel="nofollow noreferrer">Google</a> only shows clients.</p>
9,227
<p>My question is whether or not Flex's fcsh can be called from within a PHP script. Here is the background:</p> <p>I have been created a simple process that creates a simple quiz/tutorial by converting a text file into a .mxml file and compiling to a .swf file using the mxmlc compiler. This works well from the command line, but I wanted to make the process easier by creating a web-interface to do this. My initial attempts with PHP's exec() function have not worked. The Python scripts I use to create the .mxml file work fine (using exec()), but I have not been able to get the mxmlc compiler to work.</p> <p>After searching on the Web and on this site, I believe that using fcsh (instead of mxmlc) may be the way to go. Using fcsh would certainly compile the .mxml file faster (after the first run), and I think that fcsh can be launched as a service that might be able to be called from PHP.</p> <p>On the other hand, maybe I am approaching this the wrong way. Would it be better to write a Flex application that calls fcsh and avoid using PHP?</p> <p><strong>Edit:</strong> Using fcshctl as hasseg suggested in his answer below worked very well. Thanks Ali.</p>
<p>The problem with calling fcsh from within scripts is that it works as an <em>interactive shell</em> instead of taking command-line arguments, compiling, and returning an exit status. There are different ways to get around this, which I've listed in <a href="http://hasseg.org/blog/?p=194" rel="nofollow noreferrer">this blog post of mine</a>, where I mainly talk about <code>fcshctl</code> (which is my own solution for this,) but at the bottom of the post I've also listed other similar solutions to get fcsh integrated into nonstandard build workflows.</p>
<p>There are a few other ways in php to execute an external script. They are exec(), passthru(), system(), and backticks i.e. the key to the left of the 1 key. Each one has a different purpose and return mechanism.</p> <p>You may have to put the command that executes your executable into a script and call that script via one of these functions.</p>
45,282
<p>Anyone who writes client-side JavaScript is familiar with the DOM - the tree structure that your browser references in memory, generated from the HTML it got from the server. JavaScript can add, remove and modify nodes on the DOM tree to make changes to the page. I find it very nice to work with (browser bugs aside), and very different from the way my server-side code has to generate the page in the first place.</p> <p>My question is: what server-side frameworks/languages build a page by treating it as a DOM tree from the beginning - inserting nodes instead of echoing strings? I think it would be very helpful if the client-side and server-side code both saw the page the same way. You could certainly hack something like this together in any web server language, but a framework dedicated to creating a page this way could make some very nice optimizations.</p> <p>Open source, being widely deployed and having been around a while would all be pluses.</p>
<p>You're describing <a href="http://www.youtube.com/watch?v=1QD9XQm_Jd4" rel="nofollow noreferrer">Rhino on Rails</a>, which is not out but will be soon. Similarly, <a href="http://www.aptana.com/jaxer/" rel="nofollow noreferrer">Aptana Jaxer</a>, however RnR will include an actual framework (Rails) whereas Jaxer is just the server technology.</p>
<p>I see where you're coming from but it's all a bit moot isn't it. You can't send anything but rendered content to the browser, and you have to do it all in one go (AJAX aside). There's no value from what you are suggesting (from what I can see) as even if you build it tree-like, you're still only building a page which is sent wholesale to the client.</p>
3,569
<p>How can I execute <code>a.exe</code> using the Cygwin shell?</p> <p>I created a C file in Eclipse on Windows and then used Cygwin to navigate to the directory. I called gcc on the C source file and <code>a.exe</code> was produced. I would like to run <code>a.exe</code>.</p>
<p>./a.exe at the prompt</p>
<p>Just call it</p> <pre><code>&gt; a </code></pre> <p>Make sure it will be found (path).</p>
5,662
<p>i wind up having about 20 different parameters in the constructor of the model class, one for each service? Is this normal or a sign that something is off.</p>
<p>I think, categorically, that your controller is interacting with too many services. I've not seen your code - so I'm going off assumptions - but it seems to me that your controller is composing business logic by calling numerous "small" services, rather than drawing on fewer, "larger" services that compose business logic from the smaller services.</p> <p>Have a look around for information about "orchestration services" vs "entity" or "capability" services and you'll see what I mean. If you create orchestration services that provide your controllers with the logic they require, your architecture is improved because your controllers really should not contain any business logic at all.</p> <p>I really think that the number of services you consume is the issue here. IoC containers may go some way to resolve how you bind types to your injection parameters etc., but I think the problem is your architecture at this point.</p>
<p>As @Matt said a dependency injection could help you here and sprint.NET is a good one and there are several others.</p> <p>Seeing as you mention MVP in particular, you should at least look at <a href="http://www.microsoft.com/downloads/details.aspx?FamilyId=1643758B-2986-47F7-B529-3E41584B6CE5&amp;displaylang=en" rel="nofollow noreferrer">Ent Lib 4.1</a> which now has <strong>Unity</strong>, Microsoft's take on DI. Their <a href="http://www.codeplex.com/entlib" rel="nofollow noreferrer">codeplex</a> site is probably a good place to start if this is new. </p> <p>There are also <a href="http://www.codeplex.com/websf" rel="nofollow noreferrer">software factories</a> that <strong>integrate with visual studio</strong> and give you tools for creating MVP for web sites as linked or web services. These come from pattern and practices too.</p>
43,184
<p>I have some formulas in my reports, and to prevent divsion by zero I do like this in the expression field:</p> <p>=IIF(Fields!F1.Value &lt;> 0, Fields!F2.Value/Fields!F1.Value, 0)</p> <p>This normally works fine, but when both F1 and F2 are zero, I get "#Error" in the report, and I get this warning: "The Value expression for the textbox ‘textbox196’ contains an error: Attempted to divide by zero."</p> <p>Why is that?</p>
<p>There has to be a prettier way than this, but this should work:</p> <pre><code>=IIF(Fields!F1.Value &lt;&gt; 0, Fields!F2.Value / IIF(Fields!F1.Value &lt;&gt; 0, Fields!F1.Value, 42), 0) </code></pre>
<p>However, you can use</p> <pre><code>if Fields!F1.Value &lt;&gt; 0 then Fields!F2.Value/Fields!F1.Value else 0 </code></pre> <p>which should work, since it doesn't evaluate the then clause if the "if" section is false.</p>
19,169
<p>I have a couple of hobby C programming projects that I would like to start. I am looking for an open source library that has a liberal license (I want credit, but pretty much anybody can use). The library needs to have strings better than the C standard library and some portable threading primitives.</p> <p>I am considering <a href="http://library.gnome.org/devel/glib/" rel="noreferrer">GLib</a> and <a href="http://apr.apache.org/" rel="noreferrer">APR</a>. What is your practical experience? Which is the better foundational C library? Are there any other libraries filling the same niche?</p>
<p>I think glib is generally superior to apr. glib has many more datastructures as portable libraries. e.g hash tables, all kind of lists, queues, stacks, dynamic array, also for argument parsing, file io has it's own wrappers also and memory managment is easy modifiable. E.g you can easily make glib use the Boehm Weisser GC this is AFAIKT never been done or easy possible with Apache. I would decide a bit different. If you need a more useful library of data structures glib is a better equipped. If it comes to GUI stuff than libapr has nothing whereas glib has gdk/gtk+ and a lot of stuff for gnome if you like. </p> <p>However, if it comes to network stuff, libapr definitely has an edge over glib. </p> <p>So my suggestions is</p> <ul> <li><strong>Desktop programming</strong>: Use GTK+ and glib.</li> <li><strong>Network stuff</strong>: Use apr, but be assured glib does have all this portable stuff also.</li> </ul>
<p>Is there a reason you wouldn't want to use the c++ stl? Even if you are writing "c-style" code without classes, you can use c++ strings and data structure.</p> <p>There are plenty of valid reasons to stick to C, of course. If that's the case, I would second the recommendation for glib. APR is more of a portability layer than a utility library.</p>
37,986
<p>I would like to parse a string such as <code>p1=6&amp;p2=7&amp;p3=8</code> into a <code>NameValueCollection</code>.</p> <p>What is the most elegant way of doing this when you don't have access to the <code>Page.Request</code> object?</p>
<p>There's a built-in .NET utility for this: <a href="http://msdn.microsoft.com/en-us/library/ms150046.aspx" rel="noreferrer">HttpUtility.ParseQueryString</a></p> <pre class="lang-cs prettyprint-override"><code>// C# NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring); </code></pre> <pre class="lang-vb prettyprint-override"><code>' VB.NET Dim qscoll As NameValueCollection = HttpUtility.ParseQueryString(querystring) </code></pre> <p>You may need to replace <code>querystring</code> with <code>new Uri(fullUrl).Query</code>.</p>
<p>This is my code, I think it's very useful: </p> <pre><code>public String GetQueryString(string ItemToRemoveOrInsert = null, string InsertValue = null ) { System.Collections.Specialized.NameValueCollection filtered = new System.Collections.Specialized.NameValueCollection(Request.QueryString); if (ItemToRemoveOrInsert != null) { filtered.Remove(ItemToRemoveOrInsert); if (!string.IsNullOrWhiteSpace(InsertValue)) { filtered.Add(ItemToRemoveOrInsert, InsertValue); } } string StrQr = string.Join("&amp;", filtered.AllKeys.Select(key =&gt; key + "=" + filtered[key]).ToArray()); if (!string.IsNullOrWhiteSpace(StrQr)){ StrQr="?" + StrQr; } return StrQr; } </code></pre>
9,416
<p>I installed Visual Studio (Web Developer in this case) Express Edition and was reading through the EULA. One thing that did not jump out at me was what I was allowed to use the software for (private, commercial, etc). </p> <p>Does anyone know if you are allowed to sell/distribute the code you create in these Express editions? I know they are geared toward the hobbyist and other software licenses, like the Student and Teacher editions of Office, do not allow commercial use for the software.</p> <p>I'd like to eventually start giving out code either via OSS licenses like BSD or GPL and even maybe sell some code but not sure I can do that with the Express Editions.</p>
<p><a href="http://www.microsoft.com/express/support/faq/" rel="noreferrer">Yes</a>, you can use the Express Editions for commercial use.</p>
<p>You cannot create an executable and then run it on another computer unless that computer has Visual Studio Express installed on it. Don't believe any comments to the contrary. I have tried all the suggestions on how to do this and they don't work.</p>
21,661
<p>I hope this isn't considered a duplicate since it's more pointed than similar questions (I'm curious about a specific weakness in C# to VB.net conversion utilities).</p> <p>I've been looking at using a tool like this <a href="http://www.developerfusion.com/tools/convert/csharp-to-vb/" rel="nofollow noreferrer">.net code converter</a> to convert a class library to VB since I'm the only one in my group comfortable with C#. The problem I've run into is that it doesn't generate proper VB for automatic properties. It creates empty get/set routines. </p> <p>So this:</p> <pre><code>public string TransactionType { get; private set; } </code></pre> <p>Becomes this:</p> <pre><code>Public Property TransactionType() As String Get End Get Private Set(ByVal value As String) End Set End Property </code></pre> <p>The tools linked <a href="https://stackoverflow.com/questions/102956/c-vbnet-conversion" title="here">here</a> and <a href="https://stackoverflow.com/questions/88359/what-is-the-best-c-to-vbnet-converter">here</a> have similar issues - some create valid properties, but they don't respect the access level of the set routine.</p> <p>Side question - If you were going to fix the converter on DeveloperFusion, would you have it return something like this?</p> <pre><code>Private _TransactionType As String Public Property TransactionType() As String Get Return _TransactionType End Get Private Set(ByVal value As String) _TransactionType = value End Set End Property </code></pre>
<p>We've now updated the code generator to support this scenario. If you spot any others that we're not doing very well, please do drop me a line.</p>
<p>As an answer to your side question: yes, that code is pretty much exactly what I'd get it to produce. You can't get it to do exactly what the C# code does, which is to make the name of the variable "unspeakable" (i.e. impossible to reference in code) but that's probably close enough.</p>
21,052
<p>I have a document library with a custom column named "compound" which is just text.</p> <p>I want to put a filter (input text box) on that document library page so the view shows only the items where the compound column contains my typed-in text. Optimally, wildcards such as * or ? or full regular expressions could be supported... but for now, I just need a "contains".</p> <p>The out-of-the-box text filter seems to only support an exact match.</p> <p>The result output would be identical to what I would see if I created a new view, and added a filter with a "contains" clause.</p> <p>Third party solutions are acceptable.</p>
<p>The place where this will fail is if you have to do what's called "shard walking" - which is finding out all the data across a bunch of different users. That particular kind of "query" will have to be done programmatically, asking each of the SQLite databases in turn - and will very likely be the slowest aspect of your site. It's a common issue in any system where data has been "sharded" into separate databases.</p> <p>If all the of the data is self-contained to the user, then this should scale pretty well - the key to making this an effective design is to know how the data is likely going to be used and if data from one person will be interacting with data from another (in your context).</p> <p>You may also need to watch out for file system resources - SQLite is great, awesome, fast, etc - but you do get some caching and writing benefits when using a "standard database" (i.e. MySQL, PostgreSQL, etc) because of how they're designed. In your proposed design, you'll be missing out on some of that.</p>
<p>Having one database per user would make it really easy to restore individual users data of course, but as <a href="https://stackoverflow.com/users/1786/john-sheehan">@John</a> said, schema changes would require some work.</p> <p>Not enough to make it hard, but enough to make it non-trivial.</p>
15,674
<p>I apologize for asking such a generalized question, but it's something that can prove challenging for me. My team is about to embark on a large project that will hopefully drag together all of the random one-off codebases that have evolved through the years. Given that this project will cover standardizing logical entities across the company ("Customer", "Employee"), small tasks, large tasks that control the small tasks, and utility services, I'm struggling to figure out the best way to structure the namespaces and code structure.</p> <p>Though I guess I'm not giving you enough specifics to go on, <strong>do you have any resources or advice on how to approach splitting your domains up logically</strong>? In case it helps, most of this functionality will be revealed via web services, and we're a <strong>Microsoft</strong> shop with all the latest gizmos and gadgets.</p> <ul> <li>I'm debating one massive solution with subprojects to make references easier, but will that make it too unwieldy? </li> <li>Should I wrap up legacy application functionality, or leave that completely agnostic in the namespace (making an <code>OurCRMProduct.Customer</code> class versus a generic <code>Customer</code> class, for instance)? </li> <li>Should each service/project have its own <code>BAL</code> and <code>DAL</code>, or should that be an entirely separate assembly that everything references? </li> </ul> <p>I don't have experience with organizing such far-reaching projects, only one-offs, so I'm looking for any guidance I can get.</p>
<p>There's a million ways to skin a cat. However, the simplest one is always the best. Which way is the simplest for you? Depends on your requirements. But there are some general rules of thumb I follow.</p> <p>First, reduce the overall number of projects as much as possible. When you compile twenty times a day, that extra minute adds up. </p> <p>If your app is designed for extensibility, consider splitting your assemblies along the lines of design vs. implementation. Place your interfaces and base classes in a public assembly. Create an assembly for your company's implementations of these classes. </p> <p>For large applications, keep your UI logic and business logic separate. </p> <p>SIMPLIFY your solution. If it looks too complex, it probably is. Combine, reduce.</p>
<p>Large solutions with lots of projects can be quite slow to compile, but are easier to manage together.</p> <p>I often have Unit test assemblies in the same solution as the ones they're testing, as you tend to make changes to them together.</p>
3,329
<p>Here's what I got so far (that doesn't work). At this point I thought my target was Ansi encoded, but I really don't want to have to know at this point. My browser seems to be able to determine what encoding to use, How can I?</p> <pre><code>static void GetUrl(Uri uri, string localFileName) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); HttpWebResponse response; response = (HttpWebResponse)request.GetResponse(); // Save the stream to file Stream responseStream = response.GetResponseStream(); StreamReader reader = new StreamReader(responseStream, Encoding.Default); Stream fileStream = File.OpenWrite(localFileName); using (StreamWriter sw = new StreamWriter(fileStream, Encoding.Default)) { sw.Write(reader.ReadToEnd()); sw.Flush(); sw.Close(); } } </code></pre> <hr> <p><strong>After answers</strong> (currently only tested on a UTF-8 site):</p> <pre><code>static void GetUrl(Uri uri, string localFileName) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); try { // Hope GetEncoding() knows how to parse the CharacterSet Encoding encoding = Encoding.GetEncoding(response.CharacterSet); StreamReader reader = new StreamReader(response.GetResponseStream(), encoding); using (StreamWriter sw = new StreamWriter(localFileName, false, encoding)) { sw.Write(reader.ReadToEnd()); sw.Flush(); sw.Close(); } } finally { response.Close(); } } </code></pre>
<p>There are three ways how web-browsers try to detect character encoding.</p> <p>Look for (if it's HTML):</p> <pre><code>&lt;meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"&gt; </code></pre> <p>or (for XHTML)</p> <pre><code>&lt;?xml version="1.0" encoding="ISO-8859-1"?&gt; </code></pre> <p>or sometimes it's even specified in http header</p> <pre><code>Content-Type: text/html; charset=ISO-8859-1 </code></pre>
<p>You should be looking for the encoding the server sends the response in. <code>Encoding.Default</code> does not cut the mustard here. :-)</p> <pre><code>Stream responseStream = response.GetResponseStream(); Encoding enc = Encoding.GetEncoding(response.CharacterSet); StreamReader reader = new StreamReader(responseStream, enc); Stream fileStream = File.OpenWrite(localFileName); using (StreamWriter sw = new StreamWriter(fileStream, enc)) { /* ... */ } </code></pre> <p>To be sure, you could convert everything to UTF-8 and store your file as UTF-8 always. That way you are never left with the need to guess the encoding when reading the file.</p>
37,493
<p>I need to use a datetime.strptime on the text which looks like follows.</p> <p>"Some Random text of undetermined length Jan 28, 1986"</p> <p>how do i do this?</p>
<p>Using the ending 3 words, no need for regexps (using the <code>time</code> module):</p> <pre><code>&gt;&gt;&gt; import time &gt;&gt;&gt; a="Some Random text of undetermined length Jan 28, 1986" &gt;&gt;&gt; datetuple = a.rsplit(" ",3)[-3:] &gt;&gt;&gt; datetuple ['Jan', '28,', '1986'] &gt;&gt;&gt; time.strptime(' '.join(datetuple),"%b %d, %Y") time.struct_time(tm_year=1986, tm_mon=1, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=28, tm_isdst=-1) &gt;&gt;&gt; </code></pre> <p>Using the <code>datetime</code> module:</p> <pre><code>&gt;&gt;&gt; from datetime import datetime &gt;&gt;&gt; datetime.strptime(" ".join(datetuple), "%b %d, %Y") datetime.datetime(1986, 1, 28, 0, 0) &gt;&gt;&gt; </code></pre>
<p>You may find <a href="https://stackoverflow.com/questions/285408/python-module-to-extract-probable-dates-from-strings">this</a> question useful. I'll give the answer I gave there, which is to use the <a href="http://labix.org/python-dateutil" rel="nofollow noreferrer">dateutil</a> module. This accepts a fuzzy parameter which will ignore any text that doesn't look like a date. ie:</p> <pre><code>&gt;&gt;&gt; from dateutil.parser import parse &gt;&gt;&gt; parse("Some Random text of undetermined length Jan 28, 1986", fuzzy=True) datetime.datetime(1986, 1, 28, 0, 0) </code></pre>
44,140
<p>There are plenty of ways to provide a dynamic style/theme for a web site, but I am looking for some help on some best practices or techniques that have worked well for others.</p> <p>I am creating a web site that needs to provide the ability for customers to create or specify their own colors, style, theme, or layout. I'm not convinced how much flexibility I need yet, but basically I need to provide Branding capabilities.</p> <p>I will be using ASP.NET, and am open to any ideas that will fit within the ASP.NET framework.</p>
<p>Using Themes for ASP.NET 2 and greater will provide you everything you need for this.</p>
<p>Best way to handle it would be to make a nice CSS document that will specify all the areas that you would like to offer customization, such as header background image, background and text colors, etc. Then build application code to allow specification of which theme to load, and bring up that CSS file.</p>
10,952
<p>I need to make OK and Cancel buttons in my HTML, and I'd like them to be a fixed width so the two buttons are the same size. For example, like this:</p> <pre><code>&lt;style&gt; button.ok_cancel { width: 50px; background-color: #4274af; font-size: 9px; line-height: 12px; color: #fff; cursor: pointer; text-transform: uppercase; padding: 1px; border: 0px; margin: 0 0 0 5px; text-align: center; letter-spacing: 1px; } &lt;/style&gt; &lt;button class="ok_cancel" onclick="do_cancel()"&gt;Cancel&lt;/button&gt; </code></pre> <p>But now I'm localizing the text, and the translation for "Cancel" can be too wide for the button. I want the button to be its fixed width of 50 pixels if the string fits, but to expand in width if the string is wider. A fixed amount of side padding would be used to keep the button looking good.</p> <p>I know I probably can't do this with pure CSS, but what's the simplest HTML I can use that will give me the effect I want? </p>
<p>I worked from twodayslate's answer and ended up with this:</p> <pre><code>/* Browser hack! This is for everyone: */ button { display: inline; cursor: pointer; padding: 6px 6px; width: 50px; overflow: visible; } /* and this is for non-IE browsers: */ html&gt;body button { min-width: 50px; width: auto; } </code></pre> <p>IE wants a specified width and overflow visible, the other browsers want a min-width and width auto. The CSS hack lets IE see one set of properties and the other browser see another set.</p>
<p>Not sure but:</p> <blockquote> <p>button { min-width: 50px; width: auto; }</p> </blockquote> <p>LMK if this works, it should work as long as it isn't floated.</p>
45,780
<p>I have two constructor :</p> <pre><code>function clsUsagerEmailUserName($nickName, $email) { $this-&gt;nickName = $nickName; $this-&gt;email = $email; } function clsUsagerEmailUserName($email) { $this-&gt;email = $email; } </code></pre> <p>But this is not working? What's wrong, isn't supposed to be OO at this version of PHP? (I just migrate from PHP4)</p>
<p>PHP5 doesn't allow overloaded constructor.</p> <p>Alternativly you can use function to set or you can use this trick (found at EE):</p> <pre><code>function __construct ($var1, $var2 = null) { if (isset($var2)) { //Do one thing } else { //Do another } } </code></pre>
<p>You could use the func_get_args to count the number of passed arguments then match that up to a method.</p> <pre><code>abstract class AlmostPolymorphicObject { public function __construct() { $args = func_get_args(); $argsCount = count($args); $callback = array($this, '_construct'.$argsCount); if (!is_callable($callback)) { throw new Exception('no valid constructor for param count '.$argsCount); } return call_user_func_array($callback, $args); } } class FooBar extends AlmostPolymorphicObject { private function _construct0() { } private function _construct1($var1) { } private function _construct2($var1, $var2) { } } $var = new FooBar(); // would run _construct0 $var = new FooBar('var'); // would run _construct1 $var = new FooBar('var','var'); // would run _construct2 $var = new FooBar('var','var', 'asdasd'); // would throw error 'no valid constructor for param count 3' </code></pre>
45,103
<p>I need to grab the height of the window and the scrolling offset in jQuery, but I haven't had any luck finding this in the jQuery docs or Google.</p> <p>I'm 90% certain there's a way to access height and scrollTop for an element (presumably including the window), but I just can't find the specific reference.</p>
<p>From jQuery Docs:</p> <pre><code>const height = $(window).height(); const scrollTop = $(window).scrollTop(); </code></pre> <p><a href="http://api.jquery.com/scrollTop/" rel="noreferrer">http://api.jquery.com/scrollTop/</a><br> <a href="http://api.jquery.com/height/" rel="noreferrer">http://api.jquery.com/height/</a></p>
<p>If you need to scroll to a point of an element. You can use Jquery function to scroll it up/down.</p> <pre><code>$('html, body').animate({ scrollTop: $("#div1").offset().top }, 'slow'); </code></pre>
39,029
<p>The questions so far are pretty strongly geared towards hobbyist/consumer FFF machines. That's not necessarily bad, since that's where most legit questions will come from. (Not much reason to ask questions about a plug-and-play industrial machine.) But it's a pretty important scope distinction. So far, askers are not really providing enough technology/make/model info to tell what kind of equipment they're running. An experienced expert can tell by context what the intention is, but that's not really scalable.</p> <p>Sub-questions:</p> <ol> <li>Will other AM technologies like SLA/DLP be included? If so, a pretty rigorous clarification and tagging effort will be required to separate out these other technologies.</li> <li>Are industrial machines in scope? </li> </ol>
<p>I think all additive manufacturing techniques should be in scope. Given their popularity with consumers, most questions will naturally be regarding FDM printers. I don't see why that should rule out other techniques though: SLA machines are becoming increasingly accessible, and I think there's a $5000 SLS machine on the horizon.</p> <p>I don't see any reason to rule out industrial machines either. With the current user base those questions might go unanswered but there's no reason this site couldn't attract industry experts when it goes public.</p> <p>I do agree that questions should specify the make/model of 3D printer the question relates to if it's not obvious from the context.</p>
<p>On the question/answer trajectory we're currently following, the group would be best titled "Consumer/Hobbyist FFF 3D Printing" and not just a generic "3D Printing" group. I think some pretty aggressive moderation / self-policing will be required to make people add the necessary tags to clarify this. </p> <p>Edit: to be clear, I'm not saying we should only include hobbyist FDM printers, I'm saying we need to require clear labeling if we intend to serve more than one type of users. </p>
14
<p>What happens to the name/value pairs stored inside a form's resx file? Are they compiled into the binary when I compile my project?</p> <p>For my particular project, I would like the ability to edit one of these values manually without recompiling (app.config-style), is there a simple way to do this?</p> <p><strong>EDIT:</strong> Some people seem to not be getting my question. When doing WinForms, if the set-up inside of InitializeComponents() depends on the form's resource file, simply setting the build action to copy always and the content type to content breaks the form. I am sure that there is a simple solution, but not having worked with resource files before am confused as to what it would be.</p>
<p>If you put the values in the .resx file, by default they get compiled into your assembly (or a satellite resource assembly).</p> <p>If you want the ability to edit the values at runtime, you should really use either app.config or the registry. I personally prefer the app.config file.</p> <p>The easiest way to put the value in the app.config file would be to use the Settings tab in the project Properties.</p> <p>If you insist on keeping your values in an .resx file, I guess you could treat that particular .resx file as a an XML content file and just copy it to the output directory. I am not sure what framework classes are there to help you with parsing this file and consuming its content, though. You might have to resort to XmlDocument and your own XL parsing to extract/modify the values.</p>
<p>Go to the properties for your .resx file in Visual Studio and set the Build Action to Content. That should set it to not compile and you'll be able to copy over the .resx file with the site and modify it anytime. </p> <p>You may want to clean any compiled resources out of your project, I'm not sure if ASP.NET will look for those first since they have been compiled once.</p> <p>EDIT: just saw you were referencing WinForms, not sure about that.</p>
26,992
<p>TFS2008. I'd like to track task points on a Task work item, but there isn't anywhere (other than the description) to record this. I'd like to add a dropdown with 0, 1, 2, 3, 5, 8, etc, so these task points can be exported in reports.</p>
<p>Use the process template editor, available as part of the <a href="http://msdn.microsoft.com/en-ca/tfs2008/bb980963.aspx" rel="nofollow noreferrer">Visual Studio Team System 2008 Team Foundation Server Power Tools</a>.</p>
<p>I created a web cast awhile ago that demonstrates this tool. it covers a couple of really basic scenarios. It can be accessed <a href="http://homepage.mac.com/stevevrporter/blog/Ta.html#vyk233532924" rel="nofollow noreferrer">here</a>.</p> <p>Ta.</p> <p>Steve Porter</p>
7,628
<p>I have the following code, I'm trying to get a table with 4 columns across. If I run out of columns, create a new row and make 4 more coumns. rinse. lather. repeat.</p> <pre><code>&lt;tbody&gt; &lt;% int i = 0; foreach (ItmXtnMultimedia multimedia in ViewData.Model.ItmXtnMultimedia) { if (i%4 == 0 &amp;&amp; i== 0) { %&gt;&lt;tr&gt;&lt;% } if (i%4 == 0 &amp;&amp; i != 0) { %&gt;&lt;/tr&gt;&lt;tr&gt;&lt;% } %&gt; &lt;td&gt;&lt;%= multimedia.ImgTag100 %&gt;&lt;/td&gt; &lt;% i++; } %&gt; </code></pre> <p></p> <p>It works, but it sucks. Is there something built in to the framework or an extension method I can use? I guess I could roll my own, but figured there had to be something out there.</p>
<p>This is a good place to create an extension method. Here's some almost-compilable C# pseudocode:</p> <pre><code>public static void IDunnoWhatToCallThis&lt;T&gt;( this HtmlHelper me, T[] items, int columns, Action headerTemplate, Action&lt;T&gt; itemTemplate, Action newRowTemplate, Action footerTemplate ) { headerTemplate(); for(int i = 0;i &lt; items.Length; i++) { if(i != 0 &amp;&amp; i%columns == 0) newRowTemplate(); itemTemplate(items[i]); } footerTemplate(); } </code></pre> <p>And here's an example in use:</p> <pre><code>&lt;% Html.IDunnoWhatToCallThis( ViewData.Model.ItmXtnMultimedia, 4, () =&gt; %&gt;&lt;table&gt;&lt;tr&gt;&lt;%, (item) =&gt; %&gt;&lt;td&gt;&lt;%= item.ImgTag100 %&gt;&lt;/td&gt;&lt;%, () =&gt; %&gt;&lt;/tr&gt;&lt;tr&gt;&lt;%, () =&gt; %&gt;&lt;/tr&gt;&lt;/table&gt;&lt;%);%&gt; </code></pre> <p>I LOVE helpers like this, mixing inline code, lambdas and markup. Its like watching magic.</p>
<p>What about a little refactor?</p> <pre><code>&lt;% foreach (ItmXtnMultimedia multimedia in ViewData.Model.ItmXtnMultimedia) { manageColumnsForMe( 4 ) %&gt;&lt;td&gt;&lt;%= multimedia.ImgTag100 %&gt;&lt;/td&gt;&lt;% } %&gt; </code></pre> <p>And the put the other code in a function using a static variable to store i</p> <p>You can reuse the same function with different number of columns</p>
36,589
<p>I could only find the function <code>confirm()</code> that gives OK/Cancel buttons. Is there any way to give Yes/No buttons?</p>
<p>Javascript offers 3 modal boxes. <code>prompt</code>, <code>confirm</code> and <code>alert</code>. None of those satisfy your request. </p> <p>There are a plethora of js modal popup solutions. Here's an example.</p> <ul> <li><a href="https://github.com/okonet/modalbox" rel="nofollow noreferrer">ModalBox</a></li> </ul>
<p>Use dialog box to display yes or no</p> <pre><code> &lt;div id="dialog_box" class="mnk-modal-bg" style="display:none"&gt; &lt;div id="dbg" class="mnk-modal-box"&gt; &lt;i class="uk-icon-exclamation-triangle" style="color:#757575; padding-right:5px;"&gt; &lt;/i&gt;Confirm? &lt;div class="uk-text-center" style="margin-top:10px;"&gt; &lt;button class="md-btn md-btn-small md-btn-primary" id="ok_btn"&gt; &lt;i class="uk-icon-save" style="padding-right:3px;"&gt;&lt;/i&gt;OK &lt;/button&gt; &lt;button class="md-btn md-btn-small md-btn-danger" id="close_btn"&gt; &lt;i class="uk-icon-remove" style="padding-right:3px;"&gt;&lt;/i&gt;Cancel &lt;/button&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p></p> <pre><code>&lt;script&gt; $("#ok_btn").click(function(){ alert("OK"); $("#dialog_box").hide(); }); $("#close_btn").click(function(){ alert("CANCEL"); $("#dialog_box").hide(); }); &lt;/script&gt; </code></pre>
3,971
<p>I have a Creality Ender 5 Pro which has been working properly for some time. During my last print, the axis motors just suddenly stopped working while the extruder motor continued to work properly.</p> <p>In fact, when I connect the extruder motor wire to any of the axis motors, they respond correctly (mimicking the extruder motor) but neither works or moves when connected to its own wire(s). As a result the printer does not print anymore.</p> <p>Here's what I've tried:</p> <ul> <li>Switching the wires around to check if any motors are damaged (none are).</li> <li>Restarting the Creality</li> <li>Checking the output on the power source (which is 24 V and about 14 A)</li> <li>Checking to make sure all motor wires are connected correctly on the SKR MINI CONTROLLER (all seem fine) and checking that the board is powered.</li> <li>All external connections also seem fine.</li> </ul> <p>I'm quite confused why the axis motors would not be working all of a sudden. I'll appreciate your help if you've faced this problem before.</p>
<p>The Creality V1.1.5 board was fried. I replaced it with a BIGTREETECH SKR MINI E3 V2.0 32BIT CONTROLLER. After struggling to find a corresponding firmware for the Ender 5 pro, the axis motors worked correctly.</p>
<p>Usually, steppers not working can be found when the lines are broken. Often this is an unplugged Stepper, but OP checked that.</p> <p>That 3 steppers at once failed could indicate a bad firmware update, which OP didn't do. So it is sadly a case of blue smoke from the board. Most likely the stepper drivers are either shortened out or get no signal.</p> <p>I am sorry, but replacement seems necessary.</p>
1,866
<p>I have a Tapestry PropertyModel for gender. Right now the dropdown just shows Male and Female because those are the only values in my model. I'd like to add a "Choose an Option" option. Is there a standard way to do this without having to add a fake value to my model? I'd also like it to be smart enough to know that if the field is required, they can't leave it set to "Choose an Option".</p>
<p>On Tapestry 5 you just set the blankLabel property.</p> <p>On Tapestry 4 it is easier to just add that feature to your PropertyModel or wrap it on a LabeledPropertySelectionModel as Brian already mentioned (you can look that class up in the JavaDoc for your version of Tapestry).</p> <p>On Tapestry 3 you have to add that feature to your model because LabeledPropertySelectionModel was introduced in version 4.</p>
<p>One solution is to use the LabeledPropertySelectionModel to wrap the real model like:</p> <pre><code>new LabeledPropertySelectionModel(new GenderModel(), "Choose an Option") </code></pre> <p>The JavaDoc for that class says:</p> <blockquote> <p>Decorates an underlying IPropertySelectionModel adding an initial property. The label option, and value of the initial property are configurable.</p> </blockquote>
32,600
<p>I've got a C# class with a <code>Dispose</code> function via <code>IDisposable</code>. It's intended to be used inside a <code>using</code> block so the expensive resource it handles can be released right away.</p> <p>The problem is that a bug occurred when an exception was thrown before <code>Dispose</code> was called, and the programmer neglected to use <code>using</code> or <code>finally</code>.</p> <p>In C++, I never had to worry about this. The call to a class's destructor would be automatically inserted at the end of the object's scope. The only way to avoid that happening would be to use the new operator and hold the object behind a pointer, but that required extra work for the programmer isn't something they would do by accident, like forgetting to use <code>using</code>.</p> <p>Is there any way to for a <code>using</code> block to be automatically used in C#?</p> <p>Many thanks.</p> <p>UPDATE:</p> <p>I'd like to explain why I'm not accepting the finalizer answers. Those answers are technically correct in themselves, but they are not C++ style destructors.</p> <p>Here's the bug I found, reduced to the essentials...</p> <pre><code>try { PleaseDisposeMe a = new PleaseDisposeMe(); throw new Exception(); a.Dispose(); } catch (Exception ex) { Log(ex); } // This next call will throw a time-out exception unless the GC // runs a.Dispose in time. PleaseDisposeMe b = new PleaseDisposeMe(); </code></pre> <p>Using <code>FXCop</code> is an excellent suggestion, but if that's my only answer, my question would have to become a plea to the C# people, or use C++. Twenty nested using statements anyone?</p>
<p>Unfortunately there isn't any way to do this directly in the code. If this is an issue in house, there are various code analysis solutions that could catch these sort of problems. Have you looked into FxCop? I think that this will catch these situations and in all cases where IDisposable objects might be left hanging. If it is a component that people are using outside of your organization and you can't require FxCop, then documentation is really your only recourse :).</p> <p>Edit: In the case of finalizers, this doesn't really guarantee when the finalization will happen. So this may be a solution for you but it depends on the situation.</p>
<p>This is no different from a programmer forgetting to use <em>delete</em> in C++, except that at least here the garbage collector will still eventually catch up with it.</p> <p>And you never need to use IDisposable if the only resource you're worried about is memory. The framework will handle that on it's own. IDisposable is only for unmanaged resources like database connections, filestreams, sockets, and the like.</p>
6,988
<p>At work we are being asked to create XML files to pass data to another offline application that will then create a second XML file to pass back in order to update some of our data. During the process we have been discussing with the team of the other application about the structure of the XML file. </p> <p>The sample I came up with is essentially something like:</p> <pre><code>&lt;INVENTORY&gt; &lt;ITEM serialNumber="something" location="something" barcode="something"&gt; &lt;TYPE modelNumber="something" vendor="something"/&gt; &lt;/ITEM&gt; &lt;/INVENTORY&gt; </code></pre> <p>The other team said that this was not industry standard and that attributes should only be used for meta data. They suggested:</p> <pre><code>&lt;INVENTORY&gt; &lt;ITEM&gt; &lt;SERIALNUMBER&gt;something&lt;/SERIALNUMBER&gt; &lt;LOCATION&gt;something&lt;/LOCATION&gt; &lt;BARCODE&gt;something&lt;/BARCODE&gt; &lt;TYPE&gt; &lt;MODELNUMBER&gt;something&lt;/MODELNUMBER&gt; &lt;VENDOR&gt;something&lt;/VENDOR&gt; &lt;/TYPE&gt; &lt;/ITEM&gt; &lt;/INVENTORY&gt; </code></pre> <p>The reason I suggested the first is that the size of the file created is much smaller. There will be roughly 80000 items that will be in the file during transfer. Their suggestion in reality turns out to be three times larger than the one I suggested. I searched for the mysterious "Industry Standard" that was mentioned, but the closest I could find was that XML attributes should only be used for meta data, but said the debate was about what was actually meta data.</p> <p>After the long winded explanation (sorry) how do you determine what is meta data, and when designing the structure of an XML document how should you decide when to use an attribute or an element?</p>
<p>I use this rule of thumb:</p> <ol> <li>An Attribute is something that is self-contained, i.e., a color, an ID, a name.</li> <li>An Element is something that does or could have attributes of its own or contain other elements.</li> </ol> <p>So yours is close. I would have done something like:</p> <p><strong>EDIT</strong>: Updated the original example based on feedback below.</p> <pre><code> &lt;ITEM serialNumber="something"&gt; &lt;BARCODE encoding="Code39"&gt;something&lt;/BARCODE&gt; &lt;LOCATION&gt;XYX&lt;/LOCATION&gt; &lt;TYPE modelNumber="something"&gt; &lt;VENDOR&gt;YYZ&lt;/VENDOR&gt; &lt;/TYPE&gt; &lt;/ITEM&gt; </code></pre>
<p>I agree with feenster. Stay away from attributes if you can. Elements are evolution friendly and more interoperable between web service toolkits. You'd never find these toolkits serializing your request/response messages using attributes. This also makes sense since our messages are data (not metadata) for a web service toolkit.</p>
5,383
<p>Using DTS I'm dynamically creating an access database. After the file is created (which works at this point) I'm having the DTS package post it via HTTP to another site. (This HTTP is just how it has to be done -- part of the spec.)</p> <p>But when the package posts the file, the posted version comes out as a 0 byte file. The code to post the file is tested and well implemented code. I'm sure it works. A colleague told me that he believes this "0-byte" error occurs because the Access connection hasn't closed the access file. He said that the DTS package must complete for the access file to be closed.</p> <p><strong>The Question is:</strong> How do I get Access to close the Access file before the step to post the file executes?</p> <p>Just in case it is needed, the steps are:</p> <ul> <li>Create the Access file, set a pre-defined access connection object to this new file</li> <li>Create the Table in Access</li> <li>Use a Transform Data task to Populate the Access Database (from a SQL Server)</li> <li>Post the file via HTTP (predefined/Pretested Libaary is being used)</li> </ul> <p>Thank you in advance for your help!</p>
<p>The answer, I just found out, is that just before I post the file (or after I'm done writing to the file) have the workflow close the connection</p> <p>I can accomplish this by checking the "Close Connection on completion" checkbox on the options tab of the Workflow Properties dialog. </p> <p>Thank you all!</p>
<p>I believe your colleague is correct, the posting via HTTP most likely will need to live outside of the DTS, or you might need to look into a VBS way of closing the connection, but I'm not sure if that is possible.</p>
28,098
<p>I have a container filled with pairs. I want to iterate in it using the STL generic algorithms (in my case it would be inner_product, but consider it as a generic problem). The algorithm I am using expects iterators first and last. Can I provide special iterators first and last that will iterate not on the pairs but on the first element of each pair? </p> <p>I know i can do it manually, providing a hand-made function object that will be a wrapper around the standard container iterator, deferencing it to the first member of the pair intend of the pair itself,but I think there is also a clever one-liner to do it for me. What would it be?</p>
<p>I've looked around and found <code>boost::transform_iterator</code>. I've come up with this code. Surprising how well it works:</p> <pre><code>#include &lt;map&gt; #include &lt;algorithm&gt; #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;iterator&gt; #include &lt;boost/iterator/transform_iterator.hpp&gt; #include &lt;boost/bind.hpp&gt; #include &lt;boost/function.hpp&gt; int main() { typedef std::map&lt;std::string, int&gt;::value_type value_type; std::map&lt;std::string, int&gt; a; a["one"] = 1; a["two"] = 2; // returns the second element boost::function&lt;int(value_type&amp;)&gt; f = boost::bind(&amp;value_type::second, _1); std::copy(boost::make_transform_iterator(a.begin(), f), boost::make_transform_iterator(a.end(), f), std::ostream_iterator&lt;int&gt;(std::cout, " ")); } </code></pre> <p>It's printing <code>"1 2 "</code> to the standard output.</p>
<p>You can subclass e.g. std::vector::const_iterator yourself, reimplementing operator* and operator-> to return the first of the pair. You'd also need to create your own begin() and end() functions to return your custom iterator.</p> <p>You can also create to binary function classes and pass those to inner_product.</p>
40,307
<p>I'm currently thinking about a repository pattern for my data objects, where multiple <code>IQueryable&lt;&gt;</code> instances can be registered as data sources, but it seems its not so easy to get it running.</p> <p>Running a simple LINQ query with LINQ to entities and LINQ To Objects doesn't work. Do you think this is in general possible? Maybe the only solution is to write a specified provider?</p> <p>In my repository, I called <code>.Union&lt;&gt;()</code> on all my IQueryable instances and then finally used LINQ for a query on the resulting single <code>IQueryable</code>. The result was that one <code>IQueryable</code> was ignored completely.</p>
<p>Well, I use LINQ queries on lists, collections a whole bunch of stuff. I use very similar queries on SQL tables. I never had any problems. I have heard of people having some issues using LINQ queries on LINQ to objects, but I think they're generally considered as LINQ bugs rather than by design differences in the the way LINQ to objects, LINQ to XML and LINQ to SQL works. I did have some LINQ issues back in the days before I installed VS 2008 SP1, but they've since been resolved.</p> <p>So long as you take into account what the query is returning, it should work just fine.</p>
<p>I have absolutely no documentation to back this up, but I do recall some discussion in the pre-release days about optimizations that were being built into Linq to SQL which would attempt to eliminate multiple calls to the database when performing operations on Linq to SQL IQueryable&lt;> objects and Linq to Object IQueryable&lt;> objects. This, combined with the overall architecture of the IQueryable interfaces, makes me think that there should be no issue operating on different providers. It seems possible, though, that the ability to interact may be based on the specific implementation of the provider.</p> <p>I know I have operated on combinations of Linq to Object and Linq to XML collections without issue.</p>
44,524
<p>I want to start developing <a href="http://en.wikipedia.org/wiki/Adobe_Flash" rel="nofollow noreferrer">Flash</a> and <a href="http://en.wikipedia.org/wiki/Adobe_Flex" rel="nofollow noreferrer">Flex</a> applications so that I can put all of the concepts floating around in my head into action. The problem is that I have never done any programming nor dealt with code...ever. I have worked in the graphic design industry and a lot of the storyboarding features in Flash are intuitive to me. Additionally, I've gone through some tutorials on Flex through the Adobe website, and although I pick up on the concepts well and can do the assignments, I'm not fully understanding the language (it's only been a week though).</p> <p>My question is this: Should I just keep going with the Flex tutorials and work my way through <a href="http://en.wikipedia.org/wiki/MXML" rel="nofollow noreferrer">MXML</a> and <a href="http://en.wikipedia.org/wiki/ActionScript" rel="nofollow noreferrer">ActionScript</a>? or should I start by learning a different base language first? I've learned several languages in my life (Spanish, French, Italian) and with those, I didn't really understand the language until I jumped in, went to the country, and just struggled through it. Is it the same with MXML and ActionScript? Should I just struggle through it? Or do I need a base first? If I need a base, what would you suggest?</p>
<p>It depends on where you want to go.</p> <p>If you're aimed towards making "application"-like content - that is, buttons, pulldown menus, tab and accordion frames and so on, then probably you should keep on with the Flex tutorials. Flex is a framework, remember - it will spare you more of the gritty details if what you want to do is aligned with it.</p> <p>If you want to make more generally expressive content - games, unique menus, highly interactive experiences and the like, then learning Flex would probably be a sidetrack. You'd be better off focusing on ActionScript itself.</p> <p>Since you're starting from zero, you should also consider how far you plan on going. If you hope to eventually be able to handle complicated, heavily script-driven content, then you'd be better off learning ActionScript 3 and pretending AS2 doesn't exist. However, if you need to learn "enough" scripting to get the job done, but you don't plan on getting married to it, then you might prefer to do the reverse. AS2 is much more ad-hoc, and less strict. It has more whippituppitude, as they say. But for complex work AS3 is far better.</p> <p>As for learning other languages, I'd say not so much. AS2 is very similar to JavaScript, and AS3 is very similar to Java, but you'll understand much better how to make good Flash content if you learn the scripting together with the authoring tool, and you'll come away more able to grok Flash's internal structure and the attendant possibilities and limitations.</p>
<p>JavaScript is a good language to look at if you want to learn something similar to ActionScript, but if you are really interested in using Flex and Flash, you might as well just dive into it.</p> <p>As you get more experience you'll find that you will also be able to read code in other languages and learn from examples of core concepts in most popular languages. Like spoken languages, the rules are pretty consistent, the grammer and vocabulary just change.</p> <p>I have always found working through a language and researching when I have specific questions makes the process faster, plus I tend to remember the things I struggled on a little better.</p>
35,427
<p>Is there something like <a href="http://en.wikipedia.org/wiki/InstallShield" rel="noreferrer">InstallShield</a> that I can use for free?</p>
<p><strong><a href="http://wix.sourceforge.net/" rel="noreferrer">WiX</a></strong></p> <ul> <li><strong>Very powerful and flexible</strong>.</li> <li>Can produce MSI packages (Microsoft deployment format of choice)</li> <li><strong>Almost no documentation</strong></li> <li><strong>Very steep learning curve.</strong></li> <li>XML-based.</li> <li>Recommended for very complex installators.</li> </ul> <p><strong><a href="http://www.innosetup.com/isinfo.php" rel="noreferrer">Inno Setup</a></strong></p> <ul> <li>Cannot produce MSI packages.</li> <li><strong>Its scripting part looks like INI files structure.</strong></li> <li>Uses Pascal Script based language for extra flexibility.</li> </ul> <p><strong><a href="http://nsis.sourceforge.net/Main_Page" rel="noreferrer">NSIS</a></strong></p> <ul> <li>Cannot produce MSI packages.</li> <li>Fully scripted, very powerful but at cost of high learning curve.</li> <li><strong>Recommened if WiX is too much and Inno Setup not enough.</strong></li> </ul> <p><strong><a href="http://www.advancedinstaller.com" rel="noreferrer">AdvancedInstaller</a></strong></p> <ul> <li>Basic version is free.</li> <li>Can produce MSI packages.</li> <li><strong>Very good user-interface, almost no learning curve to get things done.</strong></li> <li>XML-based (but schema is not very user-friendly, doesn't really matter as you would use GUI editor anyway)</li> <li>The best option if you have only basic installer requirements and don't have time to learn something new.</li> </ul> <p><strong><a href="http://izpack.org/" rel="noreferrer">IzPack</a></strong></p> <ul> <li><strong>Cross-platform</strong></li> <li>Maven integration</li> <li>Customizable actions</li> <li>Well documented</li> <li>Opensource</li> </ul>
<p>There's the open source <a href="http://nsis.sourceforge.net/Main_Page" rel="nofollow noreferrer">Nullsoft Installer</a> which began with WinAmp, if I'm not mistaken.</p> <p>For .NET development you may want to take a look at <a href="http://wix.sourceforge.net/" rel="nofollow noreferrer">WiX</a>, which Microsoft also open sourced. IT's good for those with continuous integration setups.</p>
16,647
<p>I'm considering dumping boost as a dependency... atm the only thing that I really need is <code>shared_ptr&lt;&gt;</code>, and I can get that from <code>std::tr1</code>, available in gcc suite 4.*</p>
<p>It's available on Fedora, installable via "yum" if you didn't pick "Development System" as your default install set. "yum search gcc" to get the package to install.</p>
<p>No, on my debian systems I have to install it. But any half-decent system admin should be able to figure out how to install it.</p> <p>Edit: to be specific it is not always installed by default, but it should be available for most every distro.</p>
8,811
<p>Has there been any attempt and creating a formalized method for organizing CSS code? Before I go and make up my own strategy for keeping things readable, I'm wondering what else is out there. Google hasn't been very helpful, as I'm not entirely sure what terms to search for.</p> <p>I'm thinking more along the lines of indenting/spacing, when to use new lines, naming conventions, etc.</p> <p>Any ideas?</p>
<p>Natalie Down of ClearLeft fame produced a really great slide show covering this topic and more <a href="http://natbat.net/2008/Sep/28/css-systems/" rel="noreferrer">http://natbat.net/2008/Sep/28/css-systems/</a></p> <p>Download the PDF as it includes a lot more information than the slide show. I'd recommend this to CSS devs of all skill levels.</p>
<p>Well I don't personally know of any convention per se, but I know there are a lot of recommendations out there that are really good idea to follow, but basically depends in how you want to implement your CSS for you to choose the one that fits you the most.</p>
39,919
<p>When I set a component to visible=false the component hides, but how do I get it to take no space (get the container it belongs to to resize??)</p> <p></p> <pre><code>&lt;mx:HBox width="100%" height="100%"&gt; ... &lt;/mx:HBox&gt; &lt;mx:HBox width="100%" id="boxAddComment" visible="false" &gt; &lt;mx:TextArea id="txtComment"/&gt; &lt;mx:Button label="Spara" click="addComment();"/&gt; &lt;/mx:HBox&gt; </code></pre> <p></p> <p>When boxAddComment is visible=false I want the first HBox to take 100% height.</p>
<p>use the <strong>includeInLayout</strong> property. e.g.</p> <pre> <code> &lt;mx:HBox width=&quot;100%&quot; height=&quot;100%&quot;&gt; ... &lt;/mx:HBox&gt; &lt;mx:HBox width=&quot;100%&quot; id=&quot;boxAddComment&quot; visible=&quot;false&quot; includeInLayout=&quot;false&quot; &gt; &lt;mx:TextArea id=&quot;txtComment&quot;/&gt; &lt;mx:Button label=&quot;Spara&quot; click=&quot;addComment();&quot;/&gt; &lt;/mx:HBox&gt; </code> </pre>
<p>Ross Henderson's suggestion in binding includeInLayout with boxAddComment.visible works great with Flex 3.0 but I found that it's not working in Flex 3.6 (I saw a posting that it actually stops working since Flex 3.3).</p> <p>Just fyi.</p>
49,076
<p>We've been using Trac for task/defect tracking and things were going well enough, but this morning it started serving up a 500 error. Looking in the Apache error_log, I get a stack trace that culminates in:</p> <pre> PythonHandler trac.web.modpython_frontend: ExtractionError: Can't extract file(s) to egg cache The following error occurred while trying to extract file(s) to the Python egg cache: [Errno 13] Permission denied: '/.python-eggs' The Python egg cache directory is currently set to: /.python-eggs Perhaps your account does not have write access to this directory? You can change the cache directory by setting the PYTHON_EGG_CACHE environment variable to point to an accessible directory </pre> <p>So I explicitly set PYTHON_EGG_CACHE to /srv/trac/plugin-cache. I restarted Apache. Yet I get the same error (it still says "egg cache directory current set to: \n\n /.python_eggs.")</p> <p>How should I proceed? Is the simplest thing to do to reinstall Trac? If I go that route, what steps do I need to take to ensure that I don't lose existing data?</p>
<p>That should be fixed in 0.11 according to their <a href="http://trac.edgewall.org/ticket/7320" rel="noreferrer">bug tracking system</a>. </p> <p>If that's not the case you should try to pass the environment var to apache, since doing a SetEnv in the configuration file doesn't work. Adding something like </p> <pre><code>export PYTHON_EGG_CACHE=/tmp/python_eggs </code></pre> <p>to the script you use to start apache should work.</p>
<p>I had the same problem. In my case the directory wasn't there so I created and chown'ed it over to the apache user (apache on my centos 4.3 box). Then made sure it had read-write permissions on the directory. You could get by with giving rw rights to the directory if the group that owns the directory contains the apache user. A simple ps aux|grep httpd should show you what account your server is running under if you don't know it. If you have trouble finding the directory remember the -a on the ls command since it is a "hidden" directory.</p>
26,458
<p>I'm a pretty active command line user and I have shell accounts all over the place. MacBooks, Linux desktop machines, Linux servers, Cygwin on XP, you name it.</p> <p>How can I keep my shell configuration (<code>.bashrc</code>, <code>.vimrc</code> etc.) in sync across all these machines using the limited tools available across all platforms?</p> <p>I have been using <code>rsync</code> in a pretty limited manner that involves manually copying some files over when I need them, but I want a standard way for setting up the same basic shell environment across all my machines. Tell me your shell account management strategy.</p>
<p>I have folder on Dropbox with global, per OS, and per machine shell configs:</p> <pre><code>$ ls ~/Dropbox/shell/bash bashbootstrap bashrc bashrc-Darwin bashrc-Darwin-laptopname bashrc-Darwin-mininame bashrc-Linux bashrc-Linux-machineone bashrc-Linux-machinetwo </code></pre> <p><code>bashrc</code> is loaded on every machine, <code>bashrc-Linux</code>, <code>bashrc-Darwin</code> are loaded on their respective OSes, and several configs are specific to individual machines. (By the way, Darwin is the name of OS X's BSD-like kernel.)</p> <p>What ties it all together is the <code>bashbootstrap</code> file. It loads each applicable config file in order of increasing specificity, this allows per OS and per machine overrides to have higher precedence. Additionally, we silently skip missing config files; you need not create empty config files for each of your machines to keep the script happy.</p> <p>On a new machine, after installing Dropbox on <code>~/Dropbox</code>, I move away the default <code>.bashrc</code> and just symlink the bootstrap file in its place instead:</p> <pre><code>$ mv ~/.bashrc ~/.bashrc.bak $ ln -s ~/Dropbox/shell/bash/bashbootstrap ~/.bashrc </code></pre> <p>Oh, and here are the contents of the <code>bashbootstrap</code> file:</p> <pre><code>if [ -z "$PS1" ]; then return fi dropboxshelldir=~/Dropbox/shell dropboxdir=$dropboxshelldir/bash masterbashrc=$dropboxdir/bashrc osbashrc=$masterbashrc-`uname` localbashrc=$osbashrc-`hostname | cut -d. -f1` echo -n "Applicable shell configs: " for bashfile in "$masterbashrc" "$osbashrc" "$localbashrc"; do if [ -r $bashfile ]; then . $bashfile echo -n "`basename $bashfile` " fi done echo # Set convenience aliases myed=${VISUAL:-${EDITOR:-vim}} alias editbashrc="$myed $masterbashrc" alias editosbashrc="$myed $osbashrc" alias editlocalbashrc="$myed $localbashrc" </code></pre> <p>One final note, this script also provides three convenience aliases for editing your Bash config files without having to remember where they are stored.</p> <ul> <li><strong><code>editbashrc</code>:</strong> Edit the global config file.</li> <li><strong><code>editosbashrc</code>:</strong> Edit the OS-specific config file.</li> <li><strong><code>editlocalbashrc</code>:</strong> Edit the machine-specific config file.</li> </ul> <p>I only tested this on Bash, but it could work on other Bash like shells. But, as they say, your mileage may vary.</p> <p>I made a blog post about this <a href="http://paksoy.net/post/159917345/how-dropbox-saved-my-command-line" rel="noreferrer">here</a>.</p>
<p>If you have access to source control, I'd just check them in. This way you get to sync them across multiple machines and you can compare/roll-back if need be. If you don't have CVS/SVN at work there are free options available.</p>
26,853
<p>I need a function to return a suffix for days when displaying text like the "<code>th</code>" in "<code>Wednesday June 5th, 2008</code>".</p> <p>It only need work for the numbers 1 through 31 (no error checking required) and English.</p>
<p>Here is an alternative which should work for larger numbers too:</p> <pre><code>static const char *daySuffixLookup[] = { "th","st","nd","rd","th", "th","th","th","th","th" }; const char *daySuffix(int n) { if(n % 100 &gt;= 11 &amp;&amp; n % 100 &lt;= 13) return "th"; return daySuffixLookup[n % 10]; } </code></pre>
<p>See my question here: <a href="https://stackoverflow.com/questions/135946/i18n-able-way-to-get-number-ordinal-in-cmfc-on-windows-1-1st-2-2nd-etc">How to convert Cardinal numbers into Ordinal ones</a> (it's not the C# one).</p> <p>Summary: looks like there's no way yet, with your limited requirements you can just use a simple function like the one posted.</p>
20,010
<p>Slightly related to my <a href="https://stackoverflow.com/questions/267750/java-instance-variable-accessibility">other question</a>: What is the difference between the following:</p> <pre><code>private class Joe protected class Joe public class Joe class Joe </code></pre> <p>Once again, the difference between the last 2 is what I'm most interested in.</p>
<p>A public class is accessible to a class in any package.</p> <p>A class with default access (<code>class Joe</code>) is only visible to other classes in the same package. </p> <p>The private and protected modifiers can only be applied to inner classes. </p> <p>A private class is only visible to its enclosing class, and other inner classes in the same enclosing class.</p> <p>A protected class is visible to other classes in the same package, and to classes that extend the enclosing class.</p>
<ul> <li>private: visible for outer classes only</li> <li>protected: visible for outer classes only</li> <li>public: visible for all other classes</li> <li>class: package-private, so visible for classes within the same package</li> </ul> <p>See <a href="http://java.sun.com/docs/books/jls/third_edition/html/names.html#104285" rel="nofollow noreferrer">JLS</a> for more info.</p>
33,591
<p>I want to skip to the first line that contains "include".</p> <pre><code>&lt;&gt; until /include/; </code></pre> <p>Why does this not work?</p>
<p>The match operator defaults to using <code>$_</code> but the <code>&lt;&gt;</code> operator doesn't store into <code>$_</code> by default unless it is used in a while loop so nothing is being stored in <code>$_</code>.</p> <p>From <code>perldoc perlop</code>:</p> <pre> I/O Operators ... Ordinarily you must assign the returned value to a variable, but there is one situation where an automatic assignment happens. If and only if the input symbol is the only thing inside the conditional of a "while" statement (even if disguised as a "for(;;)" loop), the value is auto‐ matically assigned to the global variable $_, destroying whatever was there previously. (This may seem like an odd thing to you, but you’ll use the construct in almost every Perl script you write.) The $_ vari‐ able is not implicitly localized. You’ll have to put a "local $_;" before the loop if you want that to happen. The following lines are equivalent: while (defined($_ = )) { print; } while ($_ = ) { print; } while () { print; } for (;;) { print; } print while defined($_ = ); print while ($_ = ); print while ; This also behaves similarly, but avoids $_ : while (my $line = ) { print $line } </pre>
<p><code>&lt;&gt;</code> is only magic in a <code>while(&lt;&gt;)</code> construct. Otherwise it does not assign to <code>$_</code>, so the <code>/include/</code> regular expression has nothing to match against. If you ran this with <code>-w</code> Perl would tell you:</p> <pre><code>Use of uninitialized value in pattern match (m//) at .... </code></pre> <p>You can fix this with:</p> <pre><code>$_ = &lt;&gt; until /include/; </code></pre> <p>To avoid the warning:</p> <pre><code>while(&lt;&gt;) { last if /include/; } </code></pre>
47,010
<p>In handling a form post I have something like</p> <pre><code> public ActionResult Insert() { Order order = new Order(); BindingHelperExtensions.UpdateFrom(order, this.Request.Form); this.orderService.Save(order); return this.RedirectToAction("Details", new { id = order.ID }); } </code></pre> <p>I am not using explicit parameters in the method as I anticipate having to adapt to variable number of fields etc. and a method with 20+ parameters is not appealing.</p> <p>I suppose my only option here is mock up the whole HttpRequest, equivalent to what Rob Conery has done. Is this a best practice? Hard to tell with a framework which is so new.</p> <p>I've also seen solutions involving using an ActionFilter so that you can transform the above method signature to something like</p> <pre><code>[SomeFilter] public Insert(Contact contact) </code></pre>
<p>I'm now using <a href="https://stackoverflow.com/questions/34709/how-do-you-use-the-new-modelbinder-classes-in-aspnet-mvc-preview-5#34725">ModelBinder</a> so that my action method can look (basically) like:</p> <pre><code> public ActionResult Insert(Contact contact) { if (this.ViewData.ModelState.IsValid) { this.contactService.SaveContact(contact); return this.RedirectToAction("Details", new { id = contact.ID }); } else { return this.RedirectToAction("Create"); } } </code></pre>
<p>Wrap it in an interface and mock it.</p>
4,835
<p>I have a class Animal and an interface it inherits from IAnimal.</p> <pre><code>@MappedSuperclass public class Animal implements Serializable, IAnimal{...}. @Entity public class Jaguar extends Animal{...} </code></pre> <p>My first question is, do I need to annotate the interface?</p> <p>I asked this because I am getting this error when I run my tests:</p> <blockquote> <p>Error compiling the query [SELECT s FROM animal s WHERE s.atype = :atype]. Unknown abstract schema type [animal]</p> </blockquote> <p>If I remember correctly, before I added this interface it was working.</p>
<p>Here are a bunch of good textbooks:</p> <p>Modern Compiler Implementation in Java (Tiger book) A.W. Appel Cambridge University Press, 1998 ISBN 0-52158-388-8 A textbook tutorial on compiler implementation, including techniques for many language features</p> <p>Compilers: Principles, Techniques and Tools (Dragon book) Aho, Lam, Sethi and Ullman Addison-Wesley, 2006 ISBN 0321486811 The classic compilers textbook, although its front-end emphasis reflects its age.</p> <p>Advanced Compiler Design and Implementation (Whale book) Steven Muchnick Morgan Kaufman Publishers, 1997 ISBN 1-55860-320-4 Essentially a recipe book of optimizations; very complete and suited for industrial practitioners and researchers.</p> <p>Engineering a Compiler (Ark book) Keith D. Cooper, Linda Torczon Morgan Kaufman Publishers, 2003 ISBN 1-55860-698-X A modern classroom textbook, with increased emphasis on the back-end and implementation techniques.</p> <p>Optimizing Compilers for Modern Architectures Randy Allen and Ken Kennedy Morgan Kaufman Publishers, 2001 ISBN 1-55860-286-0 A modern textbook that focuses on optimizations including parallelization and memory hierarchy optimizations.</p> <p>Programming Languages Pragmatics Michael L. Scott Morgan Kaufmann Publishers, 2005 ISBN 0126339511</p>
<p>The Purple Dragon Book is the best ever.</p>
18,505
<p>I am working with both <a href="http://activemq.apache.org/ajax.html" rel="nofollow noreferrer">amq.js</a> (ActiveMQ) and <a href="http://code.google.com/apis/maps/documentation/reference.html" rel="nofollow noreferrer">Google Maps</a>. I load my scripts in this order</p> <pre><code>&lt;head&gt; &lt;meta http-equiv="content-type" content="text/html;charset=UTF-8" /&gt; &lt;title&gt;AMQ &amp; Maps Demo&lt;/title&gt; &lt;!-- Stylesheet --&gt; &lt;link rel="stylesheet" type="text/css" href="style.css"&gt;&lt;/link&gt; &lt;!-- Google APIs --&gt; &lt;script type="text/javascript" src="http://www.google.com/jsapi?key=abcdefg"&gt;&lt;/script&gt; &lt;!-- Active MQ --&gt; &lt;script type="text/javascript" src="amq/amq.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt;amq.uri='amq';&lt;/script&gt; &lt;!-- Application --&gt; &lt;script type="text/javascript" src="application.js"&gt;&lt;/script&gt; &lt;/head&gt; </code></pre> <p>However in my application.js it loads Maps fine but I get an error when trying to subscribe to a Topic with AMQ. AMQ depends on prototype which the error console in Firefox says object is not defined. I think I have a problem with using the amq object before the script is finished loading. <strong>Is there a way to make sure both scripts load before I use them in my application.js?</strong> </p> <p>Google has this nice function call <code>google.setOnLoadCallback(initialize);</code> which works great. I'm not sure amq.js has something like this.</p>
<blockquote> <p><strong>Is there a way to make sure both scripts load before I use them in my application.js?</strong></p> </blockquote> <p>JavaScript files should load sequentially <em>and block</em> so unless the scripts you are depending on are doing something unusual all you should need to do is load application.js after the other files.</p> <p><a href="http://yuiblog.com/blog/2008/07/22/non-blocking-scripts/" rel="noreferrer">Non-blocking JavaScript Downloads</a> has some information about how scripts load (and discusses some techniques to subvert the blocking).</p>
<p>You can also use the built in SharePoint javascript method to control the execution of your scripts;</p> <pre><code>_spBodyOnLoadFunctionNames.push("yourFunction"); </code></pre>
3,954
<p>Under what circumstances might you want to use multiple indirection (that is, a chain of pointers as in <code>Foo **</code>) in C++?</p>
<p>Most common usage as @aku pointed out is to allow a change to a pointer parameter to be visible after the function returns.</p> <pre><code>#include &lt;iostream&gt; using namespace std; struct Foo { int a; }; void CreateFoo(Foo** p) { *p = new Foo(); (*p)-&gt;a = 12; } int main(int argc, char* argv[]) { Foo* p = NULL; CreateFoo(&amp;p); cout &lt;&lt; p-&gt;a &lt;&lt; endl; delete p; return 0; } </code></pre> <p>This will print</p> <pre><code>12 </code></pre> <p>But there are several other useful usages as in the following example to iterate an array of strings and print them to the standard output.</p> <pre><code>#include &lt;iostream&gt; using namespace std; int main(int argc, char* argv[]) { const char* words[] = { "first", "second", NULL }; for (const char** p = words; *p != NULL; ++p) { cout &lt;&lt; *p &lt;&lt; endl; } return 0; } </code></pre>
<p>A simple example would be using <code>int** foo_mat</code> as a 2d array of integers. Or you may also use pointers to pointers - lets say that you have a pointer <code>void* foo</code> and you have 2 different objects that have a reference to it with the following members: <code>void** foo_pointer1</code> and <code>void** foo_pointer2</code>, by having a pointer to a pointer you can actually check whether <code>*foo_pointer1 == NULL</code> which indicates that foo is NULL. You wouldn't be able to check whether foo is NULL if foo_pointer1 was a regular pointer. I hope that my explanation wasn't too messy :)</p>
9,655
<p>I want to send email with Exchange by using telnet to port 25. Until two week ago I was able to, but now a "security fix" from Microsoft has removed this possibility.</p> <p>When I try, I get this message:</p> <p>421 4.3.2 Service not available, closing transmission channel</p> <p>What can I do?</p>
<p>I found the answer at website:</p> <p><a href="http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=2900802&amp;SiteID=17" rel="nofollow noreferrer">http://forums.microsoft.com/TechNet/ShowPost.aspx?PostID=2900802&amp;SiteID=17</a></p> <p>Thanks for your help!</p> <p>Basically, this functionality was removed by default and it <em>could</em> be restored by means of an ad hoc configuration - but with no guarrantee that further "updates" break the system <em>again</em>. Thanks, Microsoft.</p>
<p>SMTP is the protocol that is used to receive email from the rest of the world so I doubt that Microsoft has dropped that. There must be some other misconfiguration on your server.</p> <p>Try double-checking your relay-settings and the event-log on your exchange-server.</p>
10,617
<p>How can I read the colors of an image with python using google app engine?</p> <p><strong>Example:</strong> I like to build a function to determine the most striking colors of an image to set a harmonic background color for it.</p>
<p>The <a href="http://code.google.com/appengine/docs/images/overview.html" rel="nofollow noreferrer">Images API</a> does not (currently) contain pixel-level functions. To quote the overview document:</p> <blockquote> <p>Note: In order to use the Images API in your local environment you must first download and install PIL, the Python Imaging Library. PIL is not available on App Engine; it is only used as a stub for the Images API in your local environment. Only the transforms provided in the images API are available on App Engine.</p> </blockquote> <p>The community has been asking for full <a href="http://www.pythonware.com/products/pil/index.htm" rel="nofollow noreferrer">PIL</a> support for some time, but it looks like we'll have to wait.</p>
<p>If you are willing to put Flash or a Java applet on the page, you might be able to do it on the client. I'm not sure if anything like canvas or SVG supports pixel-level manipulation, but if they do, you might be able to get it to work in some browsers with JavaScript.</p> <p>The Flash or Java Applet, can be invisible and optional -- you can use JavaScript to detect if the user has the plugin and only support this feature when they do.</p>
23,143
<p>I'm trying to profile SQL reporting services, used from ASP.NET application. In SQL profiler all the SQL run by ASP.NET shows up. It looks like the reporting SQL (from the RDL) doesn't show. Is there some setting or filter I'm missing?</p>
<p>Application name column = Reporting Services (or similar) usually.</p> <p>You may need to trace SQL batch complete <em>and</em> RPC call complete I've been bitten with this before...</p>
<p>When you get that big ball of mess, you can search it. I would search for an sp or sql statement that you know could only be used by SSRS. (If this doesn't exist, then force something in there just for testing purposes). Look at all the columns. There may be a column that jumps out at you as unique to reporting services that you could use as a filter.</p>
14,467
<p>When the page is done loading I call a function which puts the hover event on $('a.tooltip'). When I want to <em>unbind</em> this event I do the following: </p> <pre><code> $('a.tooltip').unbind('mouseover mouseout'); </code></pre> <p>That works! However when I want rebind the hover event and I call the function that was first loaded at document ready again, it doesn't rebind the hover helper. How can I rebind it?</p> <p>Thank you,</p> <p>Ice</p>
<p>Are you sure the unbinding is working correctly? In my experience, .hover() does rebind properly, but I have had to use this unbind syntax:</p> <pre><code>$(this).unbind('mouseenter').unbind('mouseleave'); </code></pre> <p>When I tried putting both events into one unbind(), it only unbound one of them.</p> <p>I wonder if that's happening for you? (Or if the choice of <code>mouseover</code> vs <code>mouseenter</code>, etc, matters?)</p> <h3>Update</h3> <p>According to <a href="http://www.quirksmode.org/js/events_mouse.html" rel="nofollow noreferrer">quirksmode.org</a>, <code>mouseenter</code> and <code>mouseleave</code> are IE-specific events, but as Jimmy pointed out in the comments, jQuery implements them for other browsers as well.</p>
<p>I found that when I use the bind method, things can be a bit fussy. You might want to try using the hover(over, out) function as such:</p> <pre><code> $(this).hover( function() { if (okayToHover) { dowhatever; } }, function() { if (okayToUnhover) { undowhatever; } }); </code></pre> <p>I know it seems a bit roundabout, but I find that the hover function gives me a bit more control over what's going on, and it seems to work a bit better for whatever reason. That's just in my experience though...</p>
40,996
<p>I'm writing an application that uses renaming rules to rename a list of files based on information given by the user. The files may be inconsistently named to begin with, or the filenames may be consistent. The user selects a list of files, and inputs information about the files (for MP3s, they would be Artist, Title, Album, etc). Using a rename rule (example below), the program uses the user-inputted information to rename the files accordingly.</p> <p>However, if all or some the files are named consistently, I would like to allow the program to 'guess' the file information. That is the problem I'm having. What is the best way to do this?</p> <p>Sample filenames:</p> <pre><code>Kraftwerk-Kraftwerk-01-RuckZuck.mp3 Kraftwerk-Autobahn-01-Autobahn.mp3 Kraftwerk-Computer World-03-Numbers.mp3 </code></pre> <p>Rename Rule:</p> <pre><code>%Artist%-%Album%-%Track%-%Title%.mp3 </code></pre> <p>The program should properly deduce the Artist, Track number, Title, and Album name.</p> <p>Again, what's the best way to do this? I was thinking regular expressions, but I'm a bit confused.</p>
<p>Easiest would be to replace each <code>%Label%</code> with <code>(?&lt;Label&gt;.*?)</code>, and escape any other characters.</p> <pre><code>%Artist%-%Album%-%Track%-%Title%.mp3 </code></pre> <p>becomes</p> <pre><code>(?&lt;Artist&gt;.*?)-(?&lt;Album&gt;.*?)-(?&lt;Track&gt;.*?)-(?&lt;Title&gt;.*?)\.mp3 </code></pre> <p>You would then get each component into named capture groups.</p> <pre><code>Dictinary&lt;string,string&gt; match_filename(string rule, string filename) { Regex tag_re = new Regex(@'%(\w+)%'); string pattern = tag_re.Replace(Regex.escape(rule), @'(?&lt;$1&gt;.*?)'); Regex filename_re = new Regex(pattern); Match match = filename_re.Match(filename); Dictionary&lt;string,string&gt; tokens = new Dictionary&lt;string,string&gt;(); for (int counter = 1; counter &lt; match.Groups.Count; counter++) { string group_name = filename_re.GroupNameFromNumber(counter); tokens.Add(group_name, m.Groups[counter].Value); } return tokens; } </code></pre> <p>But if the user leaves out the delimiters, or if the delimiters could be contained within the fields, you could get some strange results. The pattern would for <code>%Artist%%Album%</code> would become <code>(?&lt;Artist&gt;.*?)(?&lt;Album&gt;.*?)</code> which is equivalent to <code>.*?.*?</code>. The pattern wouldn't know where to split.</p> <p>This could be solved if you know the format of certain fields, such as the track-number. If you translate <code>%Track%</code> to <code>(?&lt;Track&gt;\d+)</code> instead, the pattern would know that any digits in the filename must be the <code>Track</code>.</p>
<p>The filenames in your example seem pretty consistent to me. You can simply do string.Split() and add each element of the resulting array to its according tag information.</p> <p>Guessing at which position is which tag information would involve TONS of heuristics.</p> <p>Btw. folders that contain song files usually have some pattern in their name as well, f.e.</p> <p>1998 - Seven</p> <p>1999 - Periscope</p> <p>2000 - CO2</p> <p>The format here is %Year% - %AlbumName%, that might help you to identify which element in the filename is the album.</p>
31,366
<p>Are there any performance benefits of using SQL Server 2008 over SQL Server 2005?</p>
<p>Moving a single database from SQL Server 2005-2008 will not notice a difference really. However, there are new tools and options available in SQL Server 2008 that you MIGHT be able to leverage to provider better performance later on in your application.</p> <p>One item that comes to mind is filtered indexes. Allowing to create an index on a subset of information.</p>
<p>There may be new features in the engine which execute queries in different ways. This includes changes to the optimiser.</p> <p>Therefore, the only way you can POSSIBLY tell, is to gather detailed performance data from your application on MSSQL2005, and then repeat the experiment on the same (production-quality) hardware with SQL2008.</p> <p>You will need to make sure your application works correctly- such a migration can't be done lightly as any change could introduce bugs.</p> <p>Also, the new version of the database could have performance <em>regressions</em> - which you need to be very careful about.</p> <p>So in summary:</p> <ul> <li>Benchmark YOUR application on SQL2005</li> <li>Benchmark it on SQL2008</li> <li>Use the same production-grade test hardware in your lab both times</li> <li>Don't run VMs (unless that's what you do in production)</li> <li>Don't change other parameters</li> </ul> <p>This may not be easy if your application is big / complicated.</p>
26,063
<p>In my WPF app, I call a WCF service to retrieve my business object. I take that business object and bind it to a grid. I want to now apply the INotifyPropertyChanged attribute, but am unsure if it would work from WCF. My ultimate goal is to be able to edit items in a grid, click update and push those back through a WCF service. </p>
<p>I think there is an option for the generated classes to implement that automatically.</p> <blockquote> <p><strong><code>svcutil /enableDataBinding</code></strong><br> - Implement the System.ComponentModel.INotifyPropertyChanged interface on all Data Contract types to enable data binding. (Short Form: /edb)</p> </blockquote>
<p>If you are talking about a partial trusted WPF app you can in .NET 3.5... You cannot in .NET 3.0..</p> <p>If it is full trust you are talking about, I see no problems :)</p>
41,605
<p>I'm starting to learn Python and I've come across generator functions, those that have a yield statement in them. I want to know what types of problems that these functions are really good at solving.</p>
<p>Generators give you lazy evaluation. You use them by iterating over them, either explicitly with 'for' or implicitly by passing it to any function or construct that iterates. You can think of generators as returning multiple items, as if they return a list, but instead of returning them all at once they return them one-by-one, and the generator function is paused until the next item is requested.</p> <p>Generators are good for calculating large sets of results (in particular calculations involving loops themselves) where you don't know if you are going to need all results, or where you don't want to allocate the memory for all results at the same time. Or for situations where the generator uses <em>another</em> generator, or consumes some other resource, and it's more convenient if that happened as late as possible.</p> <p>Another use for generators (that is really the same) is to replace callbacks with iteration. In some situations you want a function to do a lot of work and occasionally report back to the caller. Traditionally you'd use a callback function for this. You pass this callback to the work-function and it would periodically call this callback. The generator approach is that the work-function (now a generator) knows nothing about the callback, and merely yields whenever it wants to report something. The caller, instead of writing a separate callback and passing that to the work-function, does all the reporting work in a little 'for' loop around the generator.</p> <p>For example, say you wrote a 'filesystem search' program. You could perform the search in its entirety, collect the results and then display them one at a time. All of the results would have to be collected before you showed the first, and all of the results would be in memory at the same time. Or you could display the results while you find them, which would be more memory efficient and much friendlier towards the user. The latter could be done by passing the result-printing function to the filesystem-search function, or it could be done by just making the search function a generator and iterating over the result.</p> <p>If you want to see an example of the latter two approaches, see os.path.walk() (the old filesystem-walking function with callback) and os.walk() (the new filesystem-walking generator.) Of course, if you really wanted to collect all results in a list, the generator approach is trivial to convert to the big-list approach:</p> <pre><code>big_list = list(the_generator) </code></pre>
<p>Also good for printing the prime numbers up to n:</p> <pre><code>def genprime(n=10): for num in range(3, n+1): for factor in range(2, num): if num%factor == 0: break else: yield(num) for prime_num in genprime(100): print(prime_num) </code></pre>
12,814
<p>I am trying to port some data over from my production database to my sandbox using a query like this:</p> <pre><code>INSERT `dbsandbox`.`SomeTable`(Field1, Field2, Field3) SELECT t.Field1, t.Field2, t.Field3 FROM `dbprod`.`SomeTable` t; </code></pre> <p>When I attempt this cross-database join I get the following error:</p> <p>ERROR 1142 (42000): SELECT command denied to user 'myusername'@'server.domain.tdl' for table 'SomeTable'</p> <p>The user in question has permission to the tables in question for both databases. I have tried this in both the unix mysql client and the windows MySQL Query Browser application with the same result.</p> <p>What am I missing?</p>
<p>It turns out it was a permissions problem. The source database required a password for the username I was using in order to access any tables. The target only required the username be on the localhost. </p> <p>Even though I launch the MySQL client using a password every time within the context of a cross-database query another connection is attempted. This connection does not remember that I originally authenticated against the client with a password so connecting from the sandbox to the production database failed. Apparently explicitly stating the database name for a table sometimes implies the need for another connection, as well.</p> <p>The answer was to initiate the query from with the production database, refer to the local tables without the database qualifier, then insert across to the sandbox database tables. This time it worked:</p> <p>USE dbprod</p> <p>INSERT <code>dbsandbox</code>.<code>SomeTable</code>(Field1, Field2, Field3) SELECT t.Field1, t.Field2, t.Field3 FROM <code>SomeTable</code> t;</p>
<p>It sounds like a permissions problem. Often user permissions are set up on a database in a database fashion, so the user for the destination doesn't have access to the source.</p> <p>First make sure that you can do the select from the source database.</p> <pre><code>SELECT t.Field1, t.Field2, t.Field3 FROM `dbprod`.`SomeTable` t; </code></pre> <p>Does that work? If not, then you need to grant the user select permissions on the source db.</p> <p>Both databases are on/in the same server right?</p>
43,901
<p>I would like to be able to display <code>Notebook</code> and a <code>TxtCtrl</code> wx widgets in a single frame. Below is an example adapted from the wxpython wiki; is it possible to change their layout (maybe with something like <code>wx.SplitterWindow</code>) to display the text box below the <code>Notebook</code> in the same frame?</p> <pre><code>import wx import wx.lib.sheet as sheet class MySheet(sheet.CSheet): def __init__(self, parent): sheet.CSheet.__init__(self, parent) self.SetLabelBackgroundColour('#CCFF66') self.SetNumberRows(50) self.SetNumberCols(50) class Notebook(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(600, 600)) menubar = wx.MenuBar() file = wx.Menu() file.Append(101, 'Quit', '' ) menubar.Append(file, "&amp;File") self.SetMenuBar(menubar) wx.EVT_MENU(self, 101, self.OnQuit) nb = wx.Notebook(self, -1, style=wx.NB_BOTTOM) self.sheet1 = MySheet(nb) self.sheet2 = MySheet(nb) self.sheet3 = MySheet(nb) nb.AddPage(self.sheet1, "Sheet1") nb.AddPage(self.sheet2, "Sheet2") nb.AddPage(self.sheet3, "Sheet3") self.sheet1.SetFocus() self.StatusBar() def StatusBar(self): self.statusbar = self.CreateStatusBar() def OnQuit(self, event): self.Close() class MyFrame(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, wx.DefaultPosition, wx.Size(450, 400)) self.text = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE) self.Center() class MyApp(wx.App): def OnInit(self): frame = Notebook(None, -1, 'notebook.py') frame.Show(True) frame.Center() frame2 = MyFrame(None, -1, '') frame2.Show(True) self.SetTopWindow(frame2) return True app = MyApp(0) app.MainLoop() </code></pre>
<p>Making two widgets appear on the same frame is easy, actually. You should use sizers to accomplish this.</p> <p>In your example, you can change your <code>Notebook</code> class implementation to something like this:</p> <pre><code>class Notebook(wx.Frame): def __init__(self, parent, id, title): wx.Frame.__init__(self, parent, id, title, size=(600, 600)) menubar = wx.MenuBar() file = wx.Menu() file.Append(101, 'Quit', '' ) menubar.Append(file, "&amp;File") self.SetMenuBar(menubar) wx.EVT_MENU(self, 101, self.OnQuit) nb = wx.Notebook(self, -1, style=wx.NB_BOTTOM) self.sheet1 = MySheet(nb) self.sheet2 = MySheet(nb) self.sheet3 = MySheet(nb) nb.AddPage(self.sheet1, "Sheet1") nb.AddPage(self.sheet2, "Sheet2") nb.AddPage(self.sheet3, "Sheet3") self.sheet1.SetFocus() self.StatusBar() # new code begins here: # add your text ctrl: self.text = wx.TextCtrl(self, -1, style = wx.TE_MULTILINE) # create a new sizer for both controls: sizer = wx.BoxSizer(wx.VERTICAL) # add notebook first, with size factor 2: sizer.Add(nb, 2) # then text, size factor 1, maximized sizer.Add(self.text, 1, wx.EXPAND) # assign the sizer to Frame: self.SetSizerAndFit(sizer) </code></pre> <p>Only the <code>__init__</code> method is changed. Note that you can manipulate the proportions between the notebook and text control by changing the second argument of the <code>Add</code> method.</p> <p>You can learn more about sizers from the official <a href="https://docs.wxpython.org/sizers_overview.html" rel="nofollow noreferrer">Sizer overview</a> article.</p>
<p>You can use a splitter, yes.</p> <p>Also, it makes sense to create a Panel, place your widgets in it (with sizers), and add this panel to the Frame.</p>
21,915
<p>I'd like to get at least one JRE/JDK level on my Windows machine where I have the JRE/JDK source that matches the exact level of the JRE/JDK. My purpose is to be able to go into the system classes while debugging. Any suggestions about how to do this? Thanks in advance.</p>
<p>Most of the useful source will be in the src.zip file in your JDK.</p> <p>You can get source up to jdk 6u3 from <a href="https://jdk6.dev.java.net/" rel="noreferrer">jdk6.dev.java.net</a>. On Linux you can get OpenJDK source and packages from <a href="http://openjdk.java.net/" rel="noreferrer">openjdk.java.net</a>.</p>
<p>The source code is included in the JDK 1.5+ installer. Just make sure that the option is not unchecked while installing.</p>
18,188
<p>I need to create an XML schema that validates a tree structure of an XML document. I don't know exactly the occurrences or depth level of the tree.</p> <p>XML example:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;node&gt; &lt;attribute/&gt; &lt;node&gt; &lt;attribute/&gt; &lt;node/&gt; &lt;/node&gt; &lt;/node&gt; </code></pre> <p>Which is the best way to validate it? Recursion?</p>
<p>if you need a recursive type declaration, here is an example that might help:</p> <pre><code>&lt;xs:schema id="XMLSchema1" targetNamespace="http://tempuri.org/XMLSchema1.xsd" elementFormDefault="qualified" xmlns="http://tempuri.org/XMLSchema1.xsd" xmlns:mstns="http://tempuri.org/XMLSchema1.xsd" xmlns:xs="http://www.w3.org/2001/XMLSchema" &gt; &lt;xs:element name="node" type="nodeType"&gt;&lt;/xs:element&gt; &lt;xs:complexType name="nodeType"&gt; &lt;xs:sequence minOccurs="0" maxOccurs="unbounded"&gt; &lt;xs:element name="node" type="nodeType"&gt;&lt;/xs:element&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:schema&gt; </code></pre> <p>As you can see, this defines a recursive schema with only one node named "node" which can be as deep as desired.</p>
<p>The other solutions work great for making root elements recursive. However, in order to make a non-root element recursive without turning it into a valid root element in the process, a slightly different approach is needed.</p> <p>Let's say you want to define an XML message format for exchanging structured data between nodes in a distributed application. It contains the following elements:</p> <ul> <li><code>&lt;message&gt;</code> - the root element;</li> <li><code>&lt;from&gt;</code> - the message's origin;</li> <li><code>&lt;to&gt;</code> - the message's destination;</li> <li><code>&lt;type&gt;</code> - the data structure type encoded in the message;</li> <li><code>&lt;data&gt;</code> - the data contained in the message.</li> </ul> <p>In order to support complex data types, <code>&lt;data&gt;</code> is a recursive element. This makes possible to write messages as below, for sending e.g. a <a href="http://docs.ros.org/melodic/api/geometry_msgs/html/msg/TwistStamped.html" rel="nofollow noreferrer"><code>geometry_msgs/TwistStamped</code></a> message to a flying drone specifying its linear and angular (i.e. rotating) speeds:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;message xmlns=&quot;https://stackoverflow.com/message/1.0.0&quot;&gt; &lt;from&gt;controller:8080&lt;/from&gt; &lt;to&gt;drone:8080&lt;/to&gt; &lt;type&gt;geometry_msgs/TwistStamped&lt;/type&gt; &lt;data name=&quot;header&quot;&gt; &lt;data name=&quot;seq&quot;&gt;0&lt;/data&gt; &lt;data name=&quot;stamp&quot;&gt; &lt;data name=&quot;sec&quot;&gt;1&lt;/data&gt; &lt;data name=&quot;nsec&quot;&gt;0&lt;/data&gt; &lt;/data&gt; &lt;data name=&quot;frame_id&quot;&gt;base_link&lt;/data&gt; &lt;/data&gt; &lt;data name=&quot;twist&quot;&gt; &lt;data name=&quot;linear&quot;&gt; &lt;data name=&quot;x&quot;&gt;1.0&lt;/data&gt; &lt;data name=&quot;y&quot;&gt;0&lt;/data&gt; &lt;data name=&quot;z&quot;&gt;1.0&lt;/data&gt; &lt;/data&gt; &lt;data name=&quot;angular&quot;&gt; &lt;data name=&quot;x&quot;&gt;0.3&lt;/data&gt; &lt;data name=&quot;y&quot;&gt;0&lt;/data&gt; &lt;data name=&quot;z&quot;&gt;0&lt;/data&gt; &lt;/data&gt; &lt;/data&gt; &lt;/message&gt; </code></pre> <p>We can easily write an XML schema to validate this format:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;xs:schema xmlns:xs=&quot;http://www.w3.org/2001/XMLSchema&quot; targetNamespace=&quot;https://stackoverflow.com/message/1.0.0&quot; elementFormDefault=&quot;qualified&quot; xmlns=&quot;https://stackoverflow.com/message/1.0.0&quot; &gt; &lt;xs:element name=&quot;data&quot;&gt; &lt;xs:complexType mixed=&quot;true&quot;&gt; &lt;xs:sequence&gt; &lt;xs:element ref=&quot;data&quot; minOccurs=&quot;0&quot; maxOccurs=&quot;unbounded&quot;/&gt; &lt;/xs:sequence&gt; &lt;xs:attribute name=&quot;name&quot; type=&quot;xs:string&quot; use=&quot;required&quot;/&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;xs:element name=&quot;message&quot;&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name=&quot;from&quot; type=&quot;xs:string&quot;/&gt; &lt;xs:element name=&quot;to&quot; type=&quot;xs:string&quot;/&gt; &lt;xs:element name=&quot;type&quot; type=&quot;xs:string&quot;/&gt; &lt;xs:element ref=&quot;data&quot; maxOccurs=&quot;unbounded&quot;/&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:schema&gt; </code></pre> <p>The problem with the schema above is that it makes <code>&lt;data&gt;</code> a root element, which means it also validates the document below:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;data xmlns=&quot;https://stackoverflow.com/message/1.0.0&quot; name=&quot;twist&quot;&gt; &lt;data name=&quot;header&quot;&gt; &lt;data name=&quot;seq&quot;&gt;0&lt;/data&gt; &lt;data name=&quot;stamp&quot;&gt; &lt;data name=&quot;sec&quot;&gt;1&lt;/data&gt; &lt;data name=&quot;nsec&quot;&gt;0&lt;/data&gt; &lt;/data&gt; &lt;data name=&quot;frame_id&quot;&gt;base_link&lt;/data&gt; &lt;/data&gt; &lt;data name=&quot;twist&quot;&gt; &lt;data name=&quot;linear&quot;&gt; &lt;data name=&quot;x&quot;&gt;1.0&lt;/data&gt; &lt;data name=&quot;y&quot;&gt;0&lt;/data&gt; &lt;data name=&quot;z&quot;&gt;1.0&lt;/data&gt; &lt;/data&gt; &lt;data name=&quot;angular&quot;&gt; &lt;data name=&quot;x&quot;&gt;0.3&lt;/data&gt; &lt;data name=&quot;y&quot;&gt;0&lt;/data&gt; &lt;data name=&quot;z&quot;&gt;0&lt;/data&gt; &lt;/data&gt; &lt;/data&gt; &lt;/data&gt; </code></pre> <p>In order to avoid this side-effect, instead of defining the <code>&lt;data&gt;</code> element directly at the global level, we first define a <code>data</code> type, then define a <code>data</code> element of that type inside <code>message</code>:</p> <pre class="lang-xml prettyprint-override"><code>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt; &lt;xs:schema xmlns:xs=&quot;http://www.w3.org/2001/XMLSchema&quot; targetNamespace=&quot;https://stackoverflow.com/message/1.0.0&quot; elementFormDefault=&quot;qualified&quot; xmlns=&quot;https://stackoverflow.com/message/1.0.0&quot; &gt; &lt;xs:complexType name=&quot;data&quot; mixed=&quot;true&quot;&gt; &lt;xs:sequence&gt; &lt;xs:element name=&quot;data&quot; type=&quot;data&quot; minOccurs=&quot;0&quot; maxOccurs=&quot;unbounded&quot;/&gt; &lt;/xs:sequence&gt; &lt;xs:attribute name=&quot;name&quot; type=&quot;xs:string&quot; use=&quot;required&quot;/&gt; &lt;/xs:complexType&gt; &lt;xs:element name=&quot;message&quot;&gt; &lt;xs:complexType&gt; &lt;xs:sequence&gt; &lt;xs:element name=&quot;from&quot; type=&quot;xs:string&quot;/&gt; &lt;xs:element name=&quot;to&quot; type=&quot;xs:string&quot;/&gt; &lt;xs:element name=&quot;type&quot; type=&quot;xs:string&quot;/&gt; &lt;xs:element name=&quot;data&quot; type=&quot;data&quot; maxOccurs=&quot;unbounded&quot;/&gt; &lt;/xs:sequence&gt; &lt;/xs:complexType&gt; &lt;/xs:element&gt; &lt;/xs:schema&gt; </code></pre> <p>Notice that we end up having to define the <code>&lt;data&gt;</code> element twice — once inside the <code>data</code> type, and again inside <code>&lt;element&gt;</code> — but apart a little work duplication this is of no consequence.</p>
17,953
<p>Never used a cache like this before. The problem is that I want to load 500,000 + records out of a database and do some selecting/filtering wicked fast.</p> <p>I'm thinking about using a cache, and preliminarily found <a href="http://ehcache.org/" rel="noreferrer">EHCache</a> and <a href="https://java.net/projects/oscache/" rel="noreferrer">OSCache</a>, any opinions?</p>
<p>Judging by their <a href="http://www.opensymphony.com/oscache/download.action" rel="noreferrer">releases page</a>, OSCache has not been actively maintained since 2007. This is not a good thing. EhCache, on the other hand, is under constant development. For that reason alone, I would choose EhCache.</p> <p>Edit Nov 2013: OSCache, like the rest of OpenSymphony, is dead. </p>
<p>I mainly use EhCache because it used to be the default cache provider for Hibernate. There is a list of caching solutions on <a href="http://java-source.net/open-source/cache-solutions" rel="nofollow noreferrer">Java-Source.net</a>.</p> <p>I used to have a link that compared the main caching solutions. If I find it I will update this answer.</p>
12,324
<p>To follow on from my question yesterday....</p> <p><a href="https://stackoverflow.com/questions/323842/mysql-table-design-for-a-questionnaire">MySQL Table Design for a Questionnaire</a></p> <p>I sat down with my boss yesterday afternoon to run through how I was proposing to design the database. However, now I am more confused than ever.</p> <p>He has been using Access for many years, and has questioned whether I will be able to produce reports from only using one column for the answer (ENUM). He feels from his experience with Access that each possible response (i.e. Very Satisfied, Fairly Satified, Fairly Unsatisfied, Very Unsatisfied), should have it's own column and numerical value(i.e. 100, 66.6, 33.3, 0).</p> <p>This is so that the database can produce reports that show the average satisfaction nationally and for each retailer individually.</p> <p>I would really appreciate some guidence, as I really don't want to get this wrong?</p> <p>Thank you</p>
<p>In this case I wouldn't go for an enum, I'd go for a "score" column. So the columns might be:</p> <pre><code>userid, questionid, score 1,1,4 1,2,4 1,3,3 2,1,1 2,2,4 ... </code></pre> <p>1 being very unsatisfied and 4 being very satisfied.</p> <p>Then a query like:</p> <pre><code>select 25*avg(score) from Blah </code></pre> <p>will give you your overall percentage.</p> <pre><code>select 25*avg(score), questionid from Blah group by questionid </code></pre> <p>will give you a % per question.</p> <p>Access isn't really a database, so don't listen to your boss ;)</p>
<p>Just in case anyone else has this problem; I have also found a tutorial which is quite useful. <a href="http://www.roughguidetophp.com/generating-reports-using-mysqls-aggregate-functions-sum-max-min-and-more/" rel="nofollow noreferrer">http://www.roughguidetophp.com/generating-reports-using-mysqls-aggregate-functions-sum-max-min-and-more/</a></p> <p>It clarifies what JD and Genehack have said.</p>
42,137
<p>I am trying to validate user id's matching the example:</p> <pre><code>smith.jack or smith.jack.s </code></pre> <p>In other words, any number of non-whitespace characters (except dot), followed by exactly one dot, followed by any number of non-whitespace characters (except dot), optionally followed by exactly one dot followed by any number of non-whitespace characters (except dot). I have come up with several variations that work fine except for allowing consecutive dots! For example, the following Regex</p> <pre><code>^([\S][^.]*[.]{1}[\S][^.]*|[\S][^.]*[.]{1}[\S][^.]*[.]{1}[\S][^.]*)$ </code></pre> <p>matches "smith.jack" and "smith.jack.s" but also matches "smith..jack" "smith..jack.s" ! My gosh, it even likes a dot as a first character. It seems like it would be so simple to code, but it isn't. I am using .NET, btw.</p> <p>Frustrating.</p>
<p>that helps?</p> <pre><code>/^[^\s\.]+(?:\.[^\s\.]+)*$/ </code></pre> <p>or, in extended format, with comments (ruby-style)</p> <pre><code>/ ^ # start of line [^\s\.]+ # one or more non-space non-dot (?: # non-capturing group \. # dot something [^\s\.]+ # one or more non-space non-dot )* # zero or more times $ # end of line /x </code></pre> <p>you're not clear on how many times you can have dot-something, but you can replace the <code>*</code> with <code>{1,3}</code> or something, to specify how many repetitions are allowed.</p> <p>i should probably make it clear that the slashes are the literal regex delimiter in ruby (and perl and js, etc).</p>
<p>I think you'd benefit from using + which means "1 or more", instead of * meaning "any number including zero".</p>
11,352
<p>I'm doing some text rendering in Cocoa using NSAttributedString, and setting the font and underline properties, etc. However, I can't figure out how I can change the text's tracking. Any suggestions?</p>
<p>I don't think font tracking is an exposed property for text layout with attributed strings.</p> <p>You could perhaps use the available <strong>expansion</strong> attribute on whitespace, and manually insert whitespace characters with scaling factors to influence their width, but I expect that would be a fiddly hack for anything other than trivial cases.</p> <p>The only other route I can think of is to use your own custom attributes along with an <code>NSLayoutManager</code> subclass. The cocoa text system is extremely flexible, but with that flexibility comes a greater degree of complexity.</p>
<p>My solution so far has simply been to use the kerning attribute, as tracking and kerning are similar. Is there any better solution?</p>
37,048
<p>Users are occassionally getting the above error when using our application (VB.Net, Winforms, using v2 of the framework). I'm not able to reproduce it. The callstack is as follows:</p> <p>: System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt. at System.Windows.Forms.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam) at System.Windows.Forms.NativeWindow.DefWndProc(Message&amp; m) at System.Windows.Forms.Control.DefWndProc(Message&amp; m) at System.Windows.Forms.Control.WndProc(Message&amp; m) at System.Windows.Forms.ComboBox.WndProc(Message&amp; m) at ControlEx.AutoCompleteCombo.WndProc(Message&amp; m) at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message&amp; m) at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&amp; m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)</p> <p>The code for ControlEx.AutoCompleteCombo.WndProc is as follows:</p> <pre><code>Protected Overrides Sub WndProc(ByRef m As System.Windows.Forms.Message) Try If Not m_fReadOnly Then MyBase.WndProc(m) Else Select Case m.Msg Case WM_LBUTTONDOWN, WM_LBUTTONDBLCLK ' do nothing Case Else MyBase.WndProc(m) End Select End If Catch ex As OutOfMemoryException Throw New OutOfMemoryException("Exception during WndProc for combo " &amp; Me.Name, ex) End Try End Sub </code></pre> <p>The error handling was added so we can determine which combo causes the problem when we get an OutOfMemoryException.</p> <p>Any clues as to what causes this would be muchly appreciated! :-)</p>
<p>I have a strange non-deterministic feeling with the OutOfMemoryException in your code.</p> <p>Why do you need that? And if you need it, may this be the cause of your problems? OutOfMemoryExceptions are very rare. If you have these, I would think it is a strong indication something else is wrong.</p>
<p>It looks like you're using a custom combo box control called AutoCompleteCombo. I would suspect that the WndProc override in that class has a bug in it - probably changing the value of the message parameter. Can you post that method's code so we can have a look?</p> <hr> <p>There's nothing in the code that you posted that would cause a problem. You should probably look at the rest of AutoCompleteCombo's code for potential bugs. There's not really anything else to go on.</p>
32,843
<pre><code>sub foo {[$#{$_[!$||$|]}*@{$_[!!$_^!$_]}?@{$_[!$..!!$.]}[$_[@--@+]% @{$_[$==~/(?=)//!$`]}..$#{$_[$??!!$?:!$?]},($)?!$):!!$))..$_[$--$-]%@{ $_[$]/$]]}-(!!$++!$+)]:@{$_[!!$^^^!$^^]}]} </code></pre> <p>update: I thought the word "puzzle" would imply this, but: <em>I</em> know what it does - I wrote it. If the puzzle doesn't interest you, please don't waste any time on it.</p>
<h3>Here is how you figure out how to de-obfuscate this subroutine.</h3> <p><em>Sorry for the length</em></p> <p>First let's tidy up the code, and add useful comments.</p> <pre><code>sub foo { [ ( # ($#{$_[1]}) $#{ $_[ ! ( $| | $| ) # $OUTPUT_AUTOFLUSH === $| # $| is usually 0 # ! ( $| | $| ) # ! ( 0 | 0 ) # ! ( 0 ) # 1 ] } * # @{$_[1]} @{ $_[ !!$_ ^ !$_ # !! 1 ^ ! 1 # ! 0 ^ 0 # 1 ^ 0 # 1 # !! 0 ^ ! 0 # ! 1 ^ 1 # 0 ^ 1 # 1 ] } ) ? # @{$_[1]} @{ $_[ !$. . !!$. # $INPUT_LINE_NUMBER === $. # $. starts at 1 # !$. . !!$. # ! 1 . !! 1 # 0 . ! 0 # 0 . 1 # 01 ] } [ # $_[0] $_[ # @LAST_MATCH_START - @LAST_MATCH_END # 0 @- - @+ ] % # @{$_[1]} @{ $_[ $= =~ /(?=)/ / !$` #( fix highlighting )`/ # $= is usually 60 # /(?=)/ will match, returns 1 # $` will be '' # 1 / ! '' # 1 / ! 0 # 1 / 1 # 1 ] } .. # $#{$_[1]} $#{ $_[ $? ? !!$? : !$? # $CHILD_ERROR === $? # $? ? !!$? : !$? # 0 ? !! 0 : ! 0 # 0 ? 0 : 1 # 1 # 1 ? !! 1 : ! 1 # 1 ? 1 : 0 # 1 ] } , # ( 0 ) ( $) ? !$) : !!$) # $EFFECTIVE_GROUP_ID === $) # $) ? !$) : !!$) # 0 ? ! 0 : !! 0 # 0 ? 1 : 0 # 0 # 1 ? ! 1 : !! 1 # 1 ? 0 : 1 # 0 ) .. # $_[0] $_[ $- - $- # 0 # $LAST_PAREN_MATCH = $- # 1 - 1 == 0 # 5 - 5 == 0 ] % # @{$_[1]} @{ $_[ $] / $] # $] === The version + patchlevel / 1000 of the Perl interpreter. # 1 / 1 == 1 # 5 / 5 == 1 ] } - # ( 1 ) ( !!$+ + !$+ # !! 1 + ! 1 # ! 0 + 0 # 1 + 0 # 1 ) ] : # @{$_[1]} @{ $_[ !!$^^ ^ !$^^ # !! 1 ^ ! 1 # ! 0 ^ 0 # 1 ^ 0 # 1 # !! 0 ^ ! 0 # ! 1 ^ 1 # 0 ^ 1 # 1 ] } ] } </code></pre> <p>Now let's remove some of the obfuscation.</p> <pre><code>sub foo{ [ ( $#{$_[1]} * @{$_[1]} ) ? @{$_[1]}[ ( $_[0] % @{$_[1]} ) .. $#{$_[1]} , 0 .. ( $_[0] % @{$_[1]} - 1 ) ] : @{$_[1]} ] } </code></pre> <p>Now that we have some idea of what is going on, let's name the variables.</p> <pre><code>sub foo{ my( $item_0, $arr_1 ) = @_; my $len_1 = @$arr_1; [ # This essentially just checks that the length of $arr_1 is greater than 1 ( ( $len_1 -1 ) * $len_1 ) # ( ( $len_1 -1 ) * $len_1 ) # ( ( 5 -1 ) * 5 ) # 4 * 5 # 20 # 20 ? 1 : 0 == 1 # ( ( $len_1 -1 ) * $len_1 ) # ( ( 2 -1 ) * 2 ) # 1 * 2 # 2 # 2 ? 1 : 0 == 1 # ( ( $len_1 -1 ) * $len_1 ) # ( ( 1 -1 ) * 1 ) # 0 * 1 # 0 # 0 ? 1 : 0 == 0 # ( ( $len_1 -1 ) * $len_1 ) # ( ( 0 -1 ) * 0 ) # -1 * 0 # 0 # 0 ? 1 : 0 == 0 ? @{$arr_1}[ ( $item_0 % $len_1 ) .. ( $len_1 -1 ), 0 .. ( $item_0 % $len_1 - 1 ) ] : # If we get here, @$arr_1 is either empty or has only one element @$arr_1 ] } </code></pre> <p>Let's refactor the code to make it a little bit more readable.</p> <pre><code>sub foo{ my( $item_0, $arr_1 ) = @_; my $len_1 = @$arr_1; if( $len_1 &gt; 1 ){ return [ @{$arr_1}[ ( $item_0 % $len_1 ) .. ( $len_1 -1 ), 0 .. ( $item_0 % $len_1 - 1 ) ] ]; }elsif( $len_1 ){ return [ @$arr_1 ]; }else{ return []; } } </code></pre>
<p>It takes two arrayrefs and returns a new arrayref with the contents of the second array rearranged such that the second part comes before the first part, split at a point based on the memory location of the first array. When the second array is empty or contains one item, just returns a copy of the second array. Equivalent to the following:</p> <pre><code>sub foo { my ($list1, $list2) = @_; my @output; if (@$list2 &gt; 0) { my $split = $list1 % @$list2; @output = @$list2[$split .. $#$list2, 0 .. ($split - 1)]; } else { @output = @$list2; } return \@output; } </code></pre> <p><code>$list1 % @$list2</code> essentially picks a random place to split the array, based on <code>$list</code> which evaluates to the memory address of $list when evaluated in a numeric context.</p> <p>The original mostly uses a lot of tautologies involving punctuation variables to obfuscate. e.g.</p> <ul> <li><code>!$| | $|</code> is always 1</li> <li><code>@- - @+</code> is always 0</li> </ul> <p>Updated to note that <code>perltidy</code> was very helpful deciphering here, but it choked on <code>!!$^^^!$^^</code>, which it reformats to <code>!!$^ ^ ^ !$^ ^</code>, which is invalid Perl; it should be <code>!!$^^ ^ !$^^</code>. This might be the cause of RWendi's compile error.</p>
12,532
<p>I would like to be able to loop through all of the defined parameters on my reports and build a display string of the parameter name and value. I'd then display the results on the report so the user knows which parameters were used for that specific execution. The only problem is that I cannot loop through the Parameters collection. There doesn't seem to be an indexer on the Parameters collection, nor does it seem to implement IEnumerable. Has anyone been able to accomplish this? I'm using SSRS 2005 and it must be implemented within the Report Code (i.e., no external assembly). Thanks!</p>
<p>Unfortunately, it looks like there's no simple way to do this. See <a href="http://www.jameskovacs.com/blog/DiggingDeepIntoReportingServices.aspx" rel="nofollow noreferrer">http://www.jameskovacs.com/blog/DiggingDeepIntoReportingServices.aspx</a> for more info. If you look at the <a href="http://www.jameskovacs.com/blog/CommentView.aspx?guid=31eeaafd-a118-4e76-917d-78d54441aee9#commentstart" rel="nofollow noreferrer">comments of that post</a>, there are some ways to get around this, but they're not very elegant. The simplest solution will require you to have a list of the report parameters somewhere in your Report Code, which obviously violates the <a href="http://en.wikipedia.org/wiki/DRY" rel="nofollow noreferrer">DRY</a> principle, but if you want the simplest solution, you might just have to live with that.</p> <p>You might want to rethink your constraint of no external assembly, as it looks to me that it would be much easier to do this with an external assembly. Or if your report isn't going to change much, you can create the list of parameter names and values manually.</p>
<p>If I'm understanding your question, just do what I do: Drop a textbox on the report, then while you are setting up the report, insert the following: ="Parameter1: " + Parameters!Parameter.Label + ", Parameter2: " + Parameters!Parameter2.Label...</p> <p>Granted, it's not the prettiest thing, but it does work pretty well in our app.</p> <p>And I'm using Labels instead of Values since we have datetime values, and the user only cares about either the short date or the month and year (depending on circumstance), and I've already done that formatting work in setting up the parameters.</p>
10,974
<p>I have a base class with a property which (the get method) I want to overwrite in the subclass. My first thought was something like:</p> <pre><code>class Foo(object): def _get_age(self): return 11 age = property(_get_age) class Bar(Foo): def _get_age(self): return 44 </code></pre> <p>This does not work (subclass bar.age returns 11). I found a solution with an lambda expression which works:</p> <pre><code>age = property(lambda self: self._get_age()) </code></pre> <p>So is this the right solution for using properties and overwrite them in a subclass, or are there other preferred ways to do this?</p>
<p>I simply prefer to repeat the <code>property()</code> as well as you will repeat the <code>@classmethod</code> decorator when overriding a class method. </p> <p>While this seems very verbose, at least for Python standards, you may notice:</p> <p>1) for read only properties, <code>property</code> can be used as a decorator:</p> <pre><code>class Foo(object): @property def age(self): return 11 class Bar(Foo): @property def age(self): return 44 </code></pre> <p>2) in Python 2.6, <a href="http://docs.python.org/library/functions.html#property" rel="noreferrer">properties grew a pair of methods</a> <code>setter</code> and <code>deleter</code> which can be used to apply to general properties the shortcut already available for read-only ones:</p> <pre><code>class C(object): @property def x(self): return self._x @x.setter def x(self, value): self._x = value </code></pre>
<pre><code>class Foo: # Template method @property def age(self): return self.dothis() # Hook method of TM is accessor method of property at here def dothis(self): return 11 class Bar(Foo): def dothis(self): return 44 </code></pre> <p>Same as Nizam Mohamed, just to mention that <a href="https://google.github.io/styleguide/pyguide.html?showone=Comments#Comments" rel="nofollow noreferrer">style guide</a> 2.13.4 using both template method and property</p>
29,391
<p>I have a dataset in MySQL where using limit is already an expensive query, and finding the number of results is expensive as well. Thus, I'd like to avoid doing another query to find the number of results. I cannot use MYSQL_CALC_FOUND_ROWS because the limit is inside a subquery:</p> <pre><code>SELECT * FROM items, ( SELECT item_id FROM (etc) WHERE some.field=&lt;parameter&gt; AND (etc) GROUP BY (something) ORDER BY (something_else) DESC LIMIT 15 ) subset WHERE item.id=subset.item_id </code></pre> <p>I could left join items and do away with the subquery, then be able to use MYSQL_CALC_FOUND_ROWS, however this is very, very, slow. I've tried all index optimizations and let's just assume it is out of the question.</p> <p>This now becomes more a design question... <strong>how do I allow the user to page through this data when I don't know the last page</strong>? I only know if they've gone too far (eg: query returns no results).</p>
<p>Here's a summary of an article by MySQL guru Baron Schwartz:</p> <p><a href="http://www.mysqlperformanceblog.com/2008/09/24/four-ways-to-optimize-paginated-displays/" rel="noreferrer">http://www.mysqlperformanceblog.com/2008/09/24/four-ways-to-optimize-paginated-displays/</a></p> <h2>Four Ways to Optimize Paginated Displays</h2> <ol> <li><p>On the first query, fetch and cache all the results. </p></li> <li><p>Don't show all results. Not even Google lets you see the millionth result. </p></li> <li><p>Don't show the total count or the intermediate links to other pages. Show only the "next" link.</p></li> <li><p>Estimate how many results there are. Again, Google does this and nobody complains.</p></li> </ol>
<p>To reinforce that, the concept of "how many" is extremely transitory anyway; by the time the answer gets to the user, it could easily be wrong.</p>
45,185
<p>I am currently working on a project which requires migration of content from different content management Systems to SharePoint. Are there any good, preferably open source, tools that would help me do this? Also, what are the best practices that I would have to keep in mind when it comes to such projects. One more thing that i would like to factor here is reusablity, because we might have to work on similar migration projects, from other Content Management systems in future. </p>
<p>This MSDN blog also goes into some detail about the Migration API and may be useful as its generally very had to do this sort of thing without getting your hands dirty</p> <p><a href="http://blogs.msdn.com/sharepointdeveloperdocs/archive/2007/11/30/content-migration-in-sharepoint.aspx" rel="nofollow noreferrer">http://blogs.msdn.com/sharepointdeveloperdocs/archive/2007/11/30/content-migration-in-sharepoint.aspx</a></p> <p>Also, IMHO you shouldn't dismiss proprietary products as although they can be expensive they may save you considerable time and therefore cost if you have a large conversion project.</p> <p><a href="http://www.tzunami.com/Pages/default.aspx" rel="nofollow noreferrer">http://www.tzunami.com/Pages/default.aspx</a></p> <p><a href="http://www.avepoint.com/products/sharepoint-migration" rel="nofollow noreferrer">http://www.avepoint.com/products/sharepoint-migration</a></p> <p>Tricks and tips - <a href="http://www.parallelspace.net/portals/ALS305-mwherman-Content%20Migration-1-1-18-RC6_FINAL.ppt" rel="nofollow noreferrer">http://www.parallelspace.net/portals/ALS305-mwherman-Content%20Migration-1-1-18-RC6_FINAL.ppt</a></p>
<p>We have had good mileage from going to the nearest university and grabbing some IT students to do a manual migration. </p> <p>The students like the extra cash and it is sometimes easier when the Information Architectures of the site changes between systems.</p>
25,148
<p>As a side project, I am looking at creating a personal finance program. I have tried using Money and Excel to keep track of my finances but have either been unhappy with the stability or lack of features. My question is this, what tools have you used to keep track of your personal finances? Here are some requirements I would like to achieve:</p> <ol> <li>Stable</li> <li>Can automatically download data from banks for free</li> <li>Customizable enough to easily create a total balance from selected accounts</li> </ol> <p>I was thinking of using a python script, but really haven't thought it out further than that. What interfaces are available to automatically download account information?</p> <p>EDIT: So it seems like the general consensus that there are many open source tools are out there which can be modified to suit your needs. Also, many people seem to be happy with using Quicken if they are willing to spend some money. As far as online record tracking, <a href="http://www.mint.com/" rel="nofollow noreferrer">mint</a> seems to be the most popular choice.</p> <p>The only problem I have with using the online systems such as mint or yodlee, is that there is no easy way to "approve" the bank transactions so that you can check off your receipts and see if they match the charges. </p>
<p>Perhaps instead of starting from scratch and attempting to re-create tens of thousands of man hours of programming work, you could try some open source alternatives. If one of them is close enough but missing a feature or two, you could add it yourself.</p> <p><a href="http://www.rewardprograms.org/thefreegeek/features/wide-open-wallet-50-awesome-open-source-financial-tools.html" rel="nofollow noreferrer">Here's a list of 50 open source financial tools</a>.</p> <p>(I haven't used any of these. I use Quicken myself, and like it a lot.)</p>
<p>Funny, I'm currently working on my own as well. Used Quicken &amp; excel in the past. But I've had the same issues with that as you. I like the ability to keep all my finances/usernames/passwords on my own pc. Call me paranoid but I'm not a huge fan of the online versions. My own setup is maybe halfway done, which means I'm about a year out from completing a first run of it. It's been pretty interesting to work though.</p> <p>Building off your list, here's what I think a financial app should do:</p> <p>rename/categorize based off of what you've already set up* (this is where i find most others lacking)</p> <p>show you where you'll be in x years at the current rate* (do any of them currently do this?)</p> <p>see how future purchases or events will fit into your budget* (i havent seen this either)</p> <p>as well as all the normal bells and whistles. </p>
25,411
<p>We have a 4 server cluster running ASP.NET web application using ASP.NET State Server Service for session. On one of the 4 servers ASP.NET State Server Service is running and other servers are configured to look at this. Very often we have to patch the servers, and applying patch on the State Server requires few minutes of downtime. </p> <p>Is there a way to configure more than two ASP.NET State Server Services in a cluster, so if one goes down, the other takes over?</p>
<p>I'd look into Session State Partitioning. Good info here: <a href="http://blog.maartenballiauw.be/post/2008/01/ASPNET-Session-State-Partitioning-using-State-Server-Load-Balancing.aspx" rel="nofollow noreferrer">http://blog.maartenballiauw.be/post/2008/01/ASPNET-Session-State-Partitioning-using-State-Server-Load-Balancing.aspx</a></p>
<p>A second ASP.NET State Server Service cannot take over if the first one fails <em>without</em> losing the part of session info stored on the first server. New sessions will be handled fine by the second server. To get this behaviour you need to set up session state partitioning (see <a href="https://stackoverflow.com/questions/74190/can-you-have-more-than-one-asp-net-state-server-service-in-a-cluster/74221#74221">Jon Galloway's answer</a>).</p> <p>This behaviour is by design; the ASP.NET state service does not do replication of the session data between servers.</p> <p>If you need out of process session data replicated to several servers you must either use one of the commercial offerings (ScaleOut, for instance) or wait for Microsoft Project Velocity to become production-ready. Personally I am eagerly awaiting the release of Velocity and will switch to it from ASP.NET state server as soon as I feel confident in the product.</p> <p><a href="http://blogs.msdn.com/velocity/archive/2008/06/05/how-to-use-session-store-provider-microsoft-project-code-named-velocity.aspx" rel="nofollow noreferrer">This link</a> has more on Velocity for session state for ASP.NET.</p>
9,988
<p>I need to get the default printer name. I'll be using C# but I suspect this is more of a framework question and isn't language specific.</p>
<p>The easiest way I found is to create a new <code>PrinterSettings</code> object. It starts with all default values, so you can check its <em>Name</em> property to get the name of the default printer.</p> <p><code>PrinterSettings</code> is in System.Drawing.dll in the namespace <code>System.Drawing.Printing</code>.</p> <pre><code>PrinterSettings settings = new PrinterSettings(); Console.WriteLine(settings.PrinterName);</code></pre> <p>Alternatively, you could maybe use the static <code>PrinterSettings.InstalledPrinters</code> method to get a list of all printer names, then set the <em>PrinterName</em> property and check the <em>IsDefaultPrinter</em>. I haven't tried this, but the documentation seems to suggest it won't work. Apparently <em>IsDefaultPrinter</em> is only true when <em>PrinterName</em> is not explicitly set.</p>
<ul> <li>1st create an instance of the <code>PrintDialog</code> object.</li> <li>then call the print dialog object and leave the <code>PrinterName</code> blank. this will cause the windows object to return the defualt printer name</li> <li>write this to a string and use it as the printer name when you call the print procedure</li> </ul> <p>Code:</p> <pre><code>Try Dim _printDialog As New System.Windows.Forms.PrintDialog xPrinterName = _printDialog.PrinterSettings.PrinterName '= "set as Default printer" Catch ex As Exception System.Windows.Forms.MessageBox.Show("could not printed Label.", "Print Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End Try </code></pre>
11,164
<p>What should be the best way to recognize that a number is connected to a fax without actually sending faxes around ?</p> <p>I suppose that a short phone call can be made: the goal is to determine if a number that is declared as a fax line is <em>really</em> a fax line, working and available.</p>
<p>If you can make a phone call, many faxes create a &quot;<a href="http://telecom.tbi.net/fax-call.htm" rel="nofollow noreferrer">Fax Identification tone</a>&quot;.</p> <blockquote> <p>This signal may be sent by the Terminating FAX machine anywhere between 1.8 to 2.5 seconds AFTER answering the call. The CED signal consists of a 2100 Hz tone that is from 2.6 to 4 seconds in duration. The CED tone is useful for disabling any echo cancellers on the line.</p> <p>The CED also incorporates a &quot;silent&quot; interval following the 2100 Hz tone. This interval lasts from 55 to 95 (75 +/- 20) mS. Following this interval, the Terminating FAX machine will initiate the Pre-Message Identification procedures by transmitting a 300 BPS &quot;Line Turn-around&quot; preamble.</p> </blockquote> <p>Some older faxes do not support that though, no idea how they can be triggered (i.e. by you sending a tone first, but that could be really annoying if you have a phone instead of a fax number)</p>
<p>Many old fax lines are set to automatically pick up even on a voice call, so you could just call and check. On the other hand, it won't work on a lot of new ones, so while you could tell that one is a fax line, you couldn't tell it wasn't.</p>
42,816
<p>I have a legacy C library that creates a tree of objects. I would like to convert the tree into a pre-existing Python class. How do I create the PyObject for that class?</p>
<p>Take a look at generating your Python bindings by using a tool such as <a href="https://launchpad.net/pybindgen/" rel="nofollow noreferrer">pybindgen</a>. These guys are trying to make a superior binding generator, they talk about the shortcomings of other tools (e.g. SWIG) on their front page.</p>
<p>I've had success using <a href="http://robin.python-hosting.com/" rel="nofollow noreferrer">Robin</a> in these scenarios.</p>
49,619
<p>I've a HTML page with several Div's that will show the time difference between now and each given date.</p> <pre><code>&lt;div class="dated" onEvent="calculateHTML(this, 'Sat Jun 09 2007 17:46:21')"&gt; 30 Minutes Ago&lt;/div&gt; </code></pre> <p>I want that time difference to be dynamic (calculated to all elements when the page loads and also within a time interval)</p> <p>So, my idea was to go to all div's of class "dated", calculate the time diference for each one and replace the correspondent innerHTML.</p> <p>Is this the best aproach or should I try a different one?</p> <p>Edit: <br>One of the problems I've encountered was, where do I keep within the div, the date that will be used to generate the text?</p>
<p>Using innerHTML works most (all?) of the time and may frequently be faster than generating a bunch of HTML (i.e. not in this case).</p> <p>I always prefer using standard methods as shown below, because I know they should never break. [Note that I don't check the 'class' attribute directly, since an element may have multiple classes.]</p> <pre><code>function adjustDates() { var i; var elms = document.getElementsByTagName("div"); for (i = 0; i &lt; elms.length; i++) { var e = elms[i]; /* update timestamps with date */ if (elementHasClass(e, "dated")) { var txt = YOUR_DIFFERENCE_CODE(e); e.replaceChild(document.createTextNode(txt), e.lastChild); } } } </code></pre>
<p>When you get around to taking user data, <strong>always</strong> use dom methods to append user data to the page and assume all user data will contain horrible stuff like " ' > and and hrefs. </p> <p>"User data" here includes any text string that you didn't produce yourself. This includes browser user-agents, application library version strings, everything. </p> <p>( Its really easy to get this one wrong, so my advice is to use DOM methods everywhere unless you <em>KNOW</em> you have a speed problem. Profile and don't prematurely optimise )</p>
42,441
<p>How can I make xargs execute the command exactly once for each line of input given? It's default behavior is to chunk the lines and execute the command once, passing multiple lines to each instance. </p> <blockquote> <p>From <a href="http://en.wikipedia.org/wiki/Xargs" rel="noreferrer">http://en.wikipedia.org/wiki/Xargs</a>: </p> <p>find /path -type f -print0 | xargs -0 rm</p> <p>In this example, find feeds the input of xargs with a long list of file names. xargs then splits this list into sublists and calls rm once for every sublist. This is more efficient than this functionally equivalent version:</p> <p>find /path -type f -exec rm '{}' \;</p> </blockquote> <p>I know that find has the "exec" flag. I am just quoting an illustrative example from another resource.</p>
<p>The following will only work if you do not have spaces in your input:</p> <pre><code>xargs -L 1 xargs --max-lines=1 # synonym for the -L option </code></pre> <p> from the man page:</p> <pre><code>-L max-lines Use at most max-lines nonblank input lines per command line. Trailing blanks cause an input line to be logically continued on the next input line. Implies -x. </code></pre>
<p>In your example, the point of piping the output of find to xargs is that the standard behavior of find's -exec option is to execute the command once for each found file. If you're using find, and you want its standard behavior, then the answer is simple - don't use xargs to begin with.</p>
24,293
<p>I'm currently doing some GUI testing on a ASP.net 2.0 application. The RDBMS is SQL Server 2005. The host is Win Server 2003 / IIS 6.0.</p> <p>I do not have the source code of the application because it was programmed by an external company who's not releasing the code.</p> <p>I've noticed that the application performs well when I restart IIS but after some testing, after I have opened and closed my browser for a couple of hours, the application starts to get slower and slower. I was wondering if this behaviour was due to a bad closing connection practice from the programmers : I'm suspecting an open connection leak on the database here.</p> <p>I guess the .Net garbage collector will eventually close them but... that can take a while, no?</p> <p>I've got SQL Server Management Studio and I do notice from the activity monitor that there are quite a few connections opened on the database.</p> <p>From all that's being said above, here are some questions related to the main question : </p> <ol> <li><p>Is there any way to know in SQL Server 2005 if connections are open because they're waiting to be used in a connection pool or if they're open because they are used by an application?</p></li> <li><p>Does somone know of good online/paper resources where I could learn how to use performance counters or some other kind of tools to help track down these kind of issues?</p></li> <li><p>If performance counters are the best solution, what are the variables that I should watch?</p></li> </ol>
<p>Found this thread researching a similar problem. I came up with the following sql as a good way to debug leaky connections in SQL Server:</p> <pre><code>SELECT S.spid, login_time, last_batch, status, hostname, program_name, cmd, ( select text from sys.dm_exec_sql_text(S.sql_handle) ) as last_sql FROM sys.sysprocesses S where dbid &gt; 0 and DB_NAME(dbid) = '&lt;my_database_name&gt;' and loginame = '&lt;my_application_login&gt;' order by last_batch asc </code></pre> <p>What this gives you is all open connections on a particular database and login, <em>along with the last sql executed on that connection</em>, sorted by the time at which that sql was executed.</p> <p>Because of connection pooling, you can’t just rely on the fact that there are a lot of connections hanging around to tell you that you have a connection leakage, because connection pooling will keep connections around even if they are closed correctly from code. However, if you do have a connection leakage, what you will see is that some connections become “frozen”—they will show up in the above query and the “last_batch” timestamp will never change. The other connections will also hang around, but every time new sql is run on them, the “last_batch” timestamp gets updated. So the effect is that the frozen connections will float to the top of this query. </p> <p>If you have the source code of the application in question, the fact that this gives you the last sql executed on the orphaned connection is very valuable for debugging.</p> <p><strong>Note</strong> The spelling mistake with 'loginame' (missing 'n') is in the <code>sys.sysprocesses</code> view. The statement above is correct.</p> <blockquote> <p>loginame nchar(128) Login name.</p> </blockquote> <p><a href="https://learn.microsoft.com/en-us/sql/relational-databases/system-compatibility-views/sys-sysprocesses-transact-sql?view=sql-server-ver15" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/sql/relational-databases/system-compatibility-views/sys-sysprocesses-transact-sql?view=sql-server-ver15</a></p>
<p>I would start by looking at the connections and looking at activity times, and see if you can find items that are keeping the connections open. </p> <p>I would say thought that if the solution is to restart IIS, you might also look at the memory usage of the application to see if there is a memory leak or something there that really causes its footprint to grow.</p> <p>If open connections were an issue, in activity monitor you would see a VERY large number of connections with no activity.</p> <p>For performance counters you might start looking at the "SQL Server : General Stats" performance object.</p>
26,128
<p>We are using jQuery <a href="http://jquery.com/demo/thickbox/" rel="noreferrer">thickbox</a> to dynamically display an iframe when someone clicks on a picture. In this iframe, we are using <a href="http://devkick.com/lab/galleria/demo_01.htm" rel="noreferrer">galleria</a> a javascript library to display multiple pictures.</p> <p>The problem seems to be that <code>$(document).ready</code> in the iframe seems to be fired too soon and the iframe content isn't even loaded yet, so galleria code is not applied properly on the DOM elements. <code>$(document).ready</code> seems to use the iframe parent ready state to decide if the iframe is ready.</p> <p>If we extract the function called by document ready in a separate function and call it after a timeout of 100&nbsp;ms. It works, but we can't take the chance in production with a slow computer.</p> <pre><code>$(document).ready(function() { setTimeout(ApplyGalleria, 100); }); </code></pre> <p>My question: which jQuery event should we bind to to be able to execute our code when the dynamic iframe is ready and not just it's a parent?</p>
<p>I answered a similar question (see <a href="https://stackoverflow.com/questions/164085/javascript-callback-when-iframe-is-finished-loading">Javascript callback when IFRAME is finished loading?</a>). You can obtain control over the iframe load event with the following code:</p> <pre><code>function callIframe(url, callback) { $(document.body).append('&lt;IFRAME id="myId" ...&gt;'); $('iframe#myId').attr('src', url); $('iframe#myId').load(function() { callback(this); }); } </code></pre> <p>In dealing with iframes I found good enough to use load event instead of document ready event.</p>
<p>Try this,</p> <pre><code>&lt;iframe id="testframe" src="about:blank" onload="if (testframe.location.href != 'about:blank') testframe_loaded()"&gt;&lt;/iframe&gt; </code></pre> <p>All you need to do then is create the JavaScript function testframe_loaded().</p>
25,121
<p>Even though I always strive for complete validation these days, I often wonder if it's a waste of time. If the code runs and it looks the same in all browsers (I use browsershots.org to verify) then do I need to take it any further or am I just being overly anal?</p> <p>What level do you hold your code to when you create it for:</p> <p>a) yourself b) your clients</p> <p>P.S. Jeff and company, why doesn't stack overflow validate? :)</p> <p><strong>EDIT: Some good insights, I think that since I've been so valid-obsessed for so long I program knowing what will cause problems and what won't so I'm in a better position than people who create a site first and then "go back and fix the validation problems"</strong></p> <p><strong>I think I may post another question on stack overflow; "Do you validate as you go or do you finish and then go back and validate?" as that seems to be where this question is going</strong></p>
<p>a) Must look the same</p> <p>b) As standards-compliant as possible, but not so anal that it blocks finishing work</p> <p>In a situation where you have perpetual access to the code, I don't think standards-compliance is all that important, since you can always make changes to the code if something breaks. If you don't have perpetual access (ie, you sign off on the code and it becomes someone else's responsibility), it's probably best to be as standards-compliant as possible to minimize maintenance headaches later... even if you never have to deal with the code again, your reputation persists and can be transmitted to other potential clients, and many teams like to blame the previous developer(s) for problems that come up.</p>
<p>I think validation is a good litmus test of whether you've done things properly, so if there are only a few minor problems, why not fix them and ensure your site will at least be understood correctly by browsers in the future (even if they do render things differently for other reasons)?</p> <p>OTOH, for most projects, validation seems like a huge headache and if you can get things working across browsers, it's not worth spending an extra day/week+ on just validation.</p>
2,950
<p><strong>System Description</strong> </p> <p>A plotting component that uses OOXML to generate a document.</p> <p>Plotting component consists of several parts. All parts are written in C++ as exe + dll's, with the exception of the interface to the OOXML document. The latter component is a COM component that was created in C#/.NET. The main reason for this is that the .NET framework contains <em>System.IO.Packaging</em>. This is a very handy built-in facility for dealing with OOXML documents.</p> <p>We create a document out of a template OOXML document where certain bits and pieces are replaced by their actual content.</p> <p>One of these bits is an OLE Server component. Basically this is a binary segment within the OOXML file. For writing this binary segment, the Packaging component apparently uses isolated storage. </p> <p><strong>Problem</strong></p> <p>Writing a segment > 8MB results in an exception being thrown "Unable to determine the identity of the domain".</p> <p>On the C++ side this exception contains the error ISS_E_ISOSTORE ( 0x80131450 ).</p> <p>We have analyzed this and as far as we can tell, this is a security feature that prevents semi-untrusted third-party component from completely ruining your HD by writing immense files.</p> <p>We have then tried a lot of things in the .NET/COM component ( creating custom AppDomains, setting Attributes for maximum permissivity, Creating our own Streams and passing those to the Packaging component ) but every time it resulted in the same exception being thrown.</p> <p>What could we do to make this work?</p> <p>Could it be that when the .NET component is instantiated as a COM component, its AppDomain is alway untrusted? </p>
<p>You might try to unzip the package yourself (instead of using the .NET package API), write directly to the file which represents the binary segment and zip it again. </p>
<p>You should change the title of that question since your problem is not OOXML related.</p> <p>Other than that: what system are you working on that 8MB chunks of data result in the risk of totalling your hard drive?</p>
17,839
<p>I'd like to be able to determine if a directory such as a '.app' is considered to be a package or bundle from Finder's point of view on the command line. I don't think this would be difficult to do with a small shell program, but I'd rather not re-invent the wheel if I don't have to.</p>
<h2>Update:</h2> <p>On all systems with Spotlight, using <code>mdls</code> you can detect bundles looking at the kMDItemContentTypeTree property. E.g.:</p> <pre><code>mdls -name kMDItemContentTypeTree "/Applications/Safari.app" </code></pre> <p>produces the following output for me</p> <pre><code>kMDItemContentTypeTree = ( "com.apple.application-bundle", "com.apple.application", "public.executable", "com.apple.localizable-name-bundle", "com.apple.bundle", "public.directory", "public.item", "com.apple.package" ) </code></pre> <p>Whenever you see <code>com.apple.package</code> there, it is supposed to be displayed as a package by Finder. Of course, everything with "bundle" in the name implies that already but not all packages are bundles (bundles are a specific subset of packages that have a well defined directory structure).</p> <hr> <h2>Old Answer:</h2> <p>You can get a list of all registered file type extensions, using this command (OS X prior to Leopard):</p> <pre><code>/System/Library/Frameworks/ApplicationServices.framework/Frameworks\ /LaunchServices.framework/Support/lsregister -dump </code></pre> <p>or for Leopard and later:</p> <pre><code>/System/Library/Frameworks/CoreServices.framework/Versions/A/Frameworks\ /LaunchServices.framework/Versions/A/Support/lsregister -dump </code></pre> <p>Every file extension there has flags. If the package flag is set, this is a package.</p> <p>E.g.</p> <pre><code> claim id: 806354944 name: Bundle role: none flags: apple-internal relative-icon-path package icon: Contents/Resources/KEXT.icns bindings: .bundle -------------------------------------------------------- claim id: 1276116992 name: Plug-in role: none flags: apple-internal relative-icon-path package icon: Contents/Resources/KEXT.icns bindings: .plugin </code></pre> <p>Compare this to a file that is no bundle</p> <pre><code> claim id: 2484731904 name: TEXT role: viewer flags: apple-internal icon: bindings: .txt, .text, 'TEXT' </code></pre> <p>The only way to really get all bundles is by looking up in the LaunchService database (the one we dumped above). If you just go by whether it has a plist or not or whether the bundle bit is set or not, you might catch some or even many bundles, but you can't catch all of them. This is the database Finder uses to determine</p> <ul> <li>Is this directory a bundle or not?</li> <li>Is this a known file extension or not?</li> <li>Which applications should be listed under "Open With" for this file type?</li> <li>Which icon should I use for displaying this file type?</li> </ul> <p>and some more stuff.</p> <p>[EDIT: Added path for Leopard, thanks to Hagelin for the update]</p>
<p>A bundle should always have a file `./contents/Info.plist'. You can check for the existance of this in a directory, if so then it's a package/bundle.</p>
14,734
<p>Question in the title.</p> <p>And what happens when all 3 of <code>$_GET[foo]</code>, <code>$_POST[foo]</code> and <code>$_COOKIE[foo] exist?</code> Which one of them gets included to <code>$_REQUEST?</code></p>
<p>I'd say never.</p> <p>If I wanted something to be set via the various methods, I'd code for each of them to remind myself that I'd done it that way - otherwise you might end up with things being overwritten without realising.</p> <p>Shouldn't it work like this:</p> <p>$_GET = non destructive actions (sorting, recording actions, queries)</p> <p>$_POST = destructive actions (deleting, updating)</p> <p>$_COOKIE = trivial settings (stylesheet preferences etc)</p> <p>$_SESSION = non trivial settings (username, logged in?, access levels)</p>
<p>I use POST when I don't want people to have easy access to what is being passed and I use GET when I don't mind them seeing the value in the url. I generally don't use cookies for much as I find SESSION to be fine for persisting values (although having a proper registry is the best way to utilize that).</p>
13,311
<p>Anyone familiar with specific security issues in the current version of DotNetNuke?<br> (I've already checked out their site, securityfocus, etc...)</p> <p>I've reopened the question, since my client developed their system using DotNetNuke - hence it is a programming question. I just need to know some issues regarding this platform.</p>
<p>DNN Vulnerability information will be at: <a href="http://www.dotnetnuke.com/News/SecurityPolicy/tabid/940/Default.aspx" rel="noreferrer">http://www.dotnetnuke.com/News/SecurityPolicy/tabid/940/Default.aspx</a></p>
<p>I just want to add to this, that DotNetNuke corporation, right or wrong, asks that people not publicly discuss exploit details if known, as it exposes the wide community to greater risk.</p> <p>Typically the rule of thumb with DNN is to upgrade to the most current version, and keep an eye on the security items posted on the site, also, keeping an eye on Cathal's blog is a good idea as he is the head security person.</p>
16,724
<p>I'm trying to use Python with ReportLab 2.2 to create a PDF report.<br> According to the <a href="http://www.reportlab.com/docs/userguide.pdf" rel="noreferrer">user guide</a>,</p> <blockquote> <p>Special TableStyle Indeces [sic]</p> <p>In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation. This allows splitting tables with nicer effects around the split.</p> </blockquote> <p>I've tried using several style elements, including:</p> <pre><code>('TEXTCOLOR', (0, 'splitfirst'), (1, 'splitfirst'), colors.black) ('TEXTCOLOR', (0, 'splitfirst'), (1, 0), colors.black) ('TEXTCOLOR', (0, 'splitfirst'), (1, -1), colors.black) </code></pre> <p>and none of these seems to work. The first generates a TypeError with the message: </p> <pre><code>TypeError: cannot concatenate 'str' and 'int' objects </code></pre> <p>and the latter two generate TypeErrors with the message:</p> <pre><code>TypeError: an integer is required </code></pre> <p>Is this functionality simply broken or am I doing something wrong? If the latter, what am I doing wrong?</p>
<p>Well, it looks as if I will be answering my own question.</p> <p>First, the documentation flat out lies where it reads "In any style command the first row index may be set to one of the special strings 'splitlast' or 'splitfirst' to indicate that the style should be used only for the last row of a split table, or the first row of a continuation." In the current release, the "splitlast" and "splitfirst" row indices break with the aforementioned TypeErrors on the TEXTCOLOR and BACKGROUND commnds.</p> <p>My suspicion, based on reading the source code, is that only the tablestyle line commands (GRID, BOX, LINEABOVE, and LINEBELOW) are currently compatible with the 'splitfirst' and 'splitlast' row indices. I suspect that all cell commands break with the aforementioned TypeErrors.</p> <p>However, I was able to do what I wanted by subclassing the Table class and overriding the onSplit method. Here is my code:</p> <pre><code>class XTable(Table): def onSplit(self, T, byRow=1): T.setStyle(TableStyle([ ('TEXTCOLOR', (0, 1), (1, 1), colors.black)])) </code></pre> <p>What this does is apply the text color black to the first and second cell of the second row of each page. (The first row is a header, repeated by the repeatRows parameter of the Table.) More precisely, it is doing this to the first and second cell of each frame, but since I am using the SimpleDocTemplate, frames and pages are identical.</p>
<blockquote> <p>[...] In any style command <strong>the first row index</strong> may be set to one of the special strings [...]</p> </blockquote> <p>In your first example you're setting the <em>second</em> row index to a special string as well.</p> <p>Not sure why the other two don't work... Are you sure this is where the exception is coming from?</p>
10,388
<p>I'm trying to parse a grammar in ocamlyacc (pretty much the same as regular yacc) which supports function application with no operators (like in Ocaml or Haskell), and the normal assortment of binary and unary operators. I'm getting a reduce/reduce conflict with the '-' operator, which can be used both for subtraction and negation. Here is a sample of the grammar I'm using:</p> <pre><code>%token &lt;int&gt; INT %token &lt;string&gt; ID %token MINUS %start expr %type &lt;expr&gt; expr %nonassoc INT ID %left MINUS %left APPLY %% expr: INT { ExprInt $1 } | ID { ExprId $1 } | expr MINUS expr { ExprSub($1, $3) } | MINUS expr { ExprNeg $2 } | expr expr %prec APPLY { ExprApply($1, $2) }; </code></pre> <p>The problem is that when you get an expression like "a - b" the parser doesn't know whether this should be reduced as "a (-b)" (negation of b, followed by application) or "a - b" (subtraction). The subtraction reduction is correct. How do I resolve the conflict in favor of that rule?</p>
<p>Unfortunately, the only answer I can come up with means increasing the complexity of the grammar.</p> <ol> <li>split <code>expr</code> into <code>simple_expr</code> and <code>expr_with_prefix</code></li> <li>allow only <code>simple_expr</code> or <code>(expr_with_prefix)</code> in an APPLY</li> </ol> <p>The first step turns your reduce/reduce conflict into a shift/reduce conflict, but the parentheses resolve that.</p> <p>You're going to have the same problem with 'a b c': is it <code>a(b(c))</code> or <code>(a(b))(c)</code>? You'll need to also break off <code>applied_expression</code> and required <code>(applied_expression)</code> in the grammar.</p> <p>I think this will do it, but I'm not sure:</p> <pre><code>expr := INT | parenthesized_expr | expr MINUS expr parenthesized_expr := ( expr ) | ( applied_expr ) | ( expr_with_prefix ) applied_expr := expr expr expr_with_prefix := MINUS expr </code></pre>
<p>Well, this simplest answer is to just ignore it and let the default reduce/reduce resolution handle it -- reduce the rule that appears first in the grammar. In this case, that means reducing <code>expr MINUS expr</code> in preference to <code>MINUS expr</code>, which is exactly what you want. After seeing <code>a-b</code>, you want to parse it as a binary minus, rather than a unary minus and then an apply.</p>
4,413