instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>Is there a version of FitNesse that works on Delphi 2006/2007/2009?</p> <p>If so where can I find It?</p> <p>Are there any other programs like FitNesse that work on Delphi 2006?</p>
<p>If the model class is sufficiently intelligent, it should recognize the standard Python ways of doing this.</p> <p>Try:</p> <pre><code>getattr(p, s) setattr(p, s, new_value) </code></pre> <p>There is also hasattr available.</p>
<p>p.first_name = "New first name" p.put()</p> <p>or p = Person(first_name = "Firsty", last_name = "Lasty" ) p.put()</p>
11,728
<p>I am currently running gdb version 6.7.1 on Ubuntu Linux, and working in a C++ project.</p> <p>Surprisingly I was trying to debug a constructor and I have found that local variables declared within the scope of the constructor are not followed or noticed by gdb. Is this a bug ?</p> <p>Thanks for any information ..</p>
<p>It is a <a href="http://gcc.gnu.org/bugzilla/show_bug.cgi?id=27574" rel="noreferrer">bug</a> in GCC, not in GDB.</p> <p>It was recently <a href="http://gcc.gnu.org/bugzilla/show_bug.cgi?id=27574#c21" rel="noreferrer">fixed</a>.</p>
<p>If you are using optimization (-O), disable it (remove the -O or use -O0). The compiler is sometimes too smart and guesses a variable it not needed, do calculations at compile time, change a variable's scope, or several other tricks.</p> <p>Note that even with "no optimization", some trivial optimizations are still done, but they shouldn't interfere much with debugging. Also, with inline-heavy use of C++ (including the STL), your program can become much slower without optimization.</p>
27,684
<p>I inherited a database built with the idea that composite keys are much more ideal than using a unique object ID field and that when building a database, a single unique ID should <b><em>never</em></b> be used as a primary key. Because I was building a Rails front-end for this database, I ran into difficulties getting it to conform to the Rails conventions (though it was possible using custom views and a few additional gems to handle composite keys).</p> <p>The reasoning behind this specific schema design from the person who wrote it had to do with how the database handles ID fields in a non-efficient manner and when it's building indexes, tree sorts are flawed. This explanation lacked any depth and I'm still trying to wrap my head around the concept (I'm familiar with using composite keys, but not 100% of the time).</p> <p>Can anyone offer opinions or add any greater depth to this topic? </p>
<p>Most of the commonly used engines (MS SQL Server, Oracle, DB2, MySQL, etc.) would not experience noticeable issues using a surrogate key system. Some may even experience a performance boost from the use of a surrogate, but performance issues are highly platform-specific.</p> <p>In general terms, the natural key (and by extension, composite key) verses surrogate key debate has a long history with no likely “right answer” in sight.</p> <p>The arguments for natural keys (singular or composite) usually include some the following:</p> <p>1) <strong>They are already available in the data model.</strong> Most entities being modeled already include one or more attributes or combinations of attributes that meet the needs of a key for the purposes of creating relations. Adding an additional attribute to each table incorporates an unnecessary redundancy.</p> <p>2) <strong>They eliminate the need for certain joins.</strong> For example, if you have customers with customer codes, and invoices with invoice numbers (both of which are "natural" keys), and you want to retrieve all the invoice numbers for a specific customer code, you can simply use <code>"SELECT InvoiceNumber FROM Invoice WHERE CustomerCode = 'XYZ123'"</code>. In the classic surrogate key approach, the SQL would look something like this: <code>"SELECT Invoice.InvoiceNumber FROM Invoice INNER JOIN Customer ON Invoice.CustomerID = Customer.CustomerID WHERE Customer.CustomerCode = 'XYZ123'"</code>.</p> <p>3) <strong>They contribute to a more universally-applicable approach to data modeling.</strong> With natural keys, the same design can be used largely unchanged between different SQL engines. Many surrogate key approaches use specific SQL engine techniques for key generation, thus requiring more specialization of the data model to implement on different platforms.</p> <p>Arguments for surrogate keys tend to revolve around issues that are SQL engine specific:</p> <p>1) <strong>They enable easier changes to attributes when business requirements/rules change.</strong> This is because they allow the data attributes to be isolated to a single table. This is primarily an issue for SQL engines that do not efficiently implement standard SQL constructs such as DOMAINs. When an attribute is defined by a DOMAIN statement, changes to the attribute can be performed schema-wide using an ALTER DOMAIN statement. Different SQL engines have different performance characteristics for altering a domain, and some SQL engines do not implement DOMAINS at all, so data modelers compensate for these situations by adding surrogate keys to improve the ability to make changes to attributes.</p> <p>2) <strong>They enable easier implementations of concurrency than natural keys.</strong> In the natural key case, if two users are concurrently working with the same information set, such as a customer row, and one of the users modifies the natural key value, then an update by the second user will fail because the customer code they are updating no longer exists in the database. In the surrogate key case, the update will process successfully because immutable ID values are used to identify the rows in the database, not mutable customer codes. However, it is not always desirable to allow the second update – if the customer code changed it is possible that the second user should not be allowed to proceed with their change because the actual “identity” of the row has changed – the second user may be updating the wrong row. Neither surrogate keys nor natural keys, by themselves, address this issue. Comprehensive concurrency solutions have to be addressed outside of the implementation of the key.</p> <p>3) <strong>They perform better than natural keys.</strong> Performance is most directly affected by the SQL engine. The same database schema implemented on the same hardware using different SQL engines will often have dramatically different performance characteristics, due to the SQL engines data storage and retrieval mechanisms. Some SQL engines closely approximate flat-file systems, where data is actually stored redundantly when the same attribute, such as a Customer Code, appears in multiple places in the database schema. This redundant storage by the SQL engine can cause performance issues when changes need to be made to the data or schema. Other SQL engines provide a better separation between the data model and the storage/retrieval system, allowing for quicker changes of data and schema.</p> <p>4) <strong>Surrogate keys function better with certain data access libraries and GUI frameworks.</strong> Due to the homogeneous nature of most surrogate key designs (example: all relational keys are integers), data access libraries, ORMs, and GUI frameworks can work with the information without needing special knowledge of the data. Natural keys, due to their heterogeneous nature (different data types, size etc.), do not work as well with automated or semi-automated toolkits and libraries. For specialized scenarios, such as embedded SQL databases, designing the database with a specific toolkit in mind may be acceptable. In other scenarios, databases are enterprise information resources, accessed concurrently by multiple platforms, applications, report systems, and devices, and therefore do not function as well when designed with a focus on any particular library or framework. In addition, databases designed to work with specific toolkits become a liability when the next great toolkit is introduced.</p> <p>I tend to fall on the side of natural keys (obviously), but I am not fanatical about it. Due to the environment I work in, where any given database I help design may be used by a variety of applications, I use natural keys for the majority of the data modeling, and rarely introduce surrogates. However, I don’t go out of my way to try to re-implement existing databases that use surrogates. Surrogate-key systems work just fine – no need to change something that is already functioning well.</p> <p>There are some excellent resources discussing the merits of each approach:</p> <p><a href="http://www.google.com/search?q=natural+key+surrogate+key" rel="noreferrer">http://www.google.com/search?q=natural+key+surrogate+key</a></p> <p><a href="http://www.agiledata.org/essays/keys.html" rel="noreferrer">http://www.agiledata.org/essays/keys.html</a></p> <p><a href="http://www.informationweek.com/news/software/bi/201806814" rel="noreferrer">http://www.informationweek.com/news/software/bi/201806814</a></p>
<p>I just wanted to add something here that I don't ever see covered when discussing auto-generated integer identity fields with relational databases (because I see them a lot), and that is, it's base type can an will overflow at some point.</p> <p>Now I'm not trying to say this automatically makes composite ids the way to go, but it's just a matter of fact that even though more data could be logically added to a table (which is still unique), the single auto-generated integer identity could prevent this from happening.</p> <p>Yes I realize that for most situations it's unlikely, and using a 64bit integer gives you lots of headroom, and realistically the database probably should have been designed differently if an overflow like this ever occurred. </p> <p>But that doesn't prevent someone from doing it... a table using a single auto-generated 32bit integer as it's identity, which is expected to store all transactions at a global level for a particular fast-food company, is going fail as soon as it tries to insert it's 2,147,483,648th transaction (and that is a completely feasible scenario).</p> <p>It's just something to note, that people tend to gloss over or just ignore entirely. If any table is going to be inserted into with regularity, considerations should be made to just how often and how much data will accumulate over time, and whether or not an integer based identifier should even be used.</p>
19,245
<p>I have a .NET application which uses an accdb file (MS Access 2007 format) as its database. To install this app on another machine I need to install the Access engine on that machine. Microsoft has this file: AccessDatabaseEngine.exe which includes the engine, but when extracted during installation, runs another .msi installer.</p> <p>As you can guess, since this msi is run during the installation of another msi (my app's installer) the Access engine setup fails with error 1500: "Another installation is in progress. Finish that one before continuing this one..."</p> <p>I found the Runtime for Access 2007 as well, and it does install the engine, but the Runtime package is again an msi installer which means I'm still having the same problem.</p> <p>Any ideas to include the engine in my app's installer?</p>
<p>You probably want to have a look at this article: <a href="http://msdn.microsoft.com/en-gb/library/bb687991.aspx" rel="nofollow noreferrer">Adding Programs to Access 2007 Deployment Packages</a></p> <p>The <a href="http://msdn.microsoft.com/en-us/office/bb229700.aspx" rel="nofollow noreferrer">Access Developer Extensions</a> offer a basic but functional installer that can take care of the general deployment scenarios.</p>
<p>I wouldn't recommend WinInstall, we have it in my office and we have to keep calling them in to package stuff for us as it's so finiky to use. Some things they haven't been able to package at all. WISE Studio is better or a free alternative is <a href="http://www.appdeploy.com/" rel="nofollow noreferrer">AppDeploy</a> whihc I have heard great things about.</p>
49,541
<p>I have been interested in database developing for some time now and decided that MS SQL has a lot to offer in terms of T-SQL and generally much more functionality (not saying that Oracle or Postgres don't have that).</p> <p>I would like to know: </p> <ol> <li>What are the big paradigm changes I should expect to see? </li> <li>How much effort do "regular" companies put into developing their database (for transactions, triggers, events, data cleansing, ETL)? </li> <li>What can I expect from the inner-workings of MS SQL developer teams and how they interact with the .NET application developers?</li> </ol> <p>I hope I have phrased my question correctly. I am not very clued-up about the whole .NET scene.</p>
<p>Can't answer #1 as I've never worked with mysql but I'll take a shot at #2 and #3.</p> <p>This tends to depend on the size of the database and/or the size (or professionalism) of the company. Companies with large databases with many users spend a great deal of time indeed making sure that the database both has integrity and is performance tuned. They woudl lose customers if they did not. We have 6 people who do nothing but ETL work and 5 dbas who tune and manage the databases and database servers as well as many many developers who write t-sql code. </p> <p>As far as #3, in good companies these people work together very well as a team. In bad companies, there is often tension between the two groups and each uses the other group as a scapegaoat for whatever problems occur. I work with a bunch of great .net developers. They respect my database expertise as I respect their .net expertise and we caonsult each other on design issues and tuning issues and in general any issue that needs input from both sides. </p>
<p><a href="http://forums.mysql.com/read.php?60,124480,124480" rel="nofollow noreferrer">http://forums.mysql.com/read.php?60,124480,124480</a> details using linked servers from SQL Server to MySQL to do the actual data migration.</p>
14,384
<p>Is there any built-in functionality for classical set operations on the java.util.Collection class? My specific implementation would be for ArrayList, but this sounds like something that should apply for all subclasses of Collection. I'm looking for something like:</p> <pre><code>ArrayList&lt;Integer&gt; setA ... ArrayList&lt;Integer&gt; setB ... ArrayList&lt;Integer&gt; setAintersectionB = setA.intersection(setB); ArrayList&lt;Integer&gt; setAminusB = setA.subtract(setB); </code></pre> <p>After some searching, I was only able to find home-grown solutions. Also, I realize I may be confusing the idea of a "Set" with the idea of a "Collection", not allowing and allowing duplicates respectively. Perhaps this is really just functionality for the Set interface?</p> <p>In the event that nobody knows of any built-in functionality, perhaps we could use this as a repository for standard practice Java set operation code? I imagine this wheel has been reinvented numerous times.</p>
<p>Intersection is done with <code>Collection.retainAll</code>; subtraction with <code>Collection.removeAll</code>; union with <code>Collection.addAll</code>. In each case, as <code>Set</code> will act like a set and a <code>List</code> will act like a list.</p> <p>As mutable objects, they operate in place. You'll need to explicitly copy if you want to retain the original mutable object unmutated.</p>
<p>Are you looking for <a href="http://java.sun.com/javase/6/docs/api/java/util/Set.html" rel="nofollow noreferrer" title="Set">java.util.Set</a> interface (and its implementations HashSet and TreeSet (sorted))?<br> The interface defines removeAll(Collection c) which looks like substract(), and retainAll(Collection c) which looks like intersection.</p>
19,823
<p>In an HTML form post what are valid characters for creating a multipart boundary?</p>
<p>According to <a href="https://www.rfc-editor.org/rfc/rfc2046#section-5.1.1" rel="nofollow noreferrer">RFC 2046</a>, section 5.1.1:</p> <pre><code> boundary := 0*69&lt;bchars&gt; bcharsnospace bchars := bcharsnospace / &quot; &quot; bcharsnospace := DIGIT / ALPHA / &quot;'&quot; / &quot;(&quot; / &quot;)&quot; / &quot;+&quot; / &quot;_&quot; / &quot;,&quot; / &quot;-&quot; / &quot;.&quot; / &quot;/&quot; / &quot;:&quot; / &quot;=&quot; / &quot;?&quot; </code></pre> <p>So it can be between 1 and 70 characters long, consisting of alphanumeric, and the punctuation you see in the list. Spaces are allowed except at the end.</p>
<p>There are no rules as of the content of the boundary but as it must not occur in any of the parts of your message content is usually a randomly generated sequence of numbers, letters or combination of both in order to guarantee uniqueness and differentiate from any possible dictionary words. So as you start your message each data type section is separated by “–” followed by the boundary sequence and the content type + encoding. After the last section “–” followed by the boundary followed by “–” is used to delimit the end of the message. The way multipart content works is by specifying a boundary in the “Content-type:” header of your email. The boundary is used to separate the different content types and looks something like this:</p> <pre><code>Content-type: multipart/mixed; boundary="fU3W4Vzr4G3D54f3" </code></pre>
17,750
<p>whats your rule of thumb for maximum size for xml files.</p> <p>What if I ask maximum no of records, and one record have 10 values for instance? Another condition is we are loading it from web.</p>
<p>My rule is that <strong>if it's too slow to do what I want, then it's too big</strong>, and your data probably needs to be moved to some other format... database or such.</p> <p>Traversing XML nodes or using XPath can be a dog.</p>
<p>I worked on a project in 2010 where by i had to move a newspaper website from Typo 3 to Drupal 7 and the fastest way around at the time was to export all the content as xml and then parse them into drupal(Xpath). We tried doing it in one go but we had problems at 4Gigs .. So we divided the xmls per year and had each file have less time to parse and the file size in MBs and that went fine. Other reads suggest that the max file may depend on your ram.</p>
16,047
<p>There are no builtin matrix functions in C#, but there are in the F# powerpack.</p> <p>Rather than using a third party or open source C# library, I wonder about rolling my own in F#, and exposing the useful bits to C#. </p> <p>Wondered if anybody has already thought of this, or tried it, and whether it's a good idea.</p> <p>Should I expose it as a class, or a load of static functions?</p> <p>Or should I create a C# wrapper class, and have that call down to F#? Or have the F# use the C# class as input and output?</p> <p>Any thoughts?</p> <p>Answer thanks to <a href="https://stackoverflow.com/questions/271966/about-using-f-to-create-a-matrix-assembly-usable-from-c#272250">Hath</a> below: you can use the F# library directly in C# (operators as well!):</p> <pre><code>using System; using System.Text; using Microsoft.FSharp.Math; namespace CSharp { class Program { static void Main(string[] args) { double[,] x = { { 1.0, 2.0 }, { 4.0, 5.0 } }; double[,] y = { { 1.0, 2.0 }, { 7.0, 8.0 } }; Matrix&lt;double&gt; m1 = MatrixModule.of_array2(x); Matrix&lt;double&gt; m2 = MatrixModule.of_array2(y); var mp = m1 * m2; var output = mp.ToArray2(); Console.WriteLine(output.StringIt()); Console.ReadKey(); } } public static class Extensions { public static string StringIt(this double[,] array) { var sb = new StringBuilder(); for (int r = 0; r &lt; array.Length / array.Rank; r++) { for (int c = 0; c &lt; array.Rank; c++) { if (c &gt; 0) sb.Append("\t"); sb.Append(array[r, c].ToString()); } sb.AppendLine(); } return sb.ToString(); } } } </code></pre>
<p>can you not just reference the f# library you need in c# and use it directly?</p> <p>I've done a similar thing to reference the FSharp.Core.dll to get at the </p> <pre><code>Microsoft.FSharp.Math.BigInt class. </code></pre> <p>So you can probably just reference the FSharp.PowerPack.dll to get at the </p> <pre><code>Microsoft.FSharp.Math.Matrix&lt;A&gt; class </code></pre>
<p>There are very good Matrix classes in the XNA Framework. I'd either reference that dll, or most likely use reflector and copy and paste the code into my own solution. I know it doesn't answer your question directly, but just another idea....</p>
34,223
<p>When I try to build my projects in Visual Studio 2008, web sites won't build anymore, they hang on this stage: </p> <pre><code>------ Build started: Project: C:\...\Web\, Configuration: Debug Any CPU ------ Validating Web Site Building directory '/Web/Admin/Secure/'. Building directory '/Web/Admin/'. Building directory '/Web/Students/'. Building directory '/Web/'. Validation Complete </code></pre> <p>And I have to cancel it as it doesn't complete even after leaving it for an hour. Does anyone have any ideas on what's going on? Class libraries build fine.</p>
<p>This can also often happen in the event that you have a 3rd party control that is not licensed\registered properly. It may be attempting to display a warning\registration UI that is not making it to focus. We have had this issue on our build servers alot.</p>
<p>I also executed this command from the cmd prompt (Run as Administrator): </p> <pre><code>regsvr32 "C:\Program Files (x86)\Internet Explorer\ieproxy.dll" </code></pre>
48,558
<p>What's the most efficient way to resize large images in PHP?</p> <p>I'm currently using the <a href="http://en.wikipedia.org/wiki/GD_Graphics_Library" rel="noreferrer">GD</a> function imagecopyresampled to take high resolution images, and cleanly resize them down to a size for web viewing (roughly 700 pixels wide by 700 pixels tall).</p> <p>This works great on small (under 2 MB) photos and the entire resize operation takes less than a second on the server. However, the site will eventually service photographers who may be uploading images up to 10 MB in size (or images up to 5000x4000 pixels in size).</p> <p>Doing this kind of resize operation with large images tends to increase the memory usage by a very large margin (larger images can spike the memory usage for the script past 80 MB). Is there any way to make this resize operation more efficient? Should I be using an alternate image library such as <a href="http://en.wikipedia.org/wiki/ImageMagick" rel="noreferrer">ImageMagick</a>?</p> <p>Right now, the resize code looks something like this</p> <pre><code>function makeThumbnail($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality) { // Takes the sourcefile (path/to/image.jpg) and makes a thumbnail from it // and places it at endfile (path/to/thumb.jpg). // Load image and get image size. $img = imagecreatefromjpeg($sourcefile); $width = imagesx( $img ); $height = imagesy( $img ); if ($width &gt; $height) { $newwidth = $thumbwidth; $divisor = $width / $thumbwidth; $newheight = floor( $height / $divisor); } else { $newheight = $thumbheight; $divisor = $height / $thumbheight; $newwidth = floor( $width / $divisor ); } // Create a new temporary image. $tmpimg = imagecreatetruecolor( $newwidth, $newheight ); // Copy and resize old image into new image. imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height ); // Save thumbnail into a file. imagejpeg( $tmpimg, $endfile, $quality); // release the memory imagedestroy($tmpimg); imagedestroy($img); </code></pre>
<p>People say that ImageMagick is much faster. At best just compare both libraries and measure that.</p> <ol> <li>Prepare 1000 typical images.</li> <li>Write two scripts -- one for GD, one for ImageMagick.</li> <li>Run both of them a few times.</li> <li>Compare results (total execution time, CPU and I/O usage, result image quality).</li> </ol> <p>Something which the best everyone else, could not be the best for you.</p> <p>Also, in my opinion, ImageMagick has much better API interface.</p>
<p>I suggest that you work something along these lines:</p> <ol> <li>Perform a getimagesize( ) on the uploaded file to check image type and size</li> <li>Save any uploaded JPEG image smaller than 700x700px in to the destination folder "as-is"</li> <li>Use GD library for medium size images (see this article for code sample: <a href="http://salman-w.blogspot.com/2008/10/resize-images-using-phpgd-library.html" rel="nofollow noreferrer">Resize Images Using PHP and GD Library</a>)</li> <li>Use ImageMagick for large images. You can use ImageMagick in background if you prefer.</li> </ol> <p>To use ImageMagick in background, move the uploaded files to a temporary folder and schedule a CRON job that "convert"s all files to jpeg and resizes them accordingly. See command syntax at: <a href="http://www.imagemagick.org/script/command-line-processing.php" rel="nofollow noreferrer">imagemagick-command line processing</a></p> <p>You can prompt the user that file is uploaded and scheduled to be processed. The CRON job could be scheduled to run daily at a specific interval. The source image could be deleted after processing to assure that an image is not processed twice.</p>
3,376
<p>Is there such a thing? </p> <p>I'm talking about something like a C++ <code>new</code> command i.e. allocation of memory which necessitates explicit releasing of the memory (or risk memory leaks).</p> <p>I ask because I remember having to solve some GDI leak problems previously by setting forms/controls/other objects to <code>Nothing</code> but can't remember what or why now...</p> <p>Do we ever have to worry about memory management when developing in VB6?</p>
<p>There are several areas of concern as far as Memory management in VB6.</p> <p>The first are circular references where a child class points back to a parent and vice versa. Without explicitly setting the reference to Nothing, This is sometimes true of forms as well especially a dialog that is an editor for a Target object. Again making sure everything set to nothing will solve the problem.</p> <p>The fundamental principles are 1) If anything pointed to by an object is "alive" then it won't be garbage collected. So when you set the reference to the parent object of a circular reference the child is alive so the parent doesn't get garbage collected, since the parent still alive the child doesn't get garbage collected. </p> <p>The same with forms. If you don't set the Target Property of a dialog that editing an object to nothing than it won't fire the final series of events as long as the Target Object is alive.</p> <p>The most common side effects of doing this are that your application won't shut down properly and your memory footprint will grow the longer the application is used.</p> <p>As for GDI leaks, anytime you use an external DLL that uses handles, pointers. You put yourself in the same realm as C++ for those functions. So you have to make sure that you follow all the rules of the particular API or DLLs you are using which often involves explicitly destroying that which you created after you are done with it.</p> <p>There is an elegant solution for the circular reference problem. Instead of the child referencing a parent directly you use a proxy.</p> <p>First make a Proxy Class for the parent object.</p> <pre><code>Option Explicit Public Event GetRef(ByRef RHS As MyObject) Public Function GetMyObject() As MyObject Dim Ref As MyObject RaiseEvent GetRef(Ref) Set GetMyObject = Ref End Function </code></pre> <p>Then define a private variable in the Parent</p> <pre><code>Private WithEvents MyProxy As MyObjectProxy Private Sub Class_Initialize() Set MyProxy = New MyObjectProxy End Sub </code></pre> <p>Then setup a read only property called Proxy and implement the GetRef event.</p> <pre><code>Public Property Get Proxy() As MyObjectProxy Set Proxy = MyProxy End Property Private Sub MyProxy_GetRef(RHS As MyObject) Set RHS = Me End Sub </code></pre> <p>For the child or anything else that needs a reference the code is as follows.</p> <pre><code>Private ParentProxy As MyObjectProxy Public Property Get Parent() As MyObject If ParentProxy Is Nothing Then Set Parent = Nothing Else Set Parent = ParentProxy.GetRef End If End Property Public Property Set Parent(RHS As MyObject) If RHS Is Me Then Set MyObjectProxy = Nothing ElseIf Target Is Nothing Then Set MyObjectProxy = Nothing Else Set MyObjectProxy = RHS.Proxy End If End Property </code></pre> <p>Because the event mechanism doesn't set references or increments the COM reference count on either object it avoids the whole circular reference problem that is the bane of many VB6 programmers.</p> <p>Note: The source I got it from called it a Proxy but thanks to Anthony's comment I find it also fits the definition of the Mediator Pattern. It uses a specific VB6 Centric feature; the Event API which isn't quite in the spirit of the Mediator Pattern.</p> <p>Also realize that the .NET framework has equivalents to VB6's Event API although it is implemented differently (delegates, etc)</p>
<p>I'd like to say you never have to worry about memory management, but it's not quite true. It depends to some extent on the execution environment that your VB6 code is running in. I have certainly seen VB6 classes running under COM+ that would leak memory if they didn't explicitly set object references to Nothing when finished with them.</p> <p>Environmental issues aside, memory that you allocate within the VB6 type system will generally be cleaned up for you. I'm talking about things you allocate with the New keyword. But there is a significant exception, pointed out by rpetrich and others: -</p> <p>Because of the reference-counting mechanism that VB uses to manage the lifetime of allocated objects, it is possible to leak memory if you have any cyclic references. For example, A->B->C->A. If you have that kind of scenario you'll probably need to spot it yourself and cure it by explicitly setting references to Nothing. I am not aware of any tools that help much with identifying this kind of problem.</p> <p>Further problems come in when you're using libraries written in other languages. You might New-up a COM object written in C++ that allocates some memory internally, and find that you have to call a particular method (such as Close) to free that memory. Maybe such a COM object would be badly-written, but plenty of them exist.</p> <p>So there are no rules to follow, except perhaps: -</p> <ol> <li>Try to know as much as possible about the behaviour of any libraries you use, and</li> <li>Always run your code while watching a memory trace in Performance Monitor to make sure its memory usage isn't growing in an unbounded fashion.</li> <li>Try to be aware of cyclic references ;-)</li> </ol>
33,139
<p>I work for a custom cabinetry manufacturer and we write our own pricing program for our product. I have a form that has a pop-up box so the user can select which side the hinge will be on for ambiguous doors on that cabinet. I've got that to work so far, but when they copy an item and paste it at the bottom I don't want the pop-up box to come up. Is there any way in Access VBA to know whether the new record is being pasted or entered manually?</p>
<p>Perhaps something on the lines of this would suit.</p> <pre><code>Option Compare Database Public gvarPasted As Boolean Private Sub txtText_AfterUpdate() If Not gvarPasted Then 'Open pop-up here Else gvarPasted = False End If End Sub Private Sub txtText_KeyDown(KeyCode As Integer, Shift As Integer) 'Detect ctrl-V combination If Shift = acCtrlMask And KeyCode = vbKeyV Then gvarPasted = True End If End Sub </code></pre>
<p>Perhaps something on the lines of this would suit.</p> <pre><code>Option Compare Database Public gvarPasted As Boolean Private Sub txtText_AfterUpdate() If Not gvarPasted Then 'Open pop-up here Else gvarPasted = False End If End Sub Private Sub txtText_KeyDown(KeyCode As Integer, Shift As Integer) 'Detect ctrl-V combination If Shift = acCtrlMask And KeyCode = vbKeyV Then gvarPasted = True End If End Sub </code></pre>
26,904
<p>My question is possibly a subtle one:</p> <p>Web services - are they extensions of the presentation/web layer? ..or are they extensions of the biz/data layer?</p> <p>That may seem like a dumb question. <em>Web</em> services are an extension of the <em>web</em> tier. I'm not so sure though. I'm building a pretty standard webform with some AJAX-y features, and it seems to me I could build the web services in one of two ways:</p> <ol> <li>they could retrieve data for me (biz/data layer extension).<br /> example: <code>GetUserData(userEmail)</code><br /> where the web form has javascript on it that knows how to consume the user data and make changes to markup</li> <li>they could return completely rendered user controls (html; extension of web layer)<br /> example: <code>RenderUserProfileControl(userEmail)</code><br /> where the web form has simple/dumb js that only copies and pastes the web service html in to the form</li> </ol> <p>I could see it working in either scenario, but I'm interested in different points of view... Thoughts?</p>
<p>In my mind, a web service has 2 characteristics:</p> <ol> <li>it exposes data to external sources, i.e. other sources than the application they reside within. In this sense I agree with <a href="https://stackoverflow.com/questions/118595/ajax-webservices-extensions-of-web-or-biz-layer#118814">@Pete</a> in that you're not really designing a web service; you're designing a helper class that responds to requests in a web-service-like fashion. A semantic distinction, perhaps, but one that's proved useful to me.</li> <li>it returns data (and only data) in a format that is reusable by multiple consumers. For me this is the answer to your "why not #2" question - if you return web-control-like structures then you limit the usefulness of the web service to other potential callers. They <strong>must</strong> present the data the way you're returning it, and can't choose to represent it in another way, which minimises the usefulness (and re-usefulness) of the service as a whole.</li> </ol> <p>All of that said, if what you really are looking at is a helper class that responds like a web-service and you only ever intend to use it in this one use case then you can do whatever you like, and your case #2 will <strong>work</strong>. From my perspective, though, it breaks the separation of responsibilities; you're combining data-access and rendering functions in the same class. I suspect that even if you don't care about MVC patterns option #2 will make your classes harder to maintain, and you're certainly limiting their future usefulness to you; if you ever wanted to access the same data but render it differently you'd need to refactor.</p>
<p>I would say definitely not #2, but #1 is valid. </p> <p>I also think (and this is opinion) that web services as a data access layer is not ideal. The service has to have a little bit more value (in general - I am sure there are notable exceptions to this). </p>
14,437
<p>I have a server-side web service that serves to multiple clients. Clients include web browsers, iPhone, BlackBerry, Android etc. My question is, I need to be able to generate dynamic content for views to these clients. Be it a full blown HTML template, an HTML snippet, JSON, XML, etc. Depending on the user-agent of the requesting client, a different "view" template gets generated and spat out by the web server. </p> <p>My question is, are there any elegant "view" frameworks or styles out there to adapt that simplify managing all of these snippets/fragments/full templates into some orderly fashion? I've been looking for an elegant way to manage this myriad of client handling, with straight forward maintenance and a simple hand off procedure to User Interface developers.</p>
<p>What you need is a clear separation between model and presentation. If you write a number of generic components that pull data out in a presentation-agnostic way (the model), you can then have a number of adapters, that render the output for each specific target (The views). There are frameworks around that tie all this up in one big package; They are usually labelled as <strong>MVC-framework</strong>s. But you don't really need this, if it's not to your taste. For most kinds of output, you can use a template engine to help you write the views. For stuff that is more data - less presentation - such as JSON or XML and general output that is for machine consumption, you would probably use something else to generate the output though.</p>
<p>First of all you should not return HTML by a webservice. IMHO a webservice should return generic/client independent form. I would suggest to use a simple ASPX web page that gets a bunch of XSL Layout transformations for some clients.</p> <p>Make it customizable and you will not have to touch the code for a long time, even if new clients come along or your visualization changes.</p>
38,323
<p>Can I store a database connection in the Session object?</p>
<p>It is generally not recommended to do so, a connection string in the Application variable, with a nice helper function/class is a much preferred method. <strike>Here</strike> is some reference. <em>(Dead link removed because it now leads to a phishy site)</em></p>
<p>As said by CJM, there is no need to store a connection in a Session object : connection pooling is much better.</p>
11,551
<p>I have seen lots of questions recently about WPF...</p> <ul> <li>What is it?</li> <li>What does it stand for?</li> <li>How can I begin programming WPF?</li> </ul>
<p>WPF is a new technology that will supersede Windows Forms. WPF stands for Windows Presentation Foundation Here are some useful topics on SO:</p> <ol> <li><a href="https://stackoverflow.com/questions/9591/what-wpf-books-would-you-recommend">What WPF books would you recommend</a></li> <li><a href="https://stackoverflow.com/questions/7837/what-real-world-wpf-applications-are-out-there">What real world WPF applications are out there</a></li> </ol> <p>From my practice I can say that WPF is a truly amazing technology however it takes some time to get used to because it's totally different from the WinForms. I would recommend you to take a look at this <a href="http://perseus.franklins.net/dnrtvplayer/player.aspx?ShowNum=0115" rel="nofollow noreferrer">demo</a>.</p>
<p>Windows Presentation Foundation. It's basically Microsoft's latest attempt to make development easier, and provide a whole heap of nice functionality out of the box. I'm not sure where to start, but googling "WPF 101" should throw up a few useful links. </p>
5,870
<p>I'm currently working with a specialized, interpreted, programming language implemented in Java. As a very small part of the language, I'd like to add the ability to make calls into Java. Before I dive into all of the nitty-gritty of reflection, I was wondering if anyone knew of a general library for doing the &quot;back-end&quot; part of invoking Java code reflectively.</p> <p>That is, I parse a string (I define the grammar) into some data structure that represents a Java method call (or constructor, or field access) and then pass that data structure to this library that invokes the call and returns the result. In particular, I'd like it to already handle all the edge cases that I don't want to figure out:</p> <ul> <li>Automagically pick the right method based on the types of arguments (like an intelligent Class.getDeclaredMethod())</li> <li>Handle distinction between arrays and normal object references</li> <li>etc</li> </ul> <p>I've spent a little time looking at the implementations of dynamic languages on the JVM, but these are generally much more complicated than I'm looking for, or highly optimized for the particular language.</p> <p>Another option is to convert my grammar into a string in some dynamic language and invoke it with Rhino or something, but that's a little more overhead than I'm looking for.</p>
<p>Just a comment to your own answer; actually beanutils has support for getting "a close match" given a set of parameters. See <a href="http://commons.apache.org/beanutils/v1.8.0/apidocs/org/apache/commons/beanutils/MethodUtils.html#getMatchingAccessibleMethod(java.lang.Class,%20java.lang.String,%20java.lang.Class[])" rel="nofollow noreferrer">getMatchingAccessibleMethod()</a></p> <p>BeanUtils is really powerful and has lots of utility methods for inspecting classes. The same support is naturally available for constructors.</p>
<p>I ended up going with Alex's suggestion. BeanUtils helps a lot for beans, but I don't want to work solely with Beans. FEST looks really cool and I've bookmarked it for further study, but like BeanUtils, it doesn't appear to solve what I consider to be the difficult problem here. Namely, given a method name and list of arguments, pick the method that best "fits" the arguments. If a method takes a float and I have a double, it should be smart enough to not reject that method because the signature doesn't match exactly.</p> <p>Obviously, scripting languages built on the JVM solve this problem, but in a much more complicated way than I need due to language-specific optimizations. So, since this is a minor and experimental feature, I've chosen an expeditious solution using the scripting engine support (JavaScript, in particular) in Java 1.6. Here's the basic idea:</p> <pre><code>private ScriptEngine engine = ... initialize with JavaScript engine ... private Object invoke(Object object, String methodName, Object[] args) throws RhsFunctionException { // build up "o.method(arg0, arg1, arg2, ...)" StringBuilder exp = new StringBuilder("o." + methodName); engine.put("o", object); buildArgs(arguments, exp); try { return engine.eval(exp.toString()); } catch (ScriptException e) { throw new RhsFunctionException(e.getMessage(), e); } } private void buildArgs(Object[] args, StringBuilder exp) { // Use bindings to avoid having to escape arguments exp.append('('); int i = 0; for(Symbol arg : args) { String argName = "arg" + i; engine.put(argName, arg); if(i != 0) { exp.append(','); } exp.append(argName); ++i; } exp.append(')'); } </code></pre> <p>There's obviously a bit more to it, but this is the basic idea. I don't really like building up a string and evaluating it, but by using the bindings suggested by Alex, I avoid most of the pitfalls around escaping. Furthermore, I have a clean, simple interface that I can swap out with a "real" implementation if it proves necessary.</p> <p>Any feedback or alternate solutions are more than welcome.</p>
47,593
<p>We can successfully consume a .NET 2.0 web service from a Flex/AS3 application. Aside from SSL, how else can we make the security more robust (i.e., authentication)?</p>
<p>You can leverage ASP.Net's built in session management by decorating your webmethods with </p> <blockquote> <p><code>&lt;EnableSession()&gt;</code></p> </blockquote> <p>Then, inside your method, you can check that the user still has a valid session.</p>
<p>If you're talking about <strong>securing the information</strong> going over the wire, you can use Web Service Extensions (WSE) to encrypt the body of the soap message so that you don't have to secure the channel. This way the message can get passed around from more than one endpoint (ie. it can get forwarded) and you don't need multiple https certs.</p> <p>If you're talking abut <strong>autentication</strong> then you could do forms auth with either a password in the body or in the soap headers (once again either encrypt the body or the channel). Or one of the easiest ways to secure a webservice (if it's an internal set of services) is have IIS do it, turn on NTLM and do authentication there. You can do authorization later on in the pipeline with an HTTPModule that checks peoples credential against the code they're trying to call.</p>
8,472
<p>Since PHP is a dynamic language what's the best way of checking to see if a provided field is empty? </p> <p>I want to ensure that:</p> <ol> <li>null is considered an empty string</li> <li>a white space only string is considered empty</li> <li>that "0" is not considered empty</li> </ol> <p>This is what I've got so far:</p> <pre><code>$question = trim($_POST['question']); if ("" === "$question") { // Handle error here } </code></pre> <p>There must be a simpler way of doing this?</p>
<pre><code>// Function for basic field validation (present and neither empty nor only white space function IsNullOrEmptyString($str){ return ($str === null || trim($str) === ''); } </code></pre>
<p>empty() used to work for this, but the behavior of empty() has changed several times. As always, the php docs are always the best source for exact behavior and the comments on those pages usually provide a good history of the changes over time. If you want to check for a lack of object properties, a very defensive method at the moment is:</p> <pre><code>if (is_object($theObject) &amp;&amp; (count(get_object_vars($theObject)) &gt; 0)) { </code></pre>
49,975
<p>I'm looking for a lightweight, easy to setup CI server that I can run on my laptop along with Visual Studio &amp; Resharper. I'm obviously looking at all the big names like CruiseControl, TeamCity etc etc but the biggest consideration to me is ease of setup and to a lesser extent memory footprint.</p> <p>Edit: I'd also like some suggestions for other solutions outside the big 2/3...</p> <p>Edit: I'm about to accept an answer if no one else has anything to add?</p>
<p>I use <a href="http://www.jetbrains.com/teamcity/" rel="noreferrer">TeamCity</a>, and is really, really easy to setup and get it running.</p> <p>Check the <a href="http://www.jetbrains.com/teamcity/documentation/index.html" rel="noreferrer">Demos and Documentation</a>. You will have it up and running in less than one hour!</p>
<p>I use CI as a Solo Developer.</p> <p>When I merge my dev branch into my test branch, CI grabs the code, compiles it, modifies the connection string, changes a couple of app settings, and copies it up via <a href="http://www.scootersoftware.com" rel="nofollow noreferrer">Beyond Compare</a> to my test site for people testers to have a look at.</p>
33,102
<p>There's plenty of them out there but none of them do what I would like them to do.</p> <p>Most of them crash when opening a file or simply corrupt the data. Many don't run at all. It seems to me that most were written 3-4 years ago for AS2 .sols and no longer work with FP9/AS3 sols. I'd attempt to write my own using AIR but I can't find a new spec of the byte format.</p> <p>There's an explanation of the file format here: <a href="http://sourceforge.net/docman/display_doc.php?docid=27026&amp;group_id=131628" rel="noreferrer">http://sourceforge.net/docman/display_doc.php?docid=27026&amp;group_id=131628</a></p> <p>and another here: <a href="http://sourceforge.net/docman/display_doc.php?docid=27026&amp;group_id=131628" rel="noreferrer">http://sourceforge.net/docman/display_doc.php?docid=27026&amp;group_id=131628</a></p> <p>but it looks as though both of these docs are a good 4 years old (pre-FP9) and as I'm not skilled or experienced in file formats, writing a new one, especially without an updated spec, is seeming like less and less of a viable option. </p> <p>Ideally I'd like one that can not only read the .sol, but edit and save new values also.</p> <p>Thanks!</p>
<p>Use <a href="http://blog.coursevector.com/minerva" rel="noreferrer">minerva</a>. I've tried it, it works with every .sol I open it with.</p>
<p>I'm confused, isn't the best editor for Flash 9 shared objects... Flash? It already has methods for loading, editing and saving them.</p> <hr> <p>So make the editor and put it on your website. You won't get any security errors from flash, and then just throw a password around it so regular people can't edit their .sol files.</p> <hr> <p>Yes, they are restricted by domain, so it'd have to live on the publishers sites. If you have hundreds of clients, that might be an issue, but if you have 3 or 4... It's certainly easier than coding your own file format parser.</p>
8,965
<p>Upon page load I want to move the cursor to a particular field. No problem. But I also need to select and highlight the default value that is placed in that text field.</p>
<p>From <a href="http://www.codeave.com/javascript/code.asp?u_log=7004" rel="noreferrer">http://www.codeave.com/javascript/code.asp?u_log=7004</a>:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code>var input = document.getElementById('myTextInput'); input.focus(); input.select();</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;input id="myTextInput" value="Hello world!" /&gt;</code></pre> </div> </div> </p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-js lang-js prettyprint-override"><code> var input = document.getElementById('myTextInput'); input.focus(); input.setSelectionRange( 6, 19 );</code></pre> <pre class="snippet-code-html lang-html prettyprint-override"><code> &lt;input id="myTextInput" value="Hello default value world!" /&gt;</code></pre> </div> </div> </p> <p>select particular text on textfield</p> <p>Also you can use like</p> <pre><code>input.selectionStart = 6; input.selectionEnd = 19; </code></pre>
25,879
<p>How can I go about generating a Friendly URL in C#? Currently I simple replace spaces with an underscore, but how would I go about generating URL's like Stack Overflow?</p> <p>For example how can I convert:</p> <blockquote> <p>How do I generate a Friendly URL in C#?</p> </blockquote> <p>Into</p> <blockquote> <p>how-do-i-generate-a-friendly-url-in-C</p> </blockquote>
<p>There are several things that could be improved in Jeff's solution, though.</p> <pre><code>if (String.IsNullOrEmpty(title)) return ""; </code></pre> <p>IMHO, not the place to test this. If the function gets passed an empty string, something went seriously wrong anyway. Throw an error or don't react at all.</p> <pre><code>// remove any leading or trailing spaces left over … muuuch later: // remove trailing dash, if there is one </code></pre> <p>Twice the work. Considering that each operation creates a whole new string, this is bad, even if performance is not an issue.</p> <pre><code>// replace spaces with single dash title = Regex.Replace(title, @"\s+", "-"); // if we end up with multiple dashes, collapse to single dash title = Regex.Replace(title, @"\-{2,}", "-"); </code></pre> <p>Again, basically twice the work: First, use regex to replace multiple spaces at once. Then, use regex again to replace multiple dashes at once. Two expressions to parse, two automata to construct in memory, iterate twice over the string, create two strings: All these operations can be collapsed to a single one.</p> <p>Off the top of my head, without any testing whatsoever, this would be an equivalent solution:</p> <pre><code>// make it all lower case title = title.ToLower(); // remove entities title = Regex.Replace(title, @"&amp;\w+;", ""); // remove anything that is not letters, numbers, dash, or space title = Regex.Replace(title, @"[^a-z0-9\-\s]", ""); // replace spaces title = title.Replace(' ', '-'); // collapse dashes title = Regex.Replace(title, @"-{2,}", "-"); // trim excessive dashes at the beginning title = title.TrimStart(new [] {'-'}); // if it's too long, clip it if (title.Length &gt; 80) title = title.Substring(0, 79); // remove trailing dashes title = title.TrimEnd(new [] {'-'}); return title; </code></pre> <p>Notice that this method uses string functions instead of regex functions and char functions instead of string functions whenever possible.</p>
<p>here is a simple function which can convert your string to Url, you just need to pass title or string it will convert it to user friendly Url.</p> <pre><code> public static string GenerateUrl(string Url) { string UrlPeplaceSpecialWords = Regex.Replace(Url, @"&amp;quot;|['"",&amp;?%\.!()@$^_+=*:#/\\-]", " ").Trim(); string RemoveMutipleSpaces = Regex.Replace(UrlPeplaceSpecialWords, @"\s+", " "); string ReplaceDashes = RemoveMutipleSpaces.Replace(" ", "-"); string DuplicateDashesRemove = ReplaceDashes.Replace("--", "-"); return DuplicateDashesRemove.ToLower(); } </code></pre>
5,863
<p>Is it possible to do a HTTP Head request solely using an XMLHTTPRequest in JavaScript?</p> <p>My motivation is to conserve bandwidth.</p> <p>If not, is it possible to fake it?</p>
<p>Easy, just use the HEAD method, instead of GET or POST:</p> <pre><code>function UrlExists(url, callback) { var http = new XMLHttpRequest(); http.open('HEAD', url); http.onreadystatechange = function() { if (this.readyState == this.DONE) { callback(this.status != 404); } }; http.send(); } </code></pre> <p>This is just a short example to show how to use the HEAD method. Production code may need more fine-grained callbacks for different result states (success, failure, timeout), and may use different <a href="http://www.w3.org/TR/XMLHttpRequest2/#event-handlers" rel="noreferrer">event handlers</a> (<code>onload</code>, <code>onerror</code> and <code>ontimeout</code> rather than <code>onreadystatechange</code>).</p>
<p>An XMLHTTPRequest object should have</p> <pre><code>getAllResponseHeaders(); getResponseHeader("header-name") </code></pre> <p>defined on it</p>
43,250
<p>I am using MSBuild to build my stuff. I want to use CruiseControl.net as by Build Server.</p> <p>Now, CCNET refers nAnt a lot, but it looks as if ccnet can do most of the stuff nant could do through the project configuration and msbuild. Also, nAnt seems a bit unsupported, with a Beta release that is almost a year old now.</p> <p>In short: I am actually quite happy with MSBuild (especially since it's the "official" compiler front end) and a bit uncomfortable with nAnt, but I do not want to judge prematurely.</p> <p>What would be reasons to use nAnt over MSBuild? Especially with ccnet, which seems to overlap a bit with nant in terms of features (and adding the automated build related stuff)</p>
<p>If you are quite happy with MSBuild, then I would stick with MSBuild. This may be one of those cases where the tool you learn first is the one you will prefer. I started with NAnt and can't quite get used to MSBuild. I'm sure they will both be around for quite some time.</p> <p>There are some fundamental differences between the two, probably best highlighted by <a href="http://forums.msdn.microsoft.com/en-US/msbuild/thread/994761a3-ea9d-40c7-8d4f-4c208b2023f6/" rel="noreferrer">this conversation between some NAnt fans and a Microsoftie</a>.</p> <p>Interestingly, <a href="http://codebetter.com/blogs/jeremy.miller/default.aspx" rel="noreferrer">Jeremy Miller</a> asked the exact opposite question <a href="http://codebetter.com/blogs/jeremy.miller/archive/2007/09/20/is-there-a-good-reason-to-switch-to-msbuild.aspx" rel="noreferrer">on his blog</a> last year. </p>
<p>Like what so many people have already indicated, the answer here is "it depends". There are some things like <em>repeating operations</em> that are much simpler and cleaner in NAnt. See <a href="http://forums.msdn.microsoft.com/en-US/msbuild/thread/417329cb-a6f6-45dd-9a56-98bb4aee74f9" rel="nofollow noreferrer">the MSDN forums</a> for a discussion about this.</p>
2,369
<p>How do I apply a <em>repeating</em> texture that always maintains its original scale (1 pixel in the texture = 1 pixel on screen), regardless of the vertex data it is applied with.</p> <p>I realize this is not the most usual task, but is it possible to easily set opengl to do this, or do I need to apply some kind of mask to vertex data that respects its original appearance?</p> <p>edit: in my specific case, I'm trying to draw 2D ellipses of different sizes, with the same pixel pattern. The ellipses are made of a triangle fan, and I'm having a hard time to draw a repeating texture of any kind on it. I was hoping there was some opengl configuration combination to do this easily. Also, now I realize it's important to mention that I'm using opengles, for the iphone, so GLU is not available.</p>
<p>Create the 3D object in question, without displaying it.<br> <br> You can get the bounds of the object as pixel locations by using gluProject (to get the pixels that represent the object's edges. You can then use gluUnProject to map the intervening pixels to the object's coordinates.<br> <br> Then, you start your draw over, and map a custom (on-the-fly) texture over the same object and display it.<br> <br> Not sure why you'd want to do this, but that should be a good starting point.<br> <br> Edit:<br> <br> What I mean by custom, is if the bounds of your object (in one dimension,) are -3.0 to 1.0, and the first pixel row is from -3.0 to -2.0, your texture map is going to indicate that 25% of your custom texture maps over that spot, and you create it all with the color of the pixel you want to show there.<br> <br> After thinking that through, I realized you could just draw a texture over the top of the projected screen coordinates (using the 2D drawing facilities.)<br> <br> I think that gets the gist of your idea across. I don't think it would work well in an interactive 3D demo, if the 'object' comes closer and moves away, if the texture doesn't seem to scale up and down. But you didn't say what you were actually doing.<br> <br> Edit 2:<br> <br> OpenGL 2D Projection:<br> <br> <br> CAUTION<br> Careful with the function names, e.g., opengles 1.1 has glOrthox and glOrthof. Make sure you check what is available in your gl.h header file.<br></p> <pre><code>const XSize = 640, YSize = 480 glMatrixMode (GL_PROJECTION) glLoadIdentity () glOrtho (0, XSize, YSize, 0, 0, 1) glMatrixMode (GL_MODELVIEW) glDisable(GL_DEPTH_TEST) glClear(GL_COLOR_BUFFER_BIT) // Now draw with 2i or 2f vertices instead of the normal vertex3f functions. // And for ES, of course set up your data structures and call drawarrays ofr drawelements. SwapBuffers() </code></pre> <p>This will allow you to draw 2D shapes in OpenGL (much more simply than using 3D projections.) To mix the two, e.g., draw in 3D then in 2D, follow the second link.<br> <br> Here's an excellent tutorial on 2D drawing:<br> <a href="http://basic4gl.wikispaces.com/2D+Drawing+in+OpenGL" rel="nofollow noreferrer">http://basic4gl.wikispaces.com/2D+Drawing+in+OpenGL</a><br> <br> Here's the basics on mixing the two:<br> <a href="http://www.gamedev.net/community/forums/topic.asp?topic_id=96440" rel="nofollow noreferrer">http://www.gamedev.net/community/forums/topic.asp?topic_id=96440</a><br> <br> I hope that is what you want. I get a sneaking suspicion from your post that you're having trouble mapping your texture across triangle points to make it show up 'straight'. You might want to review basic texture mapping on NeHe:<br> <a href="http://www.gamedev.net/community/forums/topic.asp?topic_id=96440" rel="nofollow noreferrer">http://www.gamedev.net/community/forums/topic.asp?topic_id=96440</a><br> E.g., gltexcoord2f specifies the point (0.0-1.0) within the texture in terms of the percentage of width and height of the texture that maps to the next drawn vertex. With triangle fans, you can have some mathematical conniptions to figure out what % of width and height of the overall object you are specifying with the vertex.<br> <br> Take, for example, a sphere with a texture map (a mercator projection of the earth,) is best mapped by calculating the lines of latitude as a basis for your underlying triangle fan vertex values, as it eases calculation of the texture coordinates. Making your polygons approximate simple geometric shapes allows you to use trigonometry to more easily calculate texture coordinates.<br> <br> I hope this is helpful.<br> <br> Hehere, I'll quit going on with desktop examples you have to modifiy. Here's an OpenGLES example that does proper 3D texture mapping. You can use what I said above, and this example, to do 2D texture mapping.<br> <a href="http://www.zeuscmd.com/tutorials/opengles/17-TextureMapping.php" rel="nofollow noreferrer">http://www.zeuscmd.com/tutorials/opengles/17-TextureMapping.php</a><br></p>
<p>I'm not really sure, but try something like this:</p> <p>Take your model matrix, perspective matrix, and stuff like that. Mash them together in the proper order by multiplying them. Take that matrix's inverse. Multiply it by your texture matrix (which is probably the identity matrix). Set that as your texture matrix.</p>
40,226
<p>I'm developing a Java ME app &amp; need pointers to some really good UI libraries. I did see a few such as Java ME Polish. Are there any more out there? For e.g. ebuddy's java ME app has an amazing UI and so is gmail's java ME app. What libraries would they have been using or would have they have developed it on their own?</p>
<p>Sun recently released and opensourced their solution to crappy looking lcdui. It is called LIghtweight UI Toolkit and can be found on <a href="http://lwuit.dev.java.net/" rel="nofollow noreferrer">lwuit.dev.java.net</a></p>
<p>You can use LWUIT for the UI development in J2ME framework.</p>
14,178
<p>Is there a clean way to redirect all attempts to going to an HTTP:// version of a site to its HTTPS:// equivalent?</p>
<p>I think the cleanest way is as described <a href="http://www.iis-aid.com/articles/how_to_guides/redirect_http_to_https_iis_7" rel="nofollow noreferrer">here on IIS-aid.com</a>. It's web.config only and so if you change server you don't have to remember all the steps you went through with the 403.4 custom error page or other special permissions, it just works.</p> <pre><code>&lt;configuration&gt; &lt;system.webServer&gt; &lt;rewrite&gt; &lt;rules&gt; &lt;rule name="HTTP to HTTPS redirect" stopProcessing="true"&gt; &lt;match url="(.*)" /&gt; &lt;conditions&gt; &lt;add input="{HTTPS}" pattern="off" ignoreCase="true" /&gt; &lt;/conditions&gt; &lt;action type="Redirect" redirectType="Permanent" url="https://{HTTP_HOST}/{R:1}" /&gt; &lt;/rule&gt; &lt;/rules&gt; &lt;/rewrite&gt; &lt;/system.webServer&gt; &lt;/configuration&gt; </code></pre>
<p>I think by 'cleanly' you mean like with a 300 redirect. Config for a lot of servers &amp; languages <a href="http://www.somacon.com/p145.php" rel="nofollow noreferrer">here</a>.</p>
6,844
<p>is there any way to make IE6 understand double classes, say I have a class MenuButton with a color class and possibly a clicked class; like :</p> <pre><code>.LeftContent a.MenuButton {..general rules..} .LeftContent a.MenuButton.Orange {..sets background-image..} .LeftContent a.MenuButton.Clicked {...hum ta dum...} </code></pre> <p>Now, IE6 understands <code>&lt;a class="MenuButton Orange"&gt;</code>, but when adding Clicked, like <code>&lt;a class="MenuButton Orange Clicked"&gt;</code>, IE just ignores the Clicked rule.</p> <p>Of course, I could rewrite my CSS, and have own rules for .MenuButtonOrange<br> and such (and it'd probably taken a lot shorter time than asking this question ;-),<br> but golly, it just so unappealing and Web 0.9...</p> <p>Cheers!</p>
<p>IE6 doesn't support multiple class selectors. The reason you see a change with the <code>Orange</code> class is because <code>a.MenuButton.Orange</code> is interpreted by IE6 as <code>a.Orange</code>.</p> <p>I recommend structuring your markup in such a way that you can work around this:</p> <pre><code>&lt;div class="leftcontent"&gt; &lt;ul class="navmenu"&gt; &lt;li&gt;&lt;a class="menubutton orange" href="#"&gt;One&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a class="menubutton orange clicked" href="#"&gt;Two&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p>By grouping by a more specific ancestor you can create variation with classes scoped by that ancestor (in this example <code>navmenu</code>):</p> <pre><code>.leftcontent .navmenu a { /* ... basic styles ... */ } .leftcontent .navmenu a.orange { /* ... extra orange ... */ } .leftcontent .navmenu a.clicked { /* ... bold text ... */ } </code></pre> <p>It's not as good as multiple classes, but I've used it to work around the lack of support in IE.</p>
<blockquote> <p>If I use (like I wrote in the question), tag-specific rules, like .LeftContent a.MenuButton.Orange, it works...</p> <p>It only matches them if the classes in the selector are in the same order as the classes on the element.</p> </blockquote> <p>This isn't quite true. IE6 (and IE7 in Quirks Mode) only remembers one class per selector-part. If you write two, the second one overrides the first. So ‘a.MenuButton.Orange’ is identical in effect to ‘a.Orange’.</p> <p>So multiple class selectors do still have to be avoided for now.</p>
40,211
<p><a href="https://stackoverflow.com/questions/63938/how-do-i-show-data-in-the-header-of-a-sql-2005-reporting-services-report">This question</a> was very helpful, however I have a list control in my report, and when the report grows over 1 page, data in the header only shows up on the last page of the report.</p> <p>Apparently, hidden textboxes have to be on every page of the report for header to function properly. How do I do that? The only control I have in the list is a textbox with bunch of text that grows way over 1 page.</p>
<p>sExchange website to the rescue!!! </p> <p>All I needed to do is to use Report Parameters with queried values from my dataset; and then reference =Parameters!Name.Value in the textbox in the header of the report.</p>
<p>the hidden text boxes can be placed within a rectangle that was a repeatwith property set to be your list item.</p>
15,262
<p>I need to display a small (15x15 pixel) animation in a Flex app. I have it FLV format, but it could be converted to somthing else. I'd prefer to have the file embedded in the app (it's only 8k in size). I've seen posts about displaying animated GIFs using third-party code which would be OK, but is there a way to do this with the native Flex libs. I also realize that FLVs can be displayed in Video objects but only if they are external files.</p>
<p>It is a lot easier converting it into a SWF and displaying it in an <code>Image</code> control. <a href="http://www.swftools.org/" rel="nofollow noreferrer">SWFTools</a> can convert animated GIF into SWF file, small enough to be embedded in your app.<br/></p>
<p>Or alternatively you could convert it into a good old animated GIF file and use this package to embed and play it back:</p> <p><a href="http://www.bytearray.org/?p=95" rel="nofollow noreferrer">http://www.bytearray.org/?p=95</a></p>
28,895
<p>I have an Excel spreadsheet containing a list of strings. Each string is made up of several words, but the number of words in each string is different.</p> <p>Using built in Excel functions (no VBA), is there a way to isolate the last word in each string?</p> <p>Examples:</p> <pre> Are you classified as human? -> human? Negative, I am a meat popsicle -> popsicle Aziz! Light! -> Light!</pre>
<p>This one is tested and does work (based on Brad's original post):</p> <pre><code>=RIGHT(A1,LEN(A1)-FIND("|",SUBSTITUTE(A1," ","|", LEN(A1)-LEN(SUBSTITUTE(A1," ",""))))) </code></pre> <p>If your original strings could contain a pipe "|" character, then replace both in the above with some other character that won't appear in your source. (I suspect Brad's original was broken because an unprintable character was removed in the translation).</p> <p>Bonus: How it works (from right to left):</p> <p><code>LEN(A1)-LEN(SUBSTITUTE(A1," ",""))</code> &ndash; Count of spaces in the original string<br> <code>SUBSTITUTE(A1," ","|", ... )</code> &ndash; Replaces just the <em>final</em> space with a <code>|</code><br> <code>FIND("|", ... )</code> &ndash; Finds the absolute position of that replaced <code>|</code> (that was the final space)<br> <code>Right(A1,LEN(A1) - ... ))</code> &ndash; Returns all characters after that <code>|</code></p> <p><strong>EDIT:</strong> to account for the case where the source text contains no spaces, add the following to the beginning of the formula:</p> <pre><code>=IF(ISERROR(FIND(" ",A1)),A1, ... ) </code></pre> <p>making the entire formula now:</p> <pre><code>=IF(ISERROR(FIND(" ",A1)),A1, RIGHT(A1,LEN(A1) - FIND("|", SUBSTITUTE(A1," ","|",LEN(A1)-LEN(SUBSTITUTE(A1," ","")))))) </code></pre> <p>Or you can use the <code>=IF(COUNTIF(A1,"* *")</code> syntax of the other version.</p> <p>When the original string might contain a space at the last position add a trim function while counting all the spaces: Making the function the following:</p> <pre><code>=IF(ISERROR(FIND(" ",B2)),B2, RIGHT(B2,LEN(B2) - FIND("|", SUBSTITUTE(B2," ","|",LEN(TRIM(B2))-LEN(SUBSTITUTE(B2," ","")))))) </code></pre>
<p>I also had a task like this and when I was done, using the above method, a new method occured to me: Why don't you do this:</p> <ol> <li>Reverse the string ("string one" becomes "eno gnirts").</li> <li>Use the good old Find (which is hardcoded for left-to-right).</li> <li>Reverse it into readable string again.</li> </ol> <p>How does this sound?</p>
45,586
<p>I'm looking for a library or source code that provides guard methods such as checking for null arguments. Obviously this is rather simple to build, but I'm wondering if there are any out there for .NET already. A basic Google search didn't reveal much.</p>
<p>There is <a href="http://conditions.codeplex.com/" rel="noreferrer">CuttingEdge.Conditions</a>. Usage example from the page:</p> <pre><code>public ICollection GetData(Nullable&lt;int&gt; id, string xml, ICollection col) { // Check all preconditions: id.Requires("id") .IsNotNull() // throws ArgumentNullException on failure .IsInRange(1, 999) // ArgumentOutOfRangeException on failure .IsNotEqualTo(128); // throws ArgumentException on failure xml.Requires("xml") .StartsWith("&lt;data&gt;") // throws ArgumentException on failure .EndsWith("&lt;/data&gt;"); // throws ArgumentException on failure col.Requires("col") .IsNotNull() // throws ArgumentNullException on failure .IsEmpty(); // throws ArgumentException on failure // Do some work // Example: Call a method that should not return null object result = BuildResults(xml, col); // Check all postconditions: result.Ensures("result") .IsOfType(typeof(ICollection)); // throws PostconditionException on failure return (ICollection)result; } </code></pre> <p>Another nice approach, which isn't packaged in a library, but could easily be, <a href="http://blog.getpaint.net/2008/12/06/a-fluent-approach-to-c-parameter-validation/" rel="noreferrer">on Paint.Net blog</a>:</p> <pre><code>public static void Copy&lt;T&gt;(T[] dst, long dstOffset, T[] src, long srcOffset, long length) { Validate.Begin() .IsNotNull(dst, "dst") .IsNotNull(src, "src") .Check() .IsPositive(length) .IsIndexInRange(dst, dstOffset, "dstOffset") .IsIndexInRange(dst, dstOffset + length, "dstOffset + length") .IsIndexInRange(src, srcOffset, "srcOffset") .IsIndexInRange(src, srcOffset + length, "srcOffset + length") .Check(); for (int di = dstOffset; di &lt; dstOffset + length; ++di) dst[di] = src[di - dstOffset + srcOffset]; } </code></pre> <p>I use it in <a href="http://code.google.com/p/functional-dotnet/" rel="noreferrer">my project</a> and you could borrow the code from there.</p>
<p>Install the netfx-guard nuget package. You get also code snippets notnull and notempty, and it performs as fast as your manual checks</p>
38,360
<p>This is obviously a stupid question. I am coding in Eclipse both on Mac and Linux, but I mixed up and used the Mac shortcut to window tabbing (<kbd>Ctrl</kbd>-<kbd>Cmd</kbd>-<kbd>F6</kbd>), but I was using the Linux on uni and screen went black. I've done this before, but this time I can't get back to my desktop. <kbd>Ctrl</kbd>-<kbd>Alt</kbd> <kbd>F1</kbd>-<kbd>F6</kbd> gives me different terminals, <kbd>F7</kbd> gives me a black screen and <kbd>F8</kbd> a blinking underscore in the top left corner. Shouldn't my session have been somewhere in <kbd>F1</kbd>-<kbd>F6</kbd> and is it lost? </p>
<p>X is probably still running on <kbd>F7</kbd>, your display driver (or something else) is just misbehaving. You might be able to trick it into coming back on by going to <kbd>F7</kbd> and blindly opening a terminal and playing with xset ($ <em>xset dpms force on</em>). Or you can <kbd>ctrl</kbd>-<kbd>alt</kbd>-<kbd>backspace</kbd> to kill X and GDM should restart it.</p> <p>Try seeing if you can repeat the problem and then file a bug report (or let the lab admin know if it isn't your computer). It probably has something to do with your distro's kernel configuration/patching. I've had this happen before on Ubuntu but not any other distros (I've used many), which is why I am assuming it might be distro-specific issue. Probably the unintended consequences of some kernel patching.</p>
<p>We're running gnome on Red Hat 5. ps axu in one of the other terminals showed some of the processes still running. Probably something with the display drivers then. Did <kbd>ctrl</kbd>-<kbd>alt</kbd>-<kbd>backspace</kbd> and restarted it. Thanks for the help.</p>
14,632
<p>What is the best way to transparently rewrite a URL over an SSL connection with Apache 2.2?</p> <p>Apache 2 does not natively support multiple name-based virtual hosts for an SSL connection and I have heard that mod_rewrite can help with this. I would like to do something like this:</p> <p>I have set up the server so that the sites can be accessed by</p> <p><a href="https://secure.example.com/dbadmin" rel="nofollow noreferrer">https://secure.example.com/dbadmin</a></p> <p>but I would like to have this as <a href="https://dbadmin.example.com" rel="nofollow noreferrer">https://dbadmin.example.com</a></p> <p>How do I set it up so that the Rewrite rule will rewrite dbadmin.example.com to secure.example.com/dbadmin, but without displaying the rewrite on the client's address bar (i.e. the client will still just see dbadmin.example.com), all over https?</p>
<p>Configure a single VirtualHost to serve both secure.example.com and dbadmin.example.com (making it the only *:443 VirtualHost achieves this). You can then use <a href="http://httpd.apache.org/docs/2.2/mod/mod_rewrite.html" rel="nofollow noreferrer">mod_rewrite</a> to adjust the URI for requests to dbadmin.example.com:</p> <pre><code>&lt;VirtualHost *:443&gt; ServerName secure.example.com ServerAlias dbadmin.example.com RewriteEngine on RewriteCond %{SERVER_NAME} dbadmin.example.com RewriteRule !/dbadmin(.*)$ /dbadmin$1 &lt;/VirtualHost&gt; </code></pre> <p>Your SSL certificate will need to be valid for both secure.example.com and dbadmin.example.com. It can be a wildcard certificate as mentioned by Terry Lorber, or you can use the <a href="http://wiki.cacert.org/wiki/VhostTaskForce#A1.Way.3ASubjectAltNameOnly" rel="nofollow noreferrer">subjectAltName</a> field to add additional host names.</p> <p>If you're having trouble, first set it up on <code>&lt;VirtualHost *&gt;</code> and check that it works without SSL. The SSL connection and certificate is a separate layer of complexity that you can set up after the URI rewriting is working.</p>
<p>There is apaches mod_rewrite, or you could setup apache to direct <a href="https://dbadmin.example.com" rel="nofollow noreferrer">https://dbadmin.example.com</a> to path/to/example.com/dbadmin on the server</p> <pre><code>&lt;VirtualHost *&gt; ServerName subdomain.domain.com DocumentRoot /home/httpd/htdocs/subdomain/ &lt;/VirtualHost&gt; </code></pre>
2,979
<p>I was wondering if there was an alternative to <code>itoa()</code> for converting an integer to a string because when I run it in visual Studio I get warnings, and when I try to build my program under Linux, I get a compilation error.</p>
<p>In C++11 you can use <a href="http://en.cppreference.com/w/cpp/string/basic_string/to_string" rel="noreferrer"><code>std::to_string</code></a>:</p> <pre><code>#include &lt;string&gt; std::string s = std::to_string(5); </code></pre> <p>If you're working with prior to C++11, you could use C++ streams:</p> <pre><code>#include &lt;sstream&gt; int i = 5; std::string s; std::stringstream out; out &lt;&lt; i; s = out.str(); </code></pre> <p>Taken from <a href="http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/" rel="noreferrer">http://notfaq.wordpress.com/2006/08/30/c-convert-int-to-string/</a></p>
<p>Most of the above suggestions technically aren't C++, they're C solutions.</p> <p>Look into the use of <a href="http://www.cplusplus.com/reference/iostream/stringstream/" rel="nofollow noreferrer">std::stringstream</a>.</p>
28,220
<p>I find this very strange, must be something I'm doing wrong, but still... I'm working on a page using PHP and TPL files. In my TPL file, there's a place in the footer for some extra lines if needed.</p> <p>For instance, formchecking with Javascript.</p> <p>so in PHP I did this:</p> <pre><code>$foot = "&lt;script type=\"text/javascript\"&gt;if(document.getElementById){loadEvents();}&lt;/script&gt;"; </code></pre> <p>the $foot variable is then parsed and the result in HTML is this:</p> <pre><code>&lt;script type="text/javascript"&gt;if(document.getElementById)&lt;/script&gt; </code></pre> <p>So <code>{loadEvents();}</code> went missing.</p> <p>Does anybody see what I'm missing here... I'm seriously not finding it. Did I forget to escape a character or something?</p>
<p>Obviously the <a href="http://www.smarty.net/" rel="nofollow noreferrer">template engine you are using</a> eats away the part in curly braces.</p> <p>Try something like:</p> <pre><code>$foot = "{literal}&lt;script type=\"text/javascript\"&gt;if(document.getElementById){loadEvents();}&lt;/script&gt;{/literal}"; </code></pre>
<p>I believe with {} that PHP is expecting a variable within them. I haven't tested this, but try using single quote instead of double-quotes.</p>
42,884
<p>This one has me scratching my head.</p> <p>I'm running Subversion 1.3.1 (r19032) on Ubuntu. All was well until recently when I tried to run svnadmin verify prior to a dump. This is the error message:</p> <blockquote> <p>svnadmin: Invalid diff stream: insn 0 cannot be decoded</p> </blockquote> <p>I have looked around for an explanation and fix but can't seem to find one. Subversion experts, I need your help.</p>
<p>You should ensure that you are using the correct version of <code>svnadmin</code> for your repository version. It's possible to get errors like this by using the wrong version.</p> <p>Having said that, version 1.3.x is pretty old now and you should consider upgrading to the latest 1.5.x.</p> <p>I also found through google that <a href="http://www.nabble.com/Re:-svn:-Invalid-diff-stream:-insn-0-cannot-be-decoded-p17756765.html" rel="nofollow noreferrer">some versions of SVNKit</a> can cause this problem.</p>
<p>You should ensure that you are using the correct version of <code>svnadmin</code> for your repository version. It's possible to get errors like this by using the wrong version.</p> <p>Having said that, version 1.3.x is pretty old now and you should consider upgrading to the latest 1.5.x.</p> <p>I also found through google that <a href="http://www.nabble.com/Re:-svn:-Invalid-diff-stream:-insn-0-cannot-be-decoded-p17756765.html" rel="nofollow noreferrer">some versions of SVNKit</a> can cause this problem.</p>
30,427
<p>I have a <a href="http://www.luminarymicro.com/products/rdk-idm.html" rel="nofollow noreferrer">RDK-IDM</a> from <a href="http://www.luminarymicro.com/" rel="nofollow noreferrer">Luminary Micro</a>. This board has a 32-bit ARM® <a href="http://www.arm.com/products/CPUs/ARM_Cortex-M3.html" rel="nofollow noreferrer">Cortex™-M3 core</a>. Has anybody tried to run a .NET Micro Framework application on such a device?</p>
<p>I don't have any hands on experience but based on <a href="http://www.microsoft.com/netmf/about/gettingstarted.mspx" rel="noreferrer">http://www.microsoft.com/netmf/about/gettingstarted.mspx</a> The smallest footprint supported is 64kb RAM, 256kb Flash and MMU is not required. Therefore your applications needs would be the determining factor.</p> <p>FYI: the .NET Micro Framework was released as Open Source under the Apache 2.0 License November 16, 2009</p>
<p>The cortex M3 is a very cut-down core, it lacks an MMU, for example, and is intended to run very simple operating systems. Specifically, not Symbian/Windows Mobile/Linux/etc. Rather OSEck, OSEK, iTRON, or similar. I think this is actually totally infeasible due to that.</p>
18,328
<p>I've been using git for some time now on Windows (with msysGit) and I like the idea of distributed source control. Just recently I've been looking at Mercurial (hg) and it looks interesting. However, I can't wrap my head around the differences between hg and git.</p> <p>Has anyone made a side-by-side comparison between git and hg? I'm interested to know what differs hg and git without having to jump into a fanboy discussion.</p>
<p>These articles may help:</p> <ul> <li><a href="http://importantshock.wordpress.com/2008/08/07/git-vs-mercurial/" rel="noreferrer">Git vs. Mercurial: Please Relax</a> (Git is MacGyver and Mercurial is James Bond)</li> <li><a href="http://www.rockstarprogrammer.org/post/2008/apr/06/differences-between-mercurial-and-git/" rel="noreferrer">The Differences Between Mercurial and Git</a></li> </ul> <p><strong>Edit</strong>: Comparing Git and Mercurial to celebrities seems to be a trend. Here's one more:</p> <ul> <li><a href="http://www.ericsink.com/entries/hg_denzel.html" rel="noreferrer">Git is Wesley Snipes, Mercurial is Denzel Washington</a></li> </ul>
<p>This link may help you to understand the difference <a href="http://www.techtatva.com/2010/09/git-mercurial-and-bazaar-a-comparison/" rel="nofollow">http://www.techtatva.com/2010/09/git-mercurial-and-bazaar-a-comparison/</a></p>
5,641
<p>When adding a reference to a project I sometimes see the message...</p> <p>"The Target Framework version for the project is higher than the current project Target Framework version. Would you like to add this reference to your project anyway?"</p> <p>I understand what the message is indicating but can anyone explain what issues might arise from saying 'Yes'?</p>
<p>Suppose you build an application where the exe targets 2.0, but some library targets 3.5. Someone with a .NET 2.0 machine looks at the main project and thinks they can run it - after all, the application targets 2.0, right? When the library is first loaded, they'll get a nasty surprise...</p>
<p>Actually, this is perfectly fine. VS is just making you aware. Just make sure you copy the necessary references to your project and reference them. If the project you are referencing is one that you have control over you can put the references in there.</p> <p>For instance, we have an older Windows 2000 server that cannot run .Net 3.5. So, when we want to take advantage of things like LINQ we builg that into a separate project that targets 3.5. We then reference that project from our web app, which targets 2.0. We get the message you talked about but we just make sure the System.core and Link.Data DLLs are copied to the bin folder and referenced. Then there is no issue. Works like a charm.</p>
27,377
<p>New school datastore paradigms like Google BigTable and Amazon SimpleDB are specifically designed for scalability, among other things. Basically, disallowing joins and denormalization are the ways this is being accomplished.</p> <p>In <a href="https://stackoverflow.com/questions/173726/why-are-database-joins-expensive">this</a> topic, however, the consensus seems to be that joins on large tables don't necessarilly have to be too expensive and denormalization is "overrated" to some extent Why, then, do these aforementioned systems disallow joins and force everything together in a single table to achieve scalability? Is it the sheer volumes of data that needs to be stored in these systems (many terabytes)?<br> Do the general rules for databases simply not apply to these scales? Is it because these database types are tailored specifically towards storing many similar objects?<br> Or am I missing some bigger picture?</p>
<p>Distributed databases aren't quite as naive as Orion implies; there has been quite a bit of work done on optimizing fully relational queries over distributed datasets. You may want to look at what companies like Teradata, Netezza, Greenplum, Vertica, AsterData, etc are doing. (Oracle got in the game, finally, as well, with their recent announcement; Microsoft bought their solition in the name of the company that used to be called DataAllegro).</p> <p>That being said, when the data scales up into terabytes, these issues become very non-trivial. If you don't need the strict transactionality and consistency guarantees you can get from RDBMs, it is often far easier to denormalize and not do joins. Especially if you don't need to cross-reference much. Especially if you are not doing ad-hoc analysis, but require programmatic access with arbitrary transformations.</p> <p>Denormalization is overrated. Just because that's what happens when you are dealing with a 100 Tera, doesn't mean this fact should be used by every developer who never bothered to learn about databases and has trouble querying a million or two rows due to poor schema planning and query optimization.</p> <p>But if you are in the 100 Tera range, by all means...</p> <p>Oh, the other reason these technologies are getting the buzz -- folks are discovering that some things never belonged in the database in the first place, and are realizing that they aren't dealing with relations in their particular fields, but with basic key-value pairs. For things that shouldn't have been in a DB, it's entirely possible that the Map-Reduce framework, or some persistent, eventually-consistent storage system, is just the thing.</p> <p>On a less global scale, I highly recommend BerkeleyDB for those sorts of problems. </p>
<p>Novaday You need to find more interoperational environment for databases. More frequently You don't need only an relational DBs, like MySQL or MS SQL but also Big Data farms as Hadoop or non-relational DBs like MongoDB. In some cases all those DBs will be used in one solution so their performance must be as equal as possible in macro scale. It means, that You will not be able to use let say Azure SQL as relational DB and one VM with 2 cores and 3GB of RAM for MongoDB. You must scale-up Your solution and use DB as a Service when it is possible (if it is not possible, then build Your own cluster in a cloud).</p>
21,218
<p>I'm trying to get started on what I'm hoping will be a relatively quick web application in Java, yet most of the frameworks I've tried (Apache Wicket, Liftweb) require so much set-up, configuration, and trying to wrap my head around Maven while getting the whole thing to play nice with Eclipse, that I spent the whole weekend just trying to get to the point where I write my first line of code!</p> <p>Can anyone recommend a simple Java webapp framework that doesn't involve Maven, hideously complicated directory structures, or countless XML files that must be manually edited?</p>
<p>Haven't tried it myself, but I think</p> <p><a href="http://www.playframework.org/" rel="noreferrer">http://www.playframework.org/</a></p> <p>has a lot of potential...</p> <p>coming from php and classic asp, it's the first java web framework that sounds promising to me....</p> <p><em>Edit by original question asker - 2011-06-09</em></p> <p>Just wanted to provide an update.</p> <p>I went with Play and it was exactly what I asked for. It requires very little configuration, and just works out of the box. It is unusual in that it eschews some common Java best-practices in favor of keeping things as simple as possible. </p> <p>In particular, it makes heavy use of static methods, and even does some introspection on the names of variables passed to methods, something not supported by the Java reflection API.</p> <p>Play's attitude is that its first goal is being a useful web framework, and sticking to common Java best-practices and idioms is secondary to that. This approach makes sense to me, but Java purists may not like it, and would be better-off with <a href="http://wicket.apache.org/" rel="noreferrer">Apache Wicket</a>.</p> <p>In summary, if you want to build a web-app with convenience and simplicity comparable to a framework like Ruby on Rails, but in Java and with the benefit of Java's tooling (eg. Eclipse), then Play Framework is a great choice.</p>
<p>Have you tried DWR? <a href="http://directwebremoting.org" rel="nofollow noreferrer">http://directwebremoting.org</a></p>
14,253
<p>Is there a performance hit if we use a loop instead of recursion or vice versa in algorithms where both can serve the same purpose? Eg: Check if the given string is a palindrome. I have seen many programmers using recursion as a means to show off when a simple iteration algorithm can fit the bill. Does the compiler play a vital role in deciding what to use?</p>
<p>It is possible that recursion will be more expensive, depending on if the recursive function is <a href="http://en.wikipedia.org/wiki/Tail_recursion" rel="noreferrer">tail recursive</a> (the last line is recursive call). Tail recursion <em>should</em> be recognized by the compiler and optimized to its iterative counterpart (while maintaining the concise, clear implementation you have in your code).</p> <p>I would write the algorithm in the way that makes the most sense and is the clearest for the poor sucker (be it yourself or someone else) that has to maintain the code in a few months or years. If you run into performance issues, then profile your code, and then and only then look into optimizing by moving over to an iterative implementation. You may want to look into <a href="http://en.wikipedia.org/wiki/Memoization" rel="noreferrer">memoization</a> and <a href="http://en.wikipedia.org/wiki/Dynamic_programming" rel="noreferrer">dynamic programming</a>.</p>
<p>I'm going to answer your question by designing a Haskell data structure by "induction", which is a sort of "dual" to recursion. And then I will show how this duality leads to nice things.</p> <p>We introduce a type for a simple tree:</p> <pre><code>data Tree a = Branch (Tree a) (Tree a) | Leaf a deriving (Eq) </code></pre> <p>We can read this definition as saying "A tree is a Branch (which contains two trees) or is a leaf (which contains a data value)". So the leaf is a sort of minimal case. If a tree isn't a leaf, then it must be a compound tree containing two trees. These are the only cases.</p> <p>Let's make a tree:</p> <pre><code>example :: Tree Int example = Branch (Leaf 1) (Branch (Leaf 2) (Leaf 3)) </code></pre> <p>Now, let's suppose we want to add 1 to each value in the tree. We can do this by calling:</p> <pre><code>addOne :: Tree Int -&gt; Tree Int addOne (Branch a b) = Branch (addOne a) (addOne b) addOne (Leaf a) = Leaf (a + 1) </code></pre> <p>First, notice that this is in fact a recursive definition. It takes the data constructors Branch and Leaf as cases (and since Leaf is minimal and these are the only possible cases), we are sure that the function will terminate.</p> <p>What would it take to write addOne in an iterative style? What will looping into an arbitrary number of branches look like?</p> <p>Also, this kind of recursion can often be factored out, in terms of a "functor". We can make Trees into Functors by defining:</p> <pre><code>instance Functor Tree where fmap f (Leaf a) = Leaf (f a) fmap f (Branch a b) = Branch (fmap f a) (fmap f b) </code></pre> <p>and defining:</p> <pre><code>addOne' = fmap (+1) </code></pre> <p>We can factor out other recursion schemes, such as the catamorphism (or fold) for an algebraic data type. Using a catamorphism, we can write:</p> <pre><code>addOne'' = cata go where go (Leaf a) = Leaf (a + 1) go (Branch a b) = Branch a b </code></pre>
9,783
<p>If I don't know the length of a text entry (e.g. a blog post, description or other long text), what's the best way to store it in MYSQL?</p>
<p>TEXT would be the most appropriate for unknown size text. VARCHAR is limited to 65,535 characters from MYSQL 5.0.3 and 255 chararcters in previous versions, so if you can safely assume it will fit there it will be a better choice.</p> <p>BLOB is for binary data, so unless you expect your text to be in binary format it is the least suitable column type.</p> <p>For more information refer to the Mysql documentation on <a href="http://dev.mysql.com/doc/refman/5.0/en/string-types.html" rel="noreferrer">string column types</a>.</p>
<p>use TEXT if you want it treated as a character string, with a character set.<br> use BLOB if you want it treated as a binary string, without a character set.</p> <p>I recommend using TEXT.</p>
18,154
<p>Its the weekend again, and that means I get to play with my <a href="https://stackoverflow.com/questions/332585/2d-platformer-physics">hobby project</a>.</p> <p>I've gotten tired of creating test levels by hand, so I thought I'd take a break from engine development and work on a level editor:</p> <p><a href="http://gfilter.net/junk/Editor.JPG" rel="nofollow noreferrer">Level Editor http://gfilter.net/junk/Editor.JPG</a></p> <p>I'd like to implement a flood fill algorithm in the editor, which would work just like in a paint program. Does anyone have any pointers on what technique would work good for me here?</p> <p>The level is just a 2d array, so it could be considered the same as a bitmap really.</p> <p>Thanks!</p>
<p><a href="http://en.wikipedia.org/wiki/Flood_fill" rel="nofollow noreferrer">general reference</a></p> <p><a href="http://www.codeproject.com/KB/GDI-plus/queuelinearfloodfill.aspx" rel="nofollow noreferrer">optimized algorithm in C#</a></p>
<p>Here is example how to use GDI+ routines in C# program.</p> <p>( <a href="https://www.pinvoke.net/default.aspx/gdi32.extfloodfill" rel="nofollow noreferrer">https://www.pinvoke.net/default.aspx/gdi32.extfloodfill</a> )</p> <pre><code>using System.Runtime.InteropServices; //insert by Zswang(wjhu111#21cn.com) at 2007-05-22 [DllImport("gdi32.dll")] public static extern IntPtr SelectObject(IntPtr hdc, IntPtr hgdiobj); [DllImport("gdi32.dll")] public static extern IntPtr CreateSolidBrush(int crColor); [DllImport("gdi32.dll")] public static extern bool ExtFloodFill(IntPtr hdc, int nXStart, int nYStart, int crColor, uint fuFillType); [DllImport("gdi32.dll")] public static extern bool DeleteObject(IntPtr hObject); [DllImport("gdi32.dll")] public static extern int GetPixel(IntPtr hdc, int x, int y); public static uint FLOODFILLBORDER = 0; public static uint FLOODFILLSURFACE = 1; private void button1_Click(object sender, EventArgs e) { Graphics vGraphics = Graphics.FromHwnd(Handle); vGraphics.DrawRectangle(Pens.Blue, new Rectangle(0, 0, 300, 300)); vGraphics.DrawRectangle(Pens.Blue, new Rectangle(50, 70, 300, 300)); IntPtr vDC = vGraphics.GetHdc(); IntPtr vBrush = CreateSolidBrush(ColorTranslator.ToWin32(Color.Red)); IntPtr vPreviouseBrush = SelectObject(vDC, vBrush); ExtFloodFill(vDC, 10, 10, GetPixel(vDC, 10, 10), FLOODFILLSURFACE); SelectObject(vDC, vPreviouseBrush); DeleteObject(vBrush); vGraphics.ReleaseHdc(vDC); } </code></pre> <p>Instead of using <code>Graphics vGraphics = Graphics.FromHwnd(Handle);</code> , if you are calling this in OnPaint event handler, you may use <code>e.Graphics</code> . Worked for me quite well. </p> <p>Sometimes its better not to reinvent algorithm and use existing routines, although you may get some problems with this when porting to Mono.</p>
47,934
<p>I am trying to 3D print an iPhone case, however, I want it to print standing up. Is this possible to do?</p> <p>I have a picture of the case in the link below.<a href="https://i.stack.imgur.com/dUYr0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dUYr0.png" alt="iphone case"></a></p>
<p>Yes this is possible. For an FDM/FFF printer, you'll need to print with supports. I might also recommend printing in PLA to minimize the chance of warping during the print (from experience).</p> <p>It might also help to slow down the feedrate to ensure smooth surface finish and avoiding delamination on such small layers.</p> <p>You'll probably see a decrease in the surface quality on the inside due to the printing of support scaffolding depending on the slicing engine you use.</p> <h1>However</h1> <p>You'll want to pay attention to the strength of the case. If you print the case upright then it will be more susceptible to breaking without post-processing.</p> <h1>Conclusion</h1> <p>Ultimately, if you can get away with it, it would be better to subtract the star instead of extruding it in the model. Then you can simply print the case back face down on the plate with much better results.</p>
<p>You have a few options. First. I would change the design. Why not make it negative space instead? Else as the other user mentioned, glue the star on later.</p> <p>Other options are, come up with a modular design so you do not print it as one piece. </p> <p>From there you can do some more advanced things such as print it with the star up and use HIPS as a support material -- assuming you have a duel extruder</p> <p><a href="http://reprap.org/wiki/HIPS" rel="nofollow">http://reprap.org/wiki/HIPS</a></p> <p>You could print it with normal support material, with the star up, and just accept that the left overs will scratch the phone, or spend a lot of time with some hand tools and sand paper.</p>
348
<p>...instead of using the Atom syndication format?</p> <p>Atom is a <a href="http://www.atomenabled.org/developers/syndication/" rel="noreferrer">well-defined</a>, general-purpose XML syndication format. RSS is fractured into four different versions. All the major feed readers have supported Atom for as long as I can remember, so why isn't its use more prevalent?</p> <p>Worst of all are sites that provide feeds in both formats - what's the point?!</p> <ul> <li>UPDATE (18 August): Interestingly, this site itself is using Atom for its feeds rather than RSS.</li> </ul>
<p>The fundamental thing that the Atom creators didn't understand (and that the Atom supporters still don't understand), is that Atom isn't somehow separate from RSS. There's this idea that RSS fractured, and that somehow Atom fixes that problem. But it doesn't. Atom is just another RSS splinter. A new name doesn't change the fact that it's just one more standard competing to do the same job, a job for which <em>any</em> of the competing standards are sufficient.</p> <p>No one outside a fairly small group of people care at all which standard is used. They just want it to work. Atom, RSS 2.0, RSS 1.0, RSS 401(k), whatever. As long as it works, the users are happy. The RSS "brand" very much defines the entire feed category, though, so on the rare occasion that someone <em>does</em> know enough to choose, they will tend to choose RSS, because it's got "the name." They will also tend to choose RSS 2.0, because it's got the bigger number.</p> <p>RSS, and especially RSS 2.0, are very much entrenched in the feed "industry." Atom hasn't taken off because it doesn't bring much except a new name. Why switch away from RSS when it works just fine? And why even bother using Atom on new projects if RSS is sufficient? Switching to a new feed format mostly means extra time spent learning the new format.</p> <p>If nothing else <a href="http://www.apple.com/itunes/store/podcaststechspecs.html" rel="noreferrer">Apple's exclusive use of RSS 2.0 for podcasts</a> means that RSS 2.0 is here for the foreseeable future.</p>
<p>There are a lot of RSS feed readers out there that people are used to using, and most importantly, RSS is very well known and has been around much longer. Why mess with something if it works?</p>
3,353
<p>I am migrating a 1.1 winforms app to 2.0. what are the main things i should immediately change because of generics. Here what i have so far:</p> <ol> <li>Replace all hashtables with generic dictionaries</li> <li>Replace all arraylists with List&lt;></li> <li>Replace all CollectionBase derive classes with : List&lt;></li> </ol> <p>Any others that should be done immediately?</p> <p>thks, ak</p>
<blockquote> <p>Any others that should be done immediately?</p> </blockquote> <p>Generally, change any mention of <code>IEnumerable</code> to <code>IEnumerable&lt;T&gt;</code>, where possible. Migration can be greatly helped by switching the whole namespace, i.e. un-<code>import</code>ing <code>System.Collections</code> in every file and instead importing <code>System.Collections.Generic</code>.</p> <p>Also, search for mentions of <code>object</code> and/or usage of boxing in your code and consider whether this is still appropriate or should be replaced by generics.</p> <p>As <strong>jalf</strong> reminded me in the comments, another important change is the switch to the generic version of <code>IComparable</code> where applicable.</p>
<p>I wouldn't recommend using <code>List&lt;T&gt;</code> instead of <code>CollectionBase</code>. Instead, <code>Collection&lt;T&gt;</code> gives you comparable overrides.</p>
42,466
<p>I have developed a build system on MSBuild (NET 3.0) and cc.net to perform continuous integration builds of a Visual Studio 2008 application, however a developer on the team recently added a VSTS unit test project to the mix. Is there any SDK or add-in provided by microsoft to allow this to be compiled on a non-team system build environment?</p>
<p>You can run the tests from the command-line, but it requires that the Test Edition of Visual Studio be installed on your build server:</p> <p><a href="http://devlicio.us/blogs/derik_whittaker/archive/2008/09/25/clean-build-server-with-mstest-fail.aspx" rel="nofollow noreferrer"><a href="http://devlicio.us/blogs/derik_whittaker/archive/2008/09/25/clean-build-server-with-mstest-fail.aspx" rel="nofollow noreferrer">http://devlicio.us/blogs/derik_whittaker/archive/2008/09/25/clean-build-server-with-mstest-fail.aspx</a></a></p> <p><a href="http://aspadvice.com/blogs/ssmith/archive/2008/03/18/Continuous-Integration-Setup-with-MSTest.aspx" rel="nofollow noreferrer"><a href="http://aspadvice.com/blogs/ssmith/archive/2008/03/18/Continuous-Integration-Setup-with-MSTest.aspx" rel="nofollow noreferrer">http://aspadvice.com/blogs/ssmith/archive/2008/03/18/Continuous-Integration-Setup-with-MSTest.aspx</a></a></p> <p>This person is doing MSTest with CC.NET, so it might be helpful:</p> <p><a href="http://testearly.findtechblogs.com/default.asp?item=630602" rel="nofollow noreferrer"><a href="http://testearly.findtechblogs.com/default.asp?item=630602" rel="nofollow noreferrer">http://testearly.findtechblogs.com/default.asp?item=630602</a></a></p> <p>In general, this is a main reason why many people choose something like <a href="http://www.nunit.org" rel="nofollow noreferrer">NUnit</a>, <a href="http://www.codeplex.com/xunit" rel="nofollow noreferrer">xUnit.NET</a> or <a href="http://www.mbunit.com/" rel="nofollow noreferrer">MbUnit</a> over MSTest.</p>
<p>If you use MSTEST You will have to put that edition on the build server. To cut a long story short youd be better off changing the testing framework the developer is using from MStest to Nunit. Its a much lighter solution.</p>
49,560
<p>I have taken over a large code base and would like to get an overview how and where certain classes and their methods are used.</p> <p>Is there any good tool that can somehow visualize the dependencies and draw a nice call tree or something similar?</p> <p>The code is in C++ in Visual Studio if that helps narrow down any selection.</p>
<p>Here are a few options:</p> <ul> <li><a href="http://www.codedrawer.com/index.html" rel="nofollow noreferrer">CodeDrawer</a></li> <li><a href="http://www.westernwares.com/" rel="nofollow noreferrer">CC-RIDER</a></li> <li><a href="http://www.doxygen.nl/index.html" rel="nofollow noreferrer">Doxygen</a></li> </ul> <p>The last one, doxygen, is more of an automatic documentation tool, but it is capable of generating dependency graphs and inheritance diagrams. It's also licensed under the GPL, unlike the first two which are not free.</p>
<p>In Java I would start with JDepend. In .NET, with NDepend. Don't know about C++.</p>
5,630
<p>Is there a distributed version control system (like git or Mercurial) that can be used as an embedded library in Java applications (to implement versioned and synchronizable storage for application data), ideally written in pure Java and under a permissive license?</p>
<p>I do not know of any pure Java solutions. But, check out <a href="http://javagit.sourceforge.net/" rel="nofollow noreferrer">http://javagit.sourceforge.net/</a> you can use it to connect to a git repository with Java.</p>
<p>There is a pure Java library, <a href="http://svnkit.com/" rel="nofollow noreferrer">SVN Kit</a> for interacting with <strong>Subversion</strong></p>
21,378
<p>Say I've got a class like this:</p> <pre><code>class Test { int x; SomeClass s; } </code></pre> <p>And I instantiate it like this:</p> <pre><code>Test* t = new Test; </code></pre> <p>Is x on the stack, or the heap? What about s?</p>
<pre><code>Test a; Test *t = new Test; </code></pre> <p>a, and all its members, are on the stack.</p> <p>The object pointed to by t, and all its members, are on the heap.</p> <p>The pointer t is on the stack.</p>
<p>Since you're using new, you're allocating your object on the heap. Consequently, every members of the Test pointed by t are on the heap too.</p>
22,756
<p>I am still having problems with figuring out how to create winforms in a separate UI thread that I discussed <a href="https://stackoverflow.com/questions/164789/winforms-implementation-question-for-having-my-ui-run-independently-of-my-bll-l">here</a>.</p> <p>In trying to figure this out I wrote the following simple test program. I simply want it to open a form on a separate thread named "UI thread" and keep the thread running as long as the form is open while allowing the user to interact with the form (spinning is cheating). I understand why the below fails and the thread closes immediately but am not sure of what I should do to fix it.</p> <pre><code>using System; using System.Windows.Forms; using System.Threading; namespace UIThreadMarshalling { static class Program { [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); var tt = new ThreadTest(); ThreadStart ts = new ThreadStart(tt.StartUiThread); Thread t = new Thread(ts); t.Name = "UI Thread"; t.Start(); Thread.Sleep(new TimeSpan(0, 0, 10)); } } public class ThreadTest { Form _form; public ThreadTest() { } public void StartUiThread() { _form = new Form1(); _form.Show(); } } } </code></pre>
<p>On a new thread, call Application.Run passing the form object, this will make the thread run its own message loop while the window is open.</p> <p>Then you can call .Join on that thread to make your main thread wait until the UI thread has terminated, or use a similar trick to wait for that thread to complete.</p> <p>Example:</p> <pre><code>public void StartUiThread() { using (Form1 _form = new Form1()) { Application.Run(_form); } } </code></pre>
<p>I think just calling ShowDialog instead of Show will help. The problem seems to be that the thread finishes just after calling Show, after that the Form get's garbage collected. ShowDialog will halt the thread but still run form-events on it so the thread will keep running until the form is closed.</p> <p>Normally i would do it the other way around. Run the form on the starting thread and start background threads when you want to start long-running background tasks.</p> <p>I also read your other question but couldn't figure out what you're trying to do. MVP-architecture doesn't require you to run your business logic on different threads. Multi threading is hard to do right so I'd only use multiple threads if I really needed them.</p>
20,208
<p>It seems that the decision to make your objects fully cognizant of their roles within the system, and still avoid having too many dependencies within the domain model on the database, and service layers?</p> <p>For example: Say that I've got an entity with a revision history, and several "lookup tables" that the data references, your entity object should have methods to get the details from some of the lookup tables, whether by providing access to the lookup table rows, or by delegating methods down to them, but in order to do so it depends on the database layer to read the data from those rows. Also, when the entity is saved, It needs to know not only how to save itself, but also to save entries into the revision history. Is it necessary to pass references to dozens of different data layer objects and service objects to the model object? This seems like it makes the logic far more complex to understand than just passing back and forth thin models to service layer objects, but I've heard many "wise men" recommending this sort of structure.</p>
<p>Really really good question. I have spent quite a bit of time thinking about such topics.</p> <p>You demonstrate great insight by noting the tension between an expressive domain model and separation of concerns. This is much like the tension in the question I asked about <a href="https://stackoverflow.com/questions/169450/arent-information-expert-tell-dont-ask-at-odds-with-single-responsibility-princ">Tell Don't Ask and Single Responsibility Principle</a>.</p> <p>Here is my view on the topic.</p> <p>A domain model is anemic because it contains no domain logic. Other objects get and set data using an anemic domain object. What you describe doesn't sound like domain logic to me. It might be, but generally, look-up tables and other technical language is most likely terms that mean something to us but not necessarily anything to the customers. If this is incorrect, please clarify.</p> <p>Anyway, the construction and persistence of domain objects shouldn't be contained in the domain objects themselves because that isn't domain logic.</p> <p>So to answer the question, no, you shouldn't inject a whole bunch of non-domain objects/concepts like lookup tables and other infrastructure details. This is a leak of one concern into another. The Factory and Repository patterns from Domain-Driven Design are best suited to keep these concerns apart from the domain model itself.</p> <p>But note that if you don't have any domain logic, then you will end up with anemic domain objects, i.e. bags of brainless getters and setters, which is how <a href="http://moffdub.wordpress.com/2008/09/03/soa-is-not-an-excuse-to-write-procedural-java/" rel="nofollow noreferrer">some shops claim to do SOA / service layers</a>. </p> <p>So how do you get the best of both worlds? How do you focus your domain objects only domain logic, while keeping UI, construction, persistence, etc. out of the way? I recommend you use a technique like <a href="http://www.c2.com/cgi/wiki?DoubleDispatchExample" rel="nofollow noreferrer">Double Dispatch</a>, or some form of <a href="http://moffdub.wordpress.com/restricted-method-access/" rel="nofollow noreferrer">restricted method access</a>.</p> <p>Here's an example of Double Dispatch. Say you have this line of code:</p> <pre><code>entity.saveIn(repository); </code></pre> <p>In your question, saveIn() would have all sorts of knowledge about the data layer. Using Double Dispatch, saveIn() does this:</p> <pre><code>repository.saveEntity(this.foo, this.bar, this.baz); </code></pre> <p>And the saveEntity() method of the repository has all of the knowledge of how to save in the data layer, as it should.</p> <p>In addition to this setup, you could have:</p> <pre><code>repository.save(entity); </code></pre> <p>which just calls</p> <pre><code>entity.saveIn(this); </code></pre> <p>I re-read this and I notice that the entity is still thin because it is simply dispatching its persistence to the repository. But in this case, the entity is supposed to be thin because you didn't describe any other domain logic. In this situation, you could say "screw Double Dispatch, give me accessors." </p> <p>And yeah, you could, but IMO it exposes too much of how your entity is implemented, and those accessors are distractions from domain logic. I think the only class that should have gets and sets is a class whose name ends in "Accessor".</p> <p>I'll wrap this up soon. Personally, I don't write my entities with saveIn() methods, because I think even just having a saveIn() method tends to litter the domain object with distractions. I use either the friend class pattern, package-private access, or possibly the <a href="http://www.javaworld.com/javaworld/jw-01-2004/jw-0102-toolbox.html?page=3" rel="nofollow noreferrer">Builder pattern</a>.</p> <p>OK, I'm done. As I said, I've obsessed on this topic quite a bit.</p>
<p>Try the "repository pattern" and "Domain driven design". DDD suggests to define certain entities as Aggregate-roots of other objects. Each Aggregate is encapsulated. The entities are "persistence ignorant". All the persistence-related code is put in a repository object which manages Data-access for the entity. This way you don't have to mix persistence-related code with your business logic. If you are interested in DDD, check out eric evans book.</p>
28,200
<p>What are the steps to connect to Oracle 9i with VB6? How can I use modules and stored procedures in VB6 and how can I call an SP?</p> <p>What is the method to use ADO which is helpful to insert, update, search and delete the items from the front end?</p>
<p>You will need ADO to connect to Oracle (add reference to microsoft activex data objects library).</p> <p>You need to know where is the Oracle Instance hosted alongwith username and password?</p> <p>The connection string for Oracle can be found from www.connectionstrings.com</p> <p>ADODB.Connection is the one that you will need to establish the connection.<br> Connection has Execute method - which you can use for any insert/update/delete statements.</p> <p>Now, read some documentation on ADO object library from MSDN. And, write the code by yourself.</p>
<p>You will also need to have the Oracle client installed on your PC, along with an appropriate TNS Names file. Also, be aware that there are some minor functional differences between various versions of the Oracle 9 client - I had some issues under v9.2.0.1, that did not occur under v9.2.0.7.</p>
45,026
<p>Is there a way to access the DOM of the document in an iframe from parent doc if the doc in the iframe is on another domain? I can easily access it if both parent and child pages are on the same domain, but I need to be able to do that when they are on different domains.</p> <p>If not, maybe there is some other way to READ the contents of an iframe (one consideration was to create an ActiveX control, since this would be for internal corporate use only, but I would prefer it to be cross-browser compatible)?</p>
<p>Not really. This is essential for security – otherwise you could open my online banking site or webmail and mess with it.</p> <p>You can <a href="https://developer.mozilla.org/En/Same_origin_policy_for_JavaScript" rel="nofollow noreferrer">loosen restriction</a> a bit by setting <code>document.domain</code>, but still top level domain must be the same.</p> <p>You can work around this limitation by proxying requests via your own server (but don't forget to secure it, otherwise s[cp]ammers may abuse it)</p> <pre><code>my.example.com/proxy?url=otherdomain.com/page </code></pre>
<p>I just found <code>postMessage</code> method introduced with HTML5; it's already implemented in recent browser (FF3, IE8 and Safari 4). It allows the exchange of messages between any windows object inside the browser. For the details see the documentation at <a href="https://developer.mozilla.org/En/DOM:window.postMessage" rel="nofollow noreferrer">MDC</a> and this <a href="http://ejohn.org/blog/cross-window-messaging/" rel="nofollow noreferrer">nice tutorial</a> by John Resig.</p>
43,564
<p>Given two absolute paths, e.g.</p> <pre><code>/var/data/stuff/xyz.dat /var/data </code></pre> <p>How can one create a relative path that uses the second path as its base? In the example above, the result should be: <code>./stuff/xyz.dat</code></p>
<p>It's a little roundabout, but why not use URI? It has a relativize method which does all the necessary checks for you.</p> <pre><code>String path = "/var/data/stuff/xyz.dat"; String base = "/var/data"; String relative = new File(base).toURI().relativize(new File(path).toURI()).getPath(); // relative == "stuff/xyz.dat" </code></pre> <p>Please note that for file path there's <code>java.nio.file.Path#relativize</code> since Java 1.7, as pointed out by <a href="https://stackoverflow.com/users/1113396/jirka-meluzin">@Jirka Meluzin</a> in <a href="https://stackoverflow.com/a/25743823/537554">the other answer</a>.</p>
<p>Psuedo-code:</p> <ol> <li>Split the strings by the path seperator ("/")</li> <li>Find the greatest common path by iterating thru the result of the split string (so you'd end up with "/var/data" or "/a" in your two examples)</li> <li><code>return "." + whicheverPathIsLonger.substring(commonPath.length);</code></li> </ol>
25,075
<p>In the below code snippet can i replace char * to const char * and remove the strdup() function call and directly take the optarg value set by getopt()? I am advised to use const char * to skip the strdup function usage. Appreciate the help in advance.</p> <pre><code>/* Code Snippet */ char *dir = NULL; char *bld = NULL; int chr; while ( ( chr = getopt( argc, argv, "d:a:b:f:" ) ) != -1 ) { switch ( chr ) { case 'd': //Directory parameter dir = strdup( optarg ); if (dir == NULL) { /*Error*/ } case 'b': //Build parameter bld = strdup( optarg ); if (bld == NULL) { /*Error*/ } ...other code... } } </code></pre> <p>I really don't understand the need for doing so.</p> <p>Edit: Thanks for the answers. It was really helpful. I modified the code to const char * and skipped the strdup call.</p> <p>Thanks, Liju</p>
<p>You could try and use Geometry.Combine. It applies a transform during the combine. One catch is that Combine only works if your Geometry has area, so single lines will not work.</p> <p>Here is a sample that worked for me.</p> <pre><code>PathGeometry geometry = new PathGeometry(); geometry.Figures.Add(new PathFigure(new Point(10, 10), new PathSegment[] { new LineSegment(new Point(10, 20), true), new LineSegment(new Point(20, 20), true) }, true)); ScaleTransform transform = new ScaleTransform(2, 2); PathGeometry geometryTransformed = Geometry.Combine(geometry, geometry, GeometryCombineMode.Intersect, transform); </code></pre>
<p>There are two things you have to consider:</p> <ol> <li>Geometry inherits from Freezable, you can't modify the geometry object in-place if it's frozen.</li> <li>You can scan the PathGeometry list of figures and segments and transform all the points in them but some types, like ArcSegment includes sizes and angles, you can't transform them.</li> </ol>
31,094
<p>For example:</p> <pre><code>public void doSomething() { final double MIN_INTEREST = 0.0; // ... } </code></pre> <p>Personally, I would rather see these substitution constants declared statically at the class level. I suppose I'm looking for an "industry viewpoint" on the matter.</p>
<p>I would think that you should only put them at the class level if they are used by multiple methods. If it is only used in that method then that looks fine to me.</p>
<p>The reason why you can define a final variable at a class level or method (local) level it's because you can override the global static constant inside the (local) method. </p> <p>Example: </p> <pre><code>public class Test { final double MIN_INTEREST = 0.0; /** * @param args */ public static void main(String[] args) { Test test = new Test(); test.doSomethingLocal(); test.doSomethingGlobal(); } public void doSomethingGlobal() { System.out.println("Global-&gt; " + MIN_INTEREST); } public void doSomethingLocal() { final double MIN_INTEREST = 0.1; System.out.println("Local-&gt; " + MIN_INTEREST); } } </code></pre> <p>The output will be:</p> <pre><code>Local-&gt; 0.1 Global-&gt; 0.0 </code></pre> <p>So your question doesn't make any sense.</p>
30,273
<p>I noticed a good while back that Wikipedia links to a <a href="http://pajhome.org.uk/crypt/md5/" rel="noreferrer">Javascript implementation</a> of different hash functions. Also found <a href="http://www.clipperz.com/open_source/javascript_crypto_library" rel="noreferrer">Clipperz Crypto</a>. Even Mozilla implements a <a href="http://developer.mozilla.org/en/JavaScript_crypto" rel="noreferrer">crypto object</a> in Firefox.</p> <p>So, <em>Is Javascript a proper platform for cryptography? Or, can it be?</em><br> Or, I suppose.. Are there any purposes or benefits for hashing data before POST?</p>
<p>There are uses for hashing functions in Javascript, for example validating captchas client side (by comparing hash in session to computed hash from input). Obviously, the uses are limited since it runs almost exclusively client side (and you can't trust client input), but the potential is there.</p>
<p>I dont see why a cryptographic function couldnt be implemented using javascript. </p> <p>However..Cryptography is a resource intensive process. </p> <p>Compared to compiled code Javascript is slooooooow. </p>
23,751
<p>In OOP languages like C# or VB.NET, if I make the properties or methods in a super class <code>protected</code> I can't access them in my Form - they can only be accessed in my class that inherits from that super class.</p> <p>To access those properties or methods I need to make them <code>public</code>, which defeats encapsulation, or re-write them into my class, which defeats inheritance.</p> <p>What is the right way to do this?</p>
<p>If you have code which needs to ask an Class to perform a specific operation but the class does not present your code with a means to do that then the Class doesn't fulfill you codes requirements.</p> <p>Its bit like saying I've got a Car (Automobile) that has a protected steering wheel so I can't access it. The car is no use to me.</p> <p>Either make those members Public (or at least internal) and use them or ditch the class and use one that gives your consuming code the features it needs.</p> <p>Perhaps what you are really looking for is an interface. The interface contains the members your code needs and you implement that interface on your class. The advantage here is that your class can determine that the members are being accessed via this Interface rather than an inheriting subclass.</p>
<p>Sorry, it's not clear what you mean by "in my Form" - what is the relationship between your Form and your two classes? If your classes are controls in the same project, and you want to access properties from the form, you should use the 'internal' keyword.</p>
36,929
<p>Can anyone (maybe an XSL-fan?) help me find any advantages with handling presentation of data on a web-page with XSL over ASP.NET MVC?</p> <p>The two alternatives are:</p> <ol> <li><p><strong>ASP.NET (MVC/WebForms) with XSL</strong><br/> Getting the data from the database and transforming it to XML which is then displayed on the different pages with XSL-templates.</p></li> <li><p><strong>ASP.NET MVC</strong><br /> Getting the data from the database as C# objects (or LinqToSql/EF-objects) and displaying it with inline-code on MVC-pages.</p></li> </ol> <p>The main benefit of XSL has been consistent display of data on many different pages, like WebControls. So, correct me if I'm wrong, ASP.NET MVC can be used the same way, but with strongly typed objects. Please help me see if there are any benefits to XSL.</p>
<p>I can see the main benefit of employing XSLT to transform your data and display it to the user would be the following:</p> <ul> <li>The data is already in an XML format</li> <li>The data follows a well defined schema (this makes using tools like XMLSpy much easier).</li> <li>The data needs to be transformed into a number of different output formats, e.g. PDF, WMP and HTML</li> </ul> <p>If this is to be the only output for your data, and it is not in XML format, then XSLT might not be the best solution.</p> <p>Likewise if user interaction is required (such as editing of the data) then you will end up employing back-end code anyway to handle updates so might prove one technology too far...</p>
<p>If you only going to display data from DB XSL templates may be convenient solution, but if you gonna handle user interaction. Hm... I don't think it'll be maintainable at all.</p>
6,043
<p>The question is in Java why can't I define an abstract static method? for example</p> <pre><code>abstract class foo { abstract void bar( ); // &lt;-- this is ok abstract static void bar2(); //&lt;-- this isn't why? } </code></pre>
<p>Because "abstract" means: "Implements no functionality", and "static" means: "There is functionality even if you don't have an object instance". And that's a logical contradiction.</p>
<p>Because if a class extends an abstract class then it has to override abstract methods and that is mandatory. And since static methods are class methods resolved at compile time whereas overridden methods are instance methods resolved at runtime and following dynamic polymorphism.</p>
48,477
<p>I want to change the font I am using in a CEikLabel on S60 device</p> <p>I believe I can do the following</p> <pre><code>const CFont* aPlainFont = LatinPlain12(); aLabel-&gt;SetFont(aPlainFont); </code></pre> <p>where LatinPlain12 is one from this list..</p> <pre><code>Albi12 Alp13 Alpi13 Albi13 alp17 Alb17b albi17b alpi17 Aco13 Aco21 Acalc21 LatinBold12 LatinBold13 LatinBold17 LatinBold19 LatinPlain12 Acb14 Acb30 Acp5 </code></pre> <p>However, who can help me find out which ones from this list are fixed width.. Thanks :)</p>
<p>You may use the <a href="http://www.newlc.com/FontViewer.html" rel="nofollow noreferrer">FontViewer</a> application to view and find out which of the fonts are proportional and fixed-width.</p>
<p>You may use the <a href="http://www.newlc.com/FontViewer.html" rel="nofollow noreferrer">FontViewer</a> application to view and find out which of the fonts are proportional and fixed-width.</p>
44,730
<p>I've had my Ender 3 Pro for a few months, and it's been working great. Then, after a failed print (the STL had extra seams, causing the print to get mangled), I've started having issues that I have attributed to under-extrusion.</p> <p>As evidenced by the below image, some lines in each layer are missing. The gaps align throughout the print, but not between prints (the two squares are identical G-code). This happens in every layer, with a different pattern in each. It also causes some perimeters to not adhere to the previous layer at all.</p> <p>The extra strands in the right print are present because I ripped off the infill layer that printed on top before I aborted the print.</p> <p>I first assumed I needed to calibrate my extruder. It turns out I did (93 had to be changed to 150 steps/mm). However, that did not fix the issue.</p> <p><strong>Some things I've tried</strong>:</p> <ul> <li>Calibrate the extruder</li> <li>Check nozzle size and filament size in Slic3r</li> <li>Level the bed (I had to place a post-it note under the centre of the flexible magnetic build surface to make up for a warped bed)</li> <li>Clean my nozzle and hotend (I fully dismantled the hotend)</li> <li>Replace my nozzle</li> <li>Increase printing temperature</li> </ul> <p>Is there anything else I might try to get this fixed?</p> <p><img src="https://i.stack.imgur.com/i2KNm.jpg" alt="Evidence Image" /></p> <p><strong>Specs for Reference</strong>:</p> <ul> <li>Ender 3 Pro</li> <li>0.4 mm Brass Nozzle</li> <li>205 °C Hotend</li> <li>60 °C Bed</li> <li>Slic3r</li> <li>150 Steps/mm for Extruder</li> </ul> <hr /> <p>If you need any more information, just comment and I'll do my best to supply it.</p> <p><em>Please note that I am <strong>not</strong> open to suggestions to replace my printer. I'd rather fix the one I have.</em></p>
<p>It turns out the extruder <em>was</em> slipping, but not due to a nozzle or Bowden tube pressure issue. The extruder arm (?) that holds the passive wheel (as opposed to the drive gear) was cracked, so the pressure between the wheel and the gear was weak. A bit of glue fixed it.</p> <p>These printers should ship with metal extruders, I think.</p> <p><strong>EDIT</strong></p> <p>The arm broke <em>again</em>, and this time I have a picture to illustrate the issue. I didn't make the printer do anything strenuous; I just printed a few small parts, causing it to break. <img src="https://i.stack.imgur.com/ibmeD.jpg" alt="enter image description here" /></p>
<p>This is a big red flag and severely wrong:</p> <blockquote> <p>93 had to be changed to 150 steps/mm</p> </blockquote> <p>It can be reasonable to tune steps per mm by a few percent, but needing an increase of more than 50% versus the standard value for the same physical gearing indicates either you did something wrong in computing the needed value, or some other serious root problem with the printer.</p> <p>You should start by fixing that (putting it back at 93) then try to figure out why it seemed to need change.</p> <p>Likely your extruder isn't gripping the filament. Trying to overextrude that severely likely grinds it so bad the hob fills up with shavings then doesn't grip at all.</p>
2,003
<p>I want to spruce up some areas of my website with a few jQuery animations here and there, and I'm looking to replace my AJAX code entirely since my existing code is having some cross-browser compatibility issues. However, since jQuery is a JavaScript library, I'm worried about my pages not functioning correctly when JavaScript is turned off or doesn't exist in a user's browser.</p> <p>I'll give an example: Currently, I'm using a pure CSS tooltip to give my users (players, the site is a browser game) information on other users. For example, if the other players in the game satisfy one or more conditions, a target icon is displayed next to their name, and upon hovering over that target icon information regarding the reasons behind the target is displayed. This is useful information, as it helps my players to know who they should plan to attack next in the game.</p> <p>Currently, I do such tooltips using CSS. I have a parent div that holds the image of the target icon of class "info". I then have a div inside of that with class "tooltip" that, on the hover state of the "info" class that it is contained in, is shown, but on the normal state is hidden. I thought it was rather clever when I read about it, and since no JavaScript is used it works on any CSS compliant browser.</p> <p>I would like to use jQuery to achieve the same effect, mostly because it would look much cleaner, but also because I believe quick and subtle animations can make such things "randomly appearing" make a lot more sense to the user, especially on the first encounter. I'm just wondering if the two will conflict. This is only one example of this, there are numerous other examples where the inability to use JavaScript would hinder the site.</p> <p>So what I'm asking I guess is, how does one make a jQuery site degrade gracefully on browsers that do not support JavaScript, but otherwise <em>do</em> support most CSS? My goal is for the site to function on a basic level for all users, regardless of choice in browser. The animation is a good example, but I'm also worried about the more dynamic bits, like the auto-updating with AJAX, etc. Are there any good resources on how to achieve this, or do you have any advice about the best way such degradability could be achieved?</p> <p>Thanks</p> <p>PS: Totally irrelevant, but Firefox seems to think that "degradability" isn't a word, but "biodegradability" (with the "bio" prefix) is. Weird...</p>
<p>If you consider the "Cascading Order" of css, could you not just add a css style at the very end of all your previous css definition in order to cancel any css effect you currently have for tooltip effect ?</p> <p>That css rule would only be declared if Javascript is activated and JQuery detected.</p> <p>That way, you are sure your <a href="http://psacake.com/web/jl.asp" rel="nofollow noreferrer">css tooltip effect</a> is not in conflict with your JQuery effect.</p> <p>Something like:</p> <pre><code>a.info:hover span{ display:none} </code></pre> <p>with the use of "js_enabled" class to make this css rule conditional.</p> <p>You also can do it by <a href="http://forum.mootools.net/viewtopic.php?id=6635" rel="nofollow noreferrer">adding css rule on the fly</a>:</p> <pre><code>function createCSSRule(rule,attributes) { //Create the CSS rule var newRule = "\n"+rule+"{\n"; for (var attribute in attributes) { newRule += "\t" + attribute + ": " + attributes[attribute] + ";\n"; } newRule += "}\n"; //Inject it in the style element or create a new one if it doesn't exist styleTag = $E('style[type="text/css"]') || new Element("style").setProperty('type','text/css').injectInside(document.head); if(window.ie) { styleTag.styleSheet.cssText += newRule; } else { styleTag.appendText(newRule); } } </code></pre> <hr> <p>The most simple solution for <a href="http://www.onlinetools.org/articles/unobtrusivejavascript/cssjsseparation.html" rel="nofollow noreferrer">Separation of CSS and Javascrip</a> is to <strong>remove your css class</strong></p> <pre><code>function jscss(a,o,c1,c2) { switch (a){ case 'swap': o.className=!jscss('check',o,c1)?o.className.replace(c2,c1): &lt;- o.className.replace(c1,c2); break; case 'add': if(!jscss('check',o,c1)){o.className+=o.className?' '+c1:c1;} break; case 'remove': var rep=o.className.match(' '+c1)?' '+c1:c1; o.className=o.className.replace(rep,''); break; case 'check': return new RegExp('\\b'+c1+'\\b').test(o.className) break; } } </code></pre> <p>This example function takes four parameters:</p> <p><code>a</code><br> defines the action you want the function to perform.<br> <code>o</code><br> the object in question.<br> <code>c1</code><br> the name of the first class<br> <code>c2</code><br> the name of the second class </p> <p>Possible actions are:</p> <p><code>swap</code><br> replaces class c1 with class c2 in object o.<br> <code>add</code><br> adds class c1 to the object o.<br> <code>remove</code><br> removes class c1 from the object o.<br> <code>check</code><br> test if class c1 is already applied to object o and returns true or false. </p>
<p>Man, you have a browser-based game, right? You have less than 1% users with JS disabled! And that 1% is the apocalyptic number because I can BET that you have less than that ;)</p> <p>Anyhow, if you are really concerned about this, just do the site without any JavaScript. And make it functional 100%. After your site works completely without any JS flavour, just start to improve with jQuery (or any other library; jQuery is the best :P ). But with careful: do not change ANY of you HTML. It's easier than it looks ;)</p> <p>And yes, if you have things that work without JS (like those tooltips) keep it!</p>
39,669
<p>Just installed the latest SDK for iPhone 2.1. When I go to File -> New Project in Xcode, under the iPhone OS Application selection, I don't see a template icon for "Cocoa Touch Application". Am I missing something? Anything else I need to download other than the iPhone SDK? If not, how do I add it to the "iPhone OS Application" templates?</p>
<p>All the templates (under iPhone) are Cocoa based.</p> <p>The difference between them is basically how you set up the main View and the navigational controls that are installed by default.</p>
<p>All the templates (under iPhone) are Cocoa based.</p> <p>The difference between them is basically how you set up the main View and the navigational controls that are installed by default.</p>
13,688
<p>I've just tried to make some small labels with embossed lettering. Base is 1.5 mm, with letters and a perimeter protruding by another 1 mm. After printing, I realised that Cura is not giving me a top layer, all I get is an inner and outer wall for the perimeter and the lettering:</p> <p><a href="https://i.stack.imgur.com/Hri17.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Hri17.png" alt="Screenshot showing missing infill in top layer"></a></p> <p>The base is OK, with 4 layers, but there is no infill at the top. Presumably there is a setting that I've missed (I can appreciate that maybe this is a detail to the slicing which is model dependant). Layers are 0.2 mm, top and bottom set to 4 layers.</p> <p>I had walls set to 1.6 mm, (4 layers) and the wall features here are 1 mm (i.e. 2.5x the nozzle). The features are solid so far as I know, not drawn as a hollow.</p> <p>I found a relevant bug for Cura: <a href="https://github.com/Ultimaker/Cura/issues/1303" rel="nofollow noreferrer">https://github.com/Ultimaker/Cura/issues/1303</a> (and I also understand a workaround now, just need to write up an answer).</p>
<p>What is happening here is that Cura is struggling with the quantised extrusion width. This behaviour can be improved in the slicer, they have a issue tracked here <a href="https://github.com/Ultimaker/Cura/issues/1303" rel="nofollow noreferrer">https://github.com/Ultimaker/Cura/issues/1303</a> and 2.4 beta has improved it.</p> <p>There are some pictures in this <a href="https://3dprinting.stackexchange.com/a/3581/4927">answer</a> which show how Cura 2.3 slices a rectangle of increasing width. I got nothing at the nozzle width, then a pair of overlapping lines up to twice the width (which I assume will be over-extruded due to the overlap). For anything wider than simply two sides, the result depends on the number of walls requested.</p> <ul> <li>One wall results in 100% infill for small regions (regardless of the infill setting). This is good, but maybe 1 wall is not apropriate for the whole model.</li> <li>Multiple walls seem to prevent the infill untill there is space for pairs of walls. So width of 3x nozzle has a gap. Small tweeks to the nozzle size can maybe push this quantisation point about, if 1 wall is not a good workaround.</li> </ul> <p>For rectangular geometry, it's worth trying to quantize small parts in 0.8mm increments. For curves, setting 1 wall shell might be better.</p>
<p>Try Cura 2.4.0-beta2: there is option named "Fill Gaps Between Walls" under "Shell" settings, set it to "everywhere". In stable Cura 2.3.1 this option is missing.</p>
440
<p>My server has both Subversion and Apache installed, and the Apache web directory is also a Subversion working copy. The reason for this is that the simple command <code>svn update /server/staging</code> will deploy the latest source to the staging server.</p> <p>Apache public web directory: <code>/server/staging</code> <em>— (This is an SVN working copy.)</em></p> <p>I have two users on my server, 'richard' and 'austin'. They both are members of the 'developers' group. I recursively set permissions on the /server directory to richard:developers, using "sudo chown -R richard:developers /server".</p> <p>I then set the permissions to read, write and execute for both 'richard' and the 'developers' group.</p> <p>So surely, 'austin' should now be able to use the <code>svn update /server/staging</code> command? However, when he tries, he gets the error:</p> <pre><code>svn: Can't open file '/server/staging/.svn/lock': Permission denied </code></pre> <p>If I recursively change the owner of /server to austin:developers, he can run the command just fine, but then 'richard' can't.</p> <p>How do I fix the problem? I want to create a post-commit hook with to automatically deploy the staging site when files are committed, but I can't see a way for that to work for both users. The hook would be:</p> <pre><code>/usr/bin/svn update /server/staging </code></pre> <p>Using the same user account for both of them wouldn't really be an acceptable solution, and I'm not aware of any way to run the command inside the hook as 'root'.</p> <p>Any help is appreciated!</p>
<p>Directory Set Group ID</p> <p>If the setgid bit on a directory entry is set, files in that directory will have the group ownership as the directory, instead of than the group of the user that created the file.</p> <p>This attribute is helpful when several users need access to certain files. If the users work in a directory with the setgid attribute set then any files created in the directory by any of the users will have the permission of the group. For example, the administrator can create a group called spcprj and add the users Kathy and Mark to the group spcprj. The directory spcprjdir can be created with the set GID bit set and Kathy and Mark although in different primary groups can work in the directory and have full access to all files in that directory, but still not be able to access files in each other's primary group.</p> <p>The following command will set the GID bit on a directory:</p> <pre><code>chmod g+s spcprjdir </code></pre> <p>The directory listing of the directory "spcprjdir":</p> <pre><code>drwxrwsr-x 2 kathy spcprj 1674 Sep 17 1999 spcprjdir </code></pre> <p>The "s'' in place of the execute bit in the group permissions causes all files written to the directory "spcprjdir" to belong to the group "spcprj" . </p> <p>edit: source = <a href="http://www.comptechdoc.org/os/linux/usersguide/linux_ugfilesp.html" rel="nofollow noreferrer">Linux Files and File Permissions</a></p>
<p>I would set up <code>svnserve</code> which is a simple Subversion server using the <code>svn://</code> protocol. You can set this up so it runs under its own user account, then the repository would only be accessed by that one user. This user could then have the correct privileges to run <code>svn update /server/staging</code> on a post-commit hook.</p>
19,897
<p>I have a repository which contains some unversioned directories and files. The server running svn was recently changed and since the checkout was done using the url svn://OLD-IP, I relocated my svn working copy, this time to the url svn://NEW-DOMAIN-NAME. </p> <p>Now since there are some unversioned resources, the switch did not happen properly and the working copy got locked. A cleanup operation did not work either because of these unversioned resources. </p> <p>I looked up in the net and found about svn ignore and tried that but to no use. I am unable to release all locks. Any ideas on solving the problem? Once I release the locks, I believe I can use svn ignore and carry on the relocate operation.</p>
<p>Check your <code>svn status</code> output and the legend for the letters at <code>svn help status</code>.</p> <p>Quite often, the problem is that there is a file where svn expects a directory, or other kinds of similar confusion (the letters should tell you which it is). If there are any conflicts (<code>C</code>), solve them first. You can recover lost directories with <code>svn update</code>, and <code>svn revert</code> can often help too (if there is anything important on your working copy which is not in the repository, make a backup of the working copy first!).</p> <p>After most of the confusion has been cleared, <code>svn cleanup</code> and <code>svn update</code>/<code>svn switch</code> (<code>update</code> is nothing more than a special case of <code>switch</code>) should start working again.</p> <p>In the worst case, you can do another checkout and manually copy over any locally modified files.</p>
<p>I had this issue. Rename the offending directory and rebuild it from SVN, then copy over the files you modified. May need to run cleanup in the parent directory</p>
37,071
<p>Has anyone worked with <a href="http://www.google.com.br/url?sa=t&amp;ct=res&amp;cd=1&amp;url=http%3A%2F%2Fen.wikipedia.org%2Fwiki%2FDomain-specific_programming_language&amp;ei=QyWvSIXcC4foebjSlHs&amp;usg=AFQjCNFsZOnJm-AGmi5sxai8YI-0Al6wfA&amp;sig2=6nX5EkUmNkEwiSKAkUeyZQ" rel="noreferrer">DSLs (Domain Specific Languages)</a> in the finance domain? I am planning to introduce some kind of DSL support in the application that I am working on and would like to share some ideas.</p> <p>I am in a stage of identifying which are the most stable domain elements and selecting the features which would be better implemented with the DSL. I have not yet defined the syntax for this first feature.</p>
<p>Jay Fields and Obie Fernandez have written and talked extensively on the subject.</p> <ul> <li>Jay Fields intro on <a href="http://blog.jayfields.com/2008/02/designing-domain-specific-language.html" rel="noreferrer">Domain Specific Languages</a></li> <li>Jay Fields' series on <a href="http://bnl.jayfields.com/01_introduction.html" rel="noreferrer">Business Natural Language</a></li> <li>Obie Fernandez <a href="http://www.jroller.com/obie/entry/expressing_contract_terms_in_a" rel="noreferrer">Expressing Contract Terms in a DSL</a></li> <li>A very good <a href="http://www.infoq.com/presentations/fields-business-natural-languages-ruby" rel="noreferrer">presentation</a> on infoQ by Jay Fields</li> </ul> <p>You'll also find general stuff on implementing DSL in Martin Fowler's writings (but not specific to finance).</p> <ul> <li><a href="http://martinfowler.com/dslwip/" rel="noreferrer">DSL</a></li> </ul>
<p>We worked on the idea of creating a financial valuation DSL with Fairmat ( <a href="http://www.fairmat.com" rel="nofollow">http://www.fairmat.com</a> )</p> <p>-it exposes a DSL which can be used to express pay-offs and payment dependencies -it contains an extension model for creating new types of analytic and implementations of theoretical dynamics using .NET/ C# with our underlying math library (see some open source examples at <a href="https://github.com/fairmat" rel="nofollow">https://github.com/fairmat</a></p>
4,343
<p>I recently got a notification from a McAfee service (what used to be called HackerSafe) that my website is using SSLv2 and it should be using SSLv3. I don't know anything about the versions of SSL. My site is using IIS 6.0, is there a setting somewhere to turn on SSLv3 or do I need to install something to make this happen? Also, is there any drawbacks to only using SSLv3? Are there browsers that can only use v2?</p>
<p>Microsoft has a KB article on disabling SSLv3, obviously it's in the same place as enabling it. <a href="http://support.microsoft.com/kb/187498/en-us" rel="nofollow noreferrer">http://support.microsoft.com/kb/187498/en-us</a></p>
<p>If you are looking at fixing this you will probably also want the to fix weak ciphers since most scanners will complain about both. That is <a href="http://support.microsoft.com/kb/245030" rel="nofollow noreferrer">Microsoft KB245030</a>. Generally any browser that supports SSLv3 will also support newer and stronger ciphers than the ones turned off by the scripts at that link.</p>
33,990
<p>I am writing some code to see if there is a hole in the firewall exception list for <strong>WinXP</strong> and <strong>Vista</strong> for a specific port used by our client software. </p> <p>I can see that I can use the <code>NetFwMgr.LocalPolicy.CurrentProfile.GloballyOpenPorts</code> to get a list of the current Open port exceptions. But i can not figure out how to get that enumerated list in to something that I can use in my Delphi program. </p> <p>My latest try is listed below. It's giving me an access violation when I use <code>port_list.Item</code>. I know that's wrong, it was mostly wishful thinking on my part. Any help would be appreciated.</p> <pre><code>function TFirewallUtility.IsPortInExceptionList(iPortNumber: integer): boolean; var i, h: integer; port_list, port: OleVariant; begin Result := False; port_list := mxFirewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts; for i := 0 to port_list.Count - 1 do begin port := port_list.Item[i]; if (port.PortNumber = iPortNumber) then begin Result := True; break; end; end; end; </code></pre>
<p>OK, I think that I have it figured out. </p> <p>I had to create a type library file of the hnetcfg.dll. I did that when I first started but have learned a lot about the firewall objects since then. It didn't work then, but its working now. You can create your own file from Component|Import Component. And then follow the wizard. </p> <p>The wrapping code uses exceptions which I normally don't like to do, but I don't know how to tell whether an Interface that is returning an Interface is actually returning data that I can work off of... So that would be an improvement if somebody can point me in the right direction.</p> <p>And now to the code, with a thanks to Jim for his response.</p> <pre><code>constructor TFirewallUtility.Create; begin inherited Create; CoInitialize(nil); mxCurrentFirewallProfile := INetFwMgr(CreateOLEObject('HNetCfg.FwMgr')).LocalPolicy.CurrentProfile; end; function TFirewallUtility.IsPortInExceptionList(iPortNumber: integer): boolean; begin try Result := mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, NET_FW_IP_PROTOCOL_TCP).Port = iPortNumber; except Result := False; end; end; function TFirewallUtility.IsPortEnabled(iPortNumber: integer): boolean; begin try Result := mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, NET_FW_IP_PROTOCOL_TCP).Enabled; except Result := False; end; end; procedure TFirewallUtility.SetPortEnabled(iPortNumber: integer; sPortName: string; xProtocol: TFirewallPortProtocol); begin try mxCurrentFirewallProfile.GloballyOpenPorts.Item(iPortNumber, CFirewallPortProtocalConsts[xProtocol]).Enabled := True; except HaltIf(True, 'xFirewallManager.TFirewallUtility.IsPortEnabled: Port not in exception list.'); end; end; procedure TFirewallUtility.AddPortToFirewall(sPortName: string; iPortNumber: Cardinal; xProtocol: TFirewallPortProtocol); var port: INetFwOpenPort; begin port := INetFwOpenPort(CreateOLEObject('HNetCfg.FWOpenPort')); port.Name := sPortName; port.Protocol := CFirewallPortProtocalConsts[xProtocol]; port.Port := iPortNumber; port.Scope := NET_FW_SCOPE_ALL; port.Enabled := true; mxCurrentFirewallProfile.GloballyOpenPorts.Add(port); end; </code></pre>
<p>Without setting up an application to test with, I'll suggest the following. Let me know if it works.</p> <p>I looked at the <a href="http://blogs.msdn.com/joncole/archive/2005/12/06/managed-classes-to-view-manipulate-the-windows-firewall.aspx" rel="nofollow noreferrer">C# example here</a>, and it looks like you need to do something like the following:</p> <pre><code>Result := False; port_enum := mxFirewallManager.LocalPolicy.CurrentProfile.GloballyOpenPorts._NewEnum; while port_enum.MoveNext &lt;&gt; Null do // try assigned if that doesn't work begin port = e.Current as INetFwOpenPort; if (port.PortNumber = iPortNumber) then begin Result := True; break; end; end; </code></pre> <p>Not sure if that will compile, but the <strong>_NewEnum</strong>, <strong>MoveNext</strong> and <strong>Current</strong> are the members you want to use.</p>
10,331
<p>In a VB.NET WinForms project, I get an exception</p> <blockquote> <p>Cannot access a disposed of object</p> </blockquote> <p>when closing a form. It occurs very rarely and I cannot recreate it on demand. The stack trace looks like this:</p> <pre><code>Cannot access a disposed object. Object name: 'dbiSchedule'. at System.Windows.Forms.Control.CreateHandle() at System.Windows.Forms.Control.get_Handle() at System.Windows.Forms.Control.PointToScreen(Point p) at Dbi.WinControl.Schedule.dbiSchedule.a(Boolean A_0) at Dbi.WinControl.Schedule.dbiSchedule.a(Object A_0, EventArgs A_1) at System.Windows.Forms.Timer.OnTick(EventArgs e) at System.Windows.Forms.Timer.TimerNativeWindow.WndProc(Message&amp; m) at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam) </code></pre> <p>The dbiSchedule is a schedule control from Dbi-tech. There is a timer on the form that updates the schedule on the screen every few minutes.</p> <p>Any ideas what is causing the exception and how I might go about fixing it? or even just being able to recreate it on demand?</p> <hr> <p>Hej! Thanks for all the answers. We do stop the Timer on the FormClosing event and we do check the IsDisposed property on the schedule component before using it in the Timer Tick event but it doesn't help.</p> <p>It's a really annoying problem because if someone did come up with a solution that worked - I wouldn't be able to confirm the solution because I cannot recreate the problem manually.</p>
<p>Try checking the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.control.isdisposed.aspx" rel="noreferrer">IsDisposed</a> property before accessing the control. You can also check it on the <a href="http://msdn.microsoft.com/en-us/library/system.windows.forms.form.formclosing.aspx" rel="noreferrer">FormClosing</a> event, assuming you're using the FormClosed event.</p> <blockquote> <p>We do stop the Timer on the FormClosing event and we do check the IsDisposed property on the schedule component before using it in the Timer Tick event but it doesn't help.</p> </blockquote> <p>Calling GC.Collect before checking IsDisposed may help, but be careful with this. Read this article by Rico Mariani "<a href="http://blogs.msdn.com/ricom/archive/2004/11/29/271829.aspx" rel="noreferrer">When to call GC.Collect()</a>".</p>
<p>because the solution folder was inside OneDrive folder.</p> <p>If you moving the solution folders out of the one drive folder made the errors go away.</p> <p>best</p>
4,928
<p>I want my website to join some webcam recordings in FLV files (like this one). This needs to be done on Linux without user input. How do I do this? For simplicity's sake, I'll use the same flv as both inputs in hope of getting a flv that plays the same thing twice in a row.</p> <p>That should be easy enough, right? There's even a full code example in the <a href="http://ffmpeg.mplayerhq.hu/faq.html#SEC31" rel="noreferrer">ffmpeg FAQ</a>.</p> <p>Well, pipes seem to be giving me problems (both on my mac running Leopard and on Ubuntu 8.04) so let's keep it simple and use normal files. Also, if I don't specify a rate of 15 fps, the visual part plays <a href="http://www.marc-andre.ca/posts/blog/webcam/output-norate.flv" rel="noreferrer">extremely fast</a>. The example script thus becomes:</p> <pre><code>ffmpeg -i input.flv -vn -f u16le -acodec pcm_s16le -ac 2 -ar 44100 \ - &gt; temp.a &lt; /dev/null ffmpeg -i input.flv -an -f yuv4mpegpipe - &gt; temp.v &lt; /dev/null cat temp.v temp.v &gt; all.v cat temp.a temp.a &gt; all.a ffmpeg -f u16le -acodec pcm_s16le -ac 2 -ar 44100 -i all.a \ -f yuv4mpegpipe -i all.v -sameq -y output.flv </code></pre> <p>Well, using this will work for the audio, but I only get the video the first time around. This seems to be the case for any flv I throw as input.flv, including the movie teasers that come with red5.</p> <p>a) Why doesn't the example script work as advertised, in particular why do I not get all the video I'm expecting?</p> <p>b) Why do I have to specify a framerate while Wimpy player can play the flv at the right speed?</p> <p>The only way I found to join two flvs was to use mencoder. Problem is, mencoder doesn't seem to join flvs:</p> <pre><code>mencoder input.flv input.flv -o output.flv -of lavf -oac copy \ -ovc lavc -lavcopts vcodec=flv </code></pre> <p>I get a Floating point exception...</p> <pre><code>MEncoder 1.0rc2-4.0.1 (C) 2000-2007 MPlayer Team CPU: Intel(R) Xeon(R) CPU 5150 @ 2.66GHz (Family: 6, Model: 15, Stepping: 6) CPUflags: Type: 6 MMX: 1 MMX2: 1 3DNow: 0 3DNow2: 0 SSE: 1 SSE2: 1 Compiled for x86 CPU with extensions: MMX MMX2 SSE SSE2 success: format: 0 data: 0x0 - 0x45b2f libavformat file format detected. [flv @ 0x697160]Unsupported audio codec (6) [flv @ 0x697160]Could not find codec parameters (Audio: 0x0006, 22050 Hz, mono) [lavf] Video stream found, -vid 0 [lavf] Audio stream found, -aid 1 VIDEO: [FLV1] 240x180 0bpp 1000.000 fps 0.0 kbps ( 0.0 kbyte/s) [V] filefmt:44 fourcc:0x31564C46 size:240x180 fps:1000.00 ftime:=0.0010 ** MUXER_LAVF ***************************************************************** REMEMBER: MEncoder's libavformat muxing is presently broken and can generate INCORRECT files in the presence of B frames. Moreover, due to bugs MPlayer will play these INCORRECT files as if nothing were wrong! ******************************************************************************* OK, exit Opening video filter: [expand osd=1] Expand: -1 x -1, -1 ; -1, osd: 1, aspect: 0.000000, round: 1 ========================================================================== Opening video decoder: [ffmpeg] FFmpeg's libavcodec codec family Selected video codec: [ffflv] vfm: ffmpeg (FFmpeg Flash video) ========================================================================== audiocodec: framecopy (format=6 chans=1 rate=22050 bits=16 B/s=0 sample-0) VDec: vo config request - 240 x 180 (preferred colorspace: Planar YV12) VDec: using Planar YV12 as output csp (no 0) Movie-Aspect is undefined - no prescaling applied. videocodec: libavcodec (240x180 fourcc=31564c46 [FLV1]) VIDEO CODEC ID: 22 AUDIO CODEC ID: 10007, TAG: 0 Writing header... [NULL @ 0x67d110]codec not compatible with flv Floating point exception </code></pre> <p>c) Is there a way for mencoder to decode and encode flvs correctly?</p> <p>So the only way I've found so far to join flvs, is to use ffmpeg to go back and forth between flv and avi, and use mencoder to join the avis:</p> <pre><code>ffmpeg -i input.flv -vcodec rawvideo -acodec pcm_s16le -r 15 file.avi mencoder -o output.avi -oac copy -ovc copy -noskip file.avi file.avi ffmpeg -i output.avi output.flv </code></pre> <p>d) There must be a better way to achieve this... Which one?</p> <p>e) Because of the problem of the framerate, though, only flvs with constant framerate (like the one I recorded through <a href="http://ffmpeg.mplayerhq.hu/faq.html#SEC31" rel="noreferrer">facebook</a>) will be converted correctly to avis, but this won't work for the flvs I seem to be recording (like <a href="http://www.marc-andre.ca/posts/blog/webcam/test-wowza.flv" rel="noreferrer">this one</a> or <a href="http://www.marc-andre.ca/posts/blog/webcam/test-red5-publisher.flv" rel="noreferrer">this one</a>). Is there a way to do this for these flvs too?</p> <p>Any help would be very appreciated.</p>
<p>I thought it would be a nice learning exercise to rewrite it in Ruby.</p> <p>It was.</p> <p>Six months later and three gems later, <a href="http://github.com/marcandre/flvedit" rel="nofollow noreferrer">here's the released product</a>.</p> <p>I'll still be working a bit on it, but it works.</p>
<p>dont know if this will actually work but try using this command : </p> <pre><code>cat yourVideos/*.flv &gt;&gt; big.flv </code></pre> <p>this will probably damage meta information so after executing that command use "flvtool" (ruby script you can find it with google) to fix it.</p>
9,324
<p>I'd like to know how to have a desktop application signed as a product from my company. I'm not sure of the details.I think the process is I have to purchase a certificate from a company like verisign Thanks</p>
<p>You need to sign the code with an Authenticode certificate.</p> <p>Full information here: <a href="http://msdn.microsoft.com/en-us/library/ms537359(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms537359(VS.85).aspx</a></p>
<p>You need to sign the code with an Authenticode certificate.</p> <p>Full information here: <a href="http://msdn.microsoft.com/en-us/library/ms537359(VS.85).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/ms537359(VS.85).aspx</a></p>
34,228
<p>Is any way to tell the solution explorer of Visual Studio 2005 not to expand all projects on the first opening of the solutio after svn-checkout?</p> <p>Edit: Thanks for pointing out the PowerCommands. As I am using Visual Studio 2005 with .Net 2.0 it does not work for me. Are there similar tools available for VS2005?</p>
<p>I found this annoying too, so my solution was to install <a href="http://code.msdn.microsoft.com/PowerCommands" rel="nofollow noreferrer">PowerCommands</a> for Visual Studio which is a nice add in, it has "Colapse Project" function which does exactly that. it also has a dozen of other cool features. </p> <p>Highly recommended.</p>
<p>My default (without anyway of changing this as far as I know) VS will expand all the projects like that on first opening of a solution and creation of the solution user options file. as <strong>ljubomir</strong> mentioned, the best thing to do is create something to collapse all the projects.</p>
19,587
<p>What is the difference between applying the visitor design pattern to your code and the following approach:</p> <pre><code>interface Dointerface { public void perform(Object o); } public class T { private Dointerface d; private String s; public String getS() { return s; } public T(String s) { this.s = s; } public void setInterface(Dointerface d) { this.d = d; } public void perform() { d.perform(this); } public static void main(String[] args) { T t = new T("Geonline"); t.setInterface(new Dointerface() { public void perform(Object o) { T a = (T)o; System.out.println(a.getS()); } }); t.perform(); } } </code></pre> <p>I assume that by using interfaces, we're not really separating the algorithm.</p>
<p>There is quite a big difference. </p> <p>The visitor pattern uses interfaces, but its purpose is to be able to perform an operation to one or more classes (who implement an interface) without having to change the classes. Hence, the implementation actually "visits" the class and does its thing without the class being modified.</p> <p>An interface is a basic concept used to provide a common API to a potentially diverse group of classes. The typical test for an interface is that classes that share it are alike in at least that one respect (is-like-a) and in those cases can be treated as such.</p> <p><a href="http://en.wikipedia.org/wiki/Visitor_pattern#Example_in_Java" rel="noreferrer">Here is a simple example on wikipedia that shows a couple of visitors in java.</a></p>
<p>The only thing that I see that is readily obvious is that by storing the interface, you make it so you have to do two operations rather than one to invoke it. I suppose that this could make sense if you are repeatedly going to perform the same action once the interface is set, but I think you could stick with the standard Visitor and accomplish the same thing.</p>
23,616
<p>Let's say I've got a website that works better if a client has installed and logged into a desktop application. I'd like to be able to do 2 things:</p> <ul> <li>Alter the website if they haven't installed the app (to make it easy for them to find a link to the installer)</li> <li>If they've installed the app on a couple of machines, determine which machine they are browsing from</li> </ul> <p>I'd like something that works on Windows and OSX, on any of the major browsers. Linux is a bonus. </p> <p>A few thoughts:</p> <ul> <li>Websites can detect if you've got Flash installed. How does that work and could it be used for both of my goals? </li> <li>Could I just let the client serve HTTP on localhost and do some javascript requests to fetch a local ID? I know google desktop search did something like this at one point. Is this a standard practice? </li> </ul> <p>Thanks!</p>
<p>You can have a browser plugin (activex for IE or Netscape plugin for the rest of the browsers) that can communicate with the application. When the webpage is loaded, it can try to instantiate the plugin and if it succeeded, it can use it as a proxy to the application. If it fails, then either the app is not installed or the plugin was explictly disabled by the user. Either way, your website should degrade its functionality accordingly.</p> <p><strong>Update</strong>: Forgot to answer your questions:</p> <ol> <li>Flash does it exactly this way. Flash is a browser plugin that is created by the web pages.</li> <li>You can have a machine ID generated at the application/plugin install time and your plugin can pass that machine ID to the webpage when it is created.</li> </ol> <p><strong>On the topic of using local webserver</strong>:</p> <p>I would stay away from having a local webserver, mainly because of security considerations. It takes quite a lot of work to make sure your local webserver is locked down sufficiently and there are no XSS vulnerabilities that other malicious websites can exploit to make it do stuff on their behalf.</p> <p>Plus, having a webserver means that either it has to run as a system-wide process, or if it runs as the user, you can have the website interact with only one user's instance of the application, even though multiple users can be logged on and running it at the same time.</p> <p>Google Desktop Search suffered from both the XSS security vulnerability (though they fixed it) and the limitation of only one user being able to use it on a machine (I don't know if they fixed this one yet, though chances are they did).</p>
<p>If you can pick a development environment for the desktop app, then check out AIR from Adobe. It lets you develop desktop applications using either html/javascript, Flash, or Flex.</p> <p>It has API calls you can use from a browser based flash app to see if the desktop based AIR app is installed, what version, etc. You can even launch it and pass parameters from the web app to the desktop app.</p> <p><a href="http://www.rogue-development.com/blog2/2008/03/interacting-with-an-air-app-from-a-browser-based-app/" rel="nofollow noreferrer">http://www.rogue-development.com/blog2/2008/03/interacting-with-an-air-app-from-a-browser-based-app/</a></p>
19,289
<p>I have a asp:menu object which I set up to use a <em>SiteMapDataSource</em> but everytime I try to run the site, I get a yellow screen from firefox saying it cannot find the <code>web.sitemap</code>. Here's the code for the <em>sitemapdatasource</em> and the menu. The Web.sitemap file is sitting in the root directory of the website.</p> <pre><code>&lt;div&gt; &lt;asp:Menu ID="MainMenu" CssClass="wTheme" Orientation="Horizontal" runat="server" DataSourceID="SiteMapDataSource1"&gt; &lt;/asp:Menu&gt; &lt;asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" SiteMapProvider="Web.sitemap" /&gt; &lt;/div&gt; </code></pre> <p>And this is the Web.sitemap looks like so:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8" ?&gt; </code></pre> <p> </p>
<p>I had a similar problem where I was specifying the path to the SiteMap from within my DataSource control. I tried removing it and it worked.</p> <p>Try removing the path from the SiteMapDataSource and ensure that web.sitemap is in the root directory and see if that fixes it.</p>
<p>You need to specify in web.config to use XmlSiteMapProvider and provide it with correct path to .sitemap file.</p>
10,546
<p>Imagine I have a process that starts several child processes. The parent needs to know when a child exits.</p> <p>I can use <code>waitpid</code>, but then if/when the parent needs to exit I have no way of telling the thread that is blocked in <code>waitpid</code> to exit gracefully and join it. It's nice to have things clean up themselves, but it may not be that big of a deal.</p> <p>I can use <code>waitpid</code> with <code>WNOHANG</code>, and then sleep for some arbitrary time to prevent a busy wait. However then I can only know if a child has exited every so often. In my case it may not be super critical that I know when a child exits right away, but I'd like to know ASAP...</p> <p>I can use a signal handler for <code>SIGCHLD</code>, and in the signal handler do whatever I was going to do when a child exits, or send a message to a different thread to do some action. But using a signal handler obfuscates the flow of the code a little bit.</p> <p>What I'd really like to do is use <code>waitpid</code> on some timeout, say 5 sec. Since exiting the process isn't a time critical operation, I can lazily signal the thread to exit, while still having it blocked in <code>waitpid</code> the rest of the time, always ready to react. <em>Is there such a call in linux? Of the alternatives, which one is best?</em></p> <hr> <p>EDIT:</p> <p>Another method based on the replies would be to block <code>SIGCHLD</code> in all threads with <code>pthread</code> \ <code>_sigmask()</code>. Then in one thread, keep calling <code>sigtimedwait()</code> while looking for <code>SIGCHLD</code>. This means that I can time out on that call and check whether the thread should exit, and if not, remain blocked waiting for the signal. Once a <code>SIGCHLD</code> is delivered to this thread, we can react to it immediately, and in line of the wait thread, without using a signal handler.</p>
<p>Don't mix <code>alarm()</code> with <code>wait()</code>. You can lose error information that way.</p> <p>Use the self-pipe trick. This turns any signal into a <code>select()</code>able event:</p> <pre><code>int selfpipe[2]; void selfpipe_sigh(int n) { int save_errno = errno; (void)write(selfpipe[1], "",1); errno = save_errno; } void selfpipe_setup(void) { static struct sigaction act; if (pipe(selfpipe) == -1) { abort(); } fcntl(selfpipe[0],F_SETFL,fcntl(selfpipe[0],F_GETFL)|O_NONBLOCK); fcntl(selfpipe[1],F_SETFL,fcntl(selfpipe[1],F_GETFL)|O_NONBLOCK); memset(&amp;act, 0, sizeof(act)); act.sa_handler = selfpipe_sigh; sigaction(SIGCHLD, &amp;act, NULL); } </code></pre> <p>Then, your waitpid-like function looks like this:</p> <pre><code>int selfpipe_waitpid(void) { static char dummy[4096]; fd_set rfds; struct timeval tv; int died = 0, st; tv.tv_sec = 5; tv.tv_usec = 0; FD_ZERO(&amp;rfds); FD_SET(selfpipe[0], &amp;rfds); if (select(selfpipe[0]+1, &amp;rfds, NULL, NULL, &amp;tv) &gt; 0) { while (read(selfpipe[0],dummy,sizeof(dummy)) &gt; 0); while (waitpid(-1, &amp;st, WNOHANG) != -1) died++; } return died; } </code></pre> <p>You can see in <code>selfpipe_waitpid()</code> how you can control the timeout and even mix with other <code>select()</code>-based IO.</p>
<p>If a third party library is acceptable then the <a href="https://github.com/mheily/libkqueue" rel="nofollow noreferrer">libkqueue</a> project emulates <code>kqueue</code> (the *BSD eventing system) and provides basic process monitoring with <code>EVFILT_PROC</code> + <code>NOTE_EXIT</code>.</p> <p>The main advantages of using <code>kqueue</code> or <code>libkqueue</code> is that it's cross platform, and doesn't have the complexity of signal handling. If your program is utilises async I/O you may also find it a lower friction interface than using something like <code>epoll</code> and the various <code>*fd</code> functions (<code>signalfd</code>, <code>eventfd</code>, <code>pidfd</code> etc...).</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdint.h&gt; #include &lt;sys/event.h&gt; /* kqueue header */ #include &lt;sys/types.h&gt; /* for pid_t */ /* Link with -lkqueue */ int waitpid_timeout(pid_t pid, struct timespec *timeout) { struct kevent changelist, eventlist; int kq, ret; /* Populate a changelist entry (an event we want to be notified of) */ EV_SET(&amp;changelist, pid, EVFILT_PROC, EV_ADD, NOTE_EXIT, 0, NULL); kq = kqueue(); /* Call kevent with a timeout */ ret = kevent(kq, &amp;changelist, 1, &amp;eventlist, 1, timeout); /* Kevent returns 0 on timeout, the number of events that occurred, or -1 on error */ switch (ret) { case -1: printf(&quot;Error %s\n&quot;, strerror(errno)); break; case 0: printf(&quot;Timeout\n&quot;); break; case 1: printf(&quot;PID %u exited, status %u\n&quot;, (unsigned int)eventlist.ident, (unsigned int)eventlist.data); break; } close(kq); return ret; } </code></pre> <p>Behind the scenes on Linux <code>libkqueue</code> <a href="https://github.com/mheily/libkqueue/blob/master/src/linux/proc.c" rel="nofollow noreferrer">uses either pidfd</a> on Linux kernels &gt;= 5.3 or a <a href="https://github.com/mheily/libkqueue/blob/master/src/posix/proc.c" rel="nofollow noreferrer">waiter thread</a> that listens for <code>SIGCHLD</code> and notifies one or more <code>kqueue</code> instances when a process exits. The second approach is not efficient (it scans PIDs that interest has been registered for using <code>waitid</code>), but that doesn't matter unless you're waiting on large numbers of PIDs.</p> <p><code>EVFILT_PROC</code> support has been included in <code>kqueue</code> since its inception, and in <code>libkqueue</code> since <code>v2.5.0</code>.</p>
35,728
<p>Today, everytime I try to open any <strong>.Net application</strong> I get:</p> <pre><code>CLR error: 80004005 The program will now terminate. </code></pre> <p>Any suggestions?</p>
<p>I'd start with <a href="http://msdn.microsoft.com/en-us/netframework/aa569263.aspx" rel="noreferrer">downloading</a> and re-installing the .NET framework.</p>
<p>A quick search suggests this:</p> <blockquote> <p>"If you get a Run-time error 80131522 "No Server registered or could not load class for CLSID ...", it is because you are trying to run the VB executable from a directory other than where the .NET assembly is located. This also happens if you try to run the vb code in interactive mode. This can be solved by installing the .NET assembly into the global application cache"</p> </blockquote> <p>(<a href="http://bytes.com/forum/thread353655.html" rel="nofollow noreferrer">http://bytes.com/forum/thread353655.html</a>)</p> <p>In an ASP.NET context, it appears this is related to file permissions:</p> <blockquote> <p>The error code for the failure is 80004005. This error can be caused when the worker process account has insufficient rights to read the .NET Framework files. Please ensure</p> </blockquote> <p>(<a href="http://weblogs.asp.net/jambrose/archive/2004/09/01/224226.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/jambrose/archive/2004/09/01/224226.aspx</a>)</p>
31,994
<p>I notice that StackOverflow has a views count for each question and that these view numbers are fairly low and accurate. </p> <p>I have a similar thing on one of my sites. It basically logs a "hit" whenever the page is loaded in the backend code. Unfortunately it also does this for search engine hits giving bloated and inaccurate numbers.</p> <p>I guess one way to not count a robot would be to do the view counting with an AJAX call once the page has loaded, but I'm sure there's other, better ways to ignore search engines in your hit counters whilst still letting them in to crawl your site. Do you know any?</p>
<p>An AJAX call will do it, but usually search engines will not load images, javascript or CSS files, so it may be easier to include one of those files in the page, and pass the URL of the page you want to log a request against as a parameter in the file request.</p> <p>For example, in the page...</p> <p><a href="http://www.example.com/example.html" rel="noreferrer">http://www.example.com/example.html</a></p> <p>You might include in the head section</p> <pre><code>&lt;link href="empty.css?log=example.html" rel="stylesheet" type="text/css" /&gt; </code></pre> <p>And have your server side log the request, then return an empty css file. The same approach would apply to JavaScript or and image file, though in all cases you'll want to look carefully at what caching might take place.</p> <p>Another option would be to eliminate the search engines based on their <a href="http://en.wikipedia.org/wiki/User_agent" rel="noreferrer">user agent</a>. There's a big list of possible user agents at <a href="http://user-agents.org/" rel="noreferrer">http://user-agents.org/</a> to get you started. Of course, you could go the other way, and only count requests from things you know are web browsers (covering IE, Firefox, Safari, Opera and this newfangled Chrome thing would get you 99% of the way there).</p> <p>Even easier would be to use a log analytics tool like <a href="http://awstats.sourceforge.net/" rel="noreferrer">awstats</a> or a service like <a href="http://www.google.com/analytics/" rel="noreferrer">Google analytics</a>, both of which have already solved this problem.</p>
<p>The reason Stack Overflow has accurate view counts is that it only count each view/user once.</p> <p>Third-party hit counter (and web statistics) application often filter out search engines and display them in a separate window/tab/section. </p>
6,783
<p>In CFEclipse, I do a lot of double-clicking to select text. The standard behavior is to select all text within the nearest <em>word boundaries</em>. This is problematic when editing code where the original editor didn't use camel-case; for example, they wrote "myObject" as "my_object".</p> <p>Is there a way to change the double-click selection behavior to include '_' as a valid <em>word</em> character?</p>
<p>CFEclipse does not recognize either the underscore or a period as a character for selecting text with a double-click. There is no way that I know of other than rolling your sleeves up and hacking the editor code to change it. I doubt that this will be changed any time soon with the impending release of Bolt from Adobe.</p>
<p>On eclipse 3.4.1 Ganymede, it seems to select the nearest boundaries <em>including</em> the '_' (at least in the java file I am using)</p> <p>What eclipse version are you using ?</p> <p>This <a href="http://blog.jonschneider.com/2008/07/don-treat-underscore-as-word-separator.html" rel="nofollow noreferrer">blog</a> even reports that eclipse3.3 does select word as you are expecting it...</p> <p><img src="https://i.stack.imgur.com/gRC0h.jpg" alt="Notepad2"> vs. <img src="https://i.stack.imgur.com/FeN1L.jpg" alt="FireFox"></p>
38,340
<p>What is the difference between a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Locator" rel="noreferrer"><strong>URL</strong></a>, a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Identifier" rel="noreferrer"><strong>URI</strong></a>, and a <a href="http://en.wikipedia.org/wiki/Uniform_Resource_Name" rel="noreferrer"><strong>URN</strong></a>?</p>
<p>From <a href="http://www.ietf.org/rfc/rfc3986.txt" rel="noreferrer">RFC 3986</a>:</p> <blockquote> <p>A URI can be further classified as a locator, a name, or both. The term &quot;Uniform Resource Locator&quot; (URL) refers to the subset of URIs that, in addition to identifying a resource, provide a means of locating the resource by describing its primary access mechanism (e.g., its network &quot;location&quot;). The term &quot;Uniform Resource Name&quot; (URN) has been used historically to refer to both URIs under the &quot;urn&quot; scheme <a href="https://www.ietf.org/rfc/rfc2141.txt" rel="noreferrer">[RFC2141]</a>, which are required to remain globally unique and persistent even when the resource ceases to exist or becomes unavailable, and to any other URI with the properties of a name.</p> </blockquote> <p>So all URLs are URIs, and all URNs are URIs - but URNs and URLs are different, so you can't say that all URIs are URLs.</p> <p>If you haven't already read <a href="https://stackoverflow.com/a/1984225/22656">Roger Pate's answer</a>, I'd advise doing so as well.</p>
<p>Don't forget URNs. URIs and URLs are both URNs. URLs have a location:</p> <pre><code>URI: foo URL: http://some.domain.com/foo URL: http://some.domain.com:8080/foo URL: ftp://some.domain.com/foo </code></pre> <p>They're all URNs. </p>
21,233
<p>Whats the best way to detect collisions in a 2d game sprites? I am currently working in allegro and G++</p>
<p>There are a plethora of ways to detect collision detection. The methods you use will be slightly altered if depending on if your using a 2d or 3d environment. Also remember when instituting a collision detection system, to take into account any physics you may want to implement in the game (needed for most descent 3d games) in order to enhance the reality of it. </p> <p>The short version is to use bounding boxes. Or in other words, make each entity in the world a box, then check if each of the axises of the box are colliding with other entities. </p> <p>With large amounts of entities to test for collisions you may want to check into an octree. You would simple divide the world into sectors, then only check for collision between objects in the same sectors.</p> <p>For more resources, you can go to sourceforge and search for the Bullet dynamics engine which is an open source collision detection and physics engine, or you could check out <a href="http://www.gamedev.net" rel="nofollow noreferrer">http://www.gamedev.net</a> which has plenty of resources on copious game development topics.</p>
<p>Collisions between what? It depends whether you use sprites, concave polygons, convex polygons, rectangles, squares, circles, points...</p>
12,398
<p>I'm writing an <code>RSS</code> to <code>JSON parser</code> and as a part of that, I need to use <code>htmlentities()</code> on any tag found inside the description tag. Currently, I'm trying to use <code>preg_replace()</code>, but I'm struggling a little with it. My current (non-working) code looks like:</p> <pre><code>$pattern[0] = "/\&lt;description\&gt;(.*?)\&lt;\/description\&gt;/is"; $replace[0] = '&lt;description&gt;'.htmlentities("$1").'&lt;/description&gt;'; $rawFeed = preg_replace($pattern, $replace, $rawFeed); </code></pre> <p>If you have a more elegant solution to this as well, please share. Thanks.</p>
<p>Simple. Use <code>preg_replace_callback</code>:</p> <pre><code>function _handle_match($match) { return '&lt;description&gt;' . htmlentities($match[1]) . '&lt;/description&gt;'; } $pattern = "/\&lt;description\&gt;(.*?)\&lt;\/description\&gt;/is"; $rawFeed = preg_replace_callback($pattern, '_handle_match', $rawFeed); </code></pre> <p>It accepts any callback type, so also methods in classes.</p>
<p>The more elegant solution would be to employ <a href="http://php.net/simplexml" rel="nofollow noreferrer">SimpleXML</a>. Or a third party library such as <a href="http://pear.php.net/package/XML_Feed_Parser" rel="nofollow noreferrer">XML_Feed_Parser</a> or <a href="http://framework.zend.com/manual/en/zend.feed.html" rel="nofollow noreferrer">Zend_Feed</a> to parse the feed.</p> <p>Here is a SimpleXML example:</p> <pre><code>&lt;?php $rss = file_get_contents('http://rss.slashdot.org/Slashdot/slashdot'); $xml = simplexml_load_string($rss); foreach ($xml-&gt;item as $item) { echo "{$item-&gt;description}\n\n"; } ?&gt; </code></pre> <p>Keep in mind that RSS and RDF and Atom look different, which is why it can make sense to employ one of the above libraries I mentioned.</p>
15,616
<p>How do I perform a database transaction where I create a new record then make a call to a web service using the new record ID returned from the database which will also manipulate the same database? I could obviously update all tables directly from the same SQLConnection object but the logic within the web service call is subject to change and I really need to ensure that the changes my code makes are committed alongside those changes introduced by the called web service.</p>
<p>If the web service has the responsibility to manipulate the database, I would extend the web service to perform the actions that your code is doing. The point of using the web service is (ought to be) to separate your code from having to deal with the database directly. Introducing direct DB manipulation into your code is just going to make things much more convoluted and harder to maintain.</p>
<p>This isn't something that you want in an actual transaction. Transactions should be as short as possible, which means no user interaction in the middle of it or in this case waiting for a web service to respond.</p> <p>As to your problem,if you have control of the web service then change the web service to make a stored procedure call that performs the whole transaction. If there are actions that MUST be completed every time the service is called then they should be part of the service.</p> <p>My guess is that you don't have control over the web service though, or this wouldn't be an issue. How is the web service accessing the database? If it's using a stored procedure already then you should be able to add the necessary logic in there. Again, I'm guessing that's not the case or it wouldn't have been a problem. My suggestion is that you try to change the web service to fit that architecture if at all possible.</p> <p>Assuming that the web service accesses tables directly (yuck), you will need to put code into your calling code that does the insert, calls the web service, then checks to see if the web service did what it was supposed to do, and if it didn't then your code takes the necessary actions to undo everything. It's basically like a home-grown transaction engine. It's also very messy and tends to be bug-prone and difficult to maintain. Not to mention, it's not 100% full proof.</p>
23,259
<p>Greetings!</p> <p>I have a DropDownList within a FormView which are bound to XmlDataSources:</p> <pre><code>&lt;asp:FormView ID="MyFormView" runat="server" DataSourceID="MyXmlDataSource"&gt; &lt;ItemTemplate&gt; &lt;h1&gt;&lt;%# XPath("SomeNode")%&gt;&lt;/h1&gt; &lt;asp:Label ID="MyLabel" runat="server" AssociatedControlID="MyDdl" Text='&lt;%# XPath("SomeOtherNode")%&gt;' /&gt; &lt;asp:DropDownList ID="MyDdl" runat="server" DataSourceID="MyDdlDataSource" DataTextField="name" DataValueField="value" AutoPostBack="true" OnSelectedIndexChanged="MyDdl_SelectedIndexChanged"&gt; &lt;/asp:DropDownList&gt; &lt;/ItemTemplate&gt; &lt;/asp:FormView&gt; &lt;asp:XmlDataSource ID="MyXmlDataSource" runat="server" XPath="Root/MainSection" /&gt; &lt;asp:XmlDataSource ID="MyDdlDataSource" runat="server" XPath="Root/MainSection/Areas/*" /&gt; </code></pre> <p>In the page's codebehind, I have the following OnLoad() method as well as the method for getting the selected value dropdownlist during postback:</p> <pre><code>private m_key; protected override void OnLoad(EventArgs e) { base.OnLoad(e); string xml_data; if (!IsPostBack) { xml_data = GetMyXml(0); // default value MyXmlDataSource.Data = xml_data; MyDdlDataSource.Data = xml_data; } else { GetSelections(); xml_data = GetMyXml(m_key); MyXmlDataSource.Data = xml_data; MyXmlDataSource.DataBind(); } } private void GetSelections() { DropDownList l_MyDdl = FindMyControl&lt;DropDownList&gt;("MyDdl"); if (l_MyDdl != null) if (!Int32.TryParse(l_MyDdl.SelectedItem.Value, out m_key)) m_key = 0; } </code></pre> <p>Everything works great, up until a postback as a result of the dropdown list changing occurs. When this happens, I get the value of the selected item in the dropdown list, pass it to my GetMyXml() method with the value from the dropdown list as a parameter and then set the FormView's datasource to the newly returned XML data from GetMyXml(). I've looked at the value of "xml_data" during postback and it's definitely correct. However, the values displayed on the page the FormView (like XPath("SomeNode")) are the values from before the postback happened and not the ones returned in xml_data. Why would this happen and how would I go about resolving it? Thanks in advance.</p>
<p>in order to automatically rebind you must have the ViewState enabled on that control.</p>
<p>You could try <code>MyFormView.DataBind()</code> after <code>MyXmlDataSource.DataBind();</code></p>
46,711
<p>I've tried several things already,</p> <pre><code>std::stringstream m; m.empty(); m.clear(); </code></pre> <p>both of which don't work.</p>
<p>For all the standard library types the member function <code>empty()</code> is a query, not a command, i.e. it means "are you empty?" not "please throw away your contents".</p> <p>The <code>clear()</code> member function is inherited from <code>ios</code> and is used to clear the error state of the stream, e.g. if a file stream has the error state set to <code>eofbit</code> (end-of-file), then calling <code>clear()</code> will set the error state back to <code>goodbit</code> (no error).</p> <p>For clearing the contents of a <code>stringstream</code>, using:</p> <pre><code>m.str(""); </code></pre> <p>is correct, although using:</p> <pre><code>m.str(std::string()); </code></pre> <p>is technically more efficient, because you avoid invoking the <code>std::string</code> constructor that takes <code>const char*</code>. But any compiler these days should be able to generate the same code in both cases - so I would just go with whatever is more readable.</p>
<p>These do not discard the data in the stringstream in gnu c++</p> <pre><code> m.str(""); m.str() = ""; m.str(std::string()); </code></pre> <p>The following does empty the stringstream for me:</p> <pre><code> m.str().clear(); </code></pre>
4,106
<p><a href="http://www.python.org/doc/2.5.2/lib/module-tempfile.html" rel="noreferrer">tempfile.mkstemp()</a> returns:</p> <blockquote> <p>a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order.</p> </blockquote> <p>How do I convert that OS-level handle to a file object?</p> <p>The <a href="http://www.python.org/doc/2.5.2/lib/os-fd-ops.html" rel="noreferrer">documentation for os.open()</a> states: </p> <blockquote> <p>To wrap a file descriptor in a "file object", use fdopen().</p> </blockquote> <p>So I tried:</p> <pre><code>&gt;&gt;&gt; import tempfile &gt;&gt;&gt; tup = tempfile.mkstemp() &gt;&gt;&gt; import os &gt;&gt;&gt; f = os.fdopen(tup[0]) &gt;&gt;&gt; f.write('foo\n') Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in ? IOError: [Errno 9] Bad file descriptor </code></pre>
<p>You can use </p> <pre><code>os.write(tup[0], "foo\n") </code></pre> <p>to write to the handle.</p> <p>If you want to open the handle for writing you need to add the <strong>"w"</strong> mode</p> <pre><code>f = os.fdopen(tup[0], "w") f.write("foo") </code></pre>
<p>I can't comment on the answers, so I will post my comment here:</p> <p>To create a temporary file for write access you can use tempfile.mkstemp and specify "w" as the last parameter, like:</p> <pre><code>f = tempfile.mkstemp("", "", "", "w") # first three params are 'suffix, 'prefix', 'dir'... os.write(f[0], "write something") </code></pre>
20,349
<p>Can someone explain when to use each of these? They almost seem interchangeable in many cases. </p> <p>The Custom Control gets added to the toolbar while the User Control (ascx) can not. The Custom Control does not get rendered in the Designer while the User Control does. Beyond that, how do you choose which is the right one to use? </p> <p>Also, I am looking for the best way to access the controls from JavaScript (GetElementById). So, a point in the right direction for adding client side support would be great.</p>
<p>This is from Microsoft's site:</p> <p><strong>Web user controls</strong> </p> <ul> <li>Easier to create</li> <li>Limited support for consumers who use a visual design tool</li> <li>A separate copy of the control is required in each application</li> <li>Cannot be added to the Toolbox in Visual Studio</li> <li>Good for static layout</li> </ul> <p><strong>Web custom controls</strong> </p> <ul> <li>Harder to create</li> <li>Full visual design tool support for consumers</li> <li>Only a single copy of the control is required, in the global assembly cache</li> <li>Can be added to the Toolbox in Visual Studio</li> <li>Good for dynamic layout</li> </ul> <p><a href="http://msdn.microsoft.com/en-us/library/aa651710(VS.71).aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/aa651710(VS.71).aspx</a></p>
<p>For accessing them from JavaScript, you should use <code>document.GetElementById('&lt;%=TheControl.ClientID%&gt;')</code>.<br> The difference between a web control and a user control is that a user control has the ascx file with the html definition while the web control does not; that is the cause for other differences. Also, for user controls you can't use <code>new Control()</code>, you need to use <code>LoadControl</code> instead because that loads the .ascx.<br> For simple controls that inherit from .Net controls, like a text box with validation or something like that, I tend to use web controls; for more complex controls with html and inner controls I tend to use user controls. But it's basically your personal preference. </p>
14,150
<p>I'm referring to distinctions such as in <a href="https://stackoverflow.com/questions/17231/why-shouldnt-i-bet-the-future-of-the-company-on-shell-scripts#92305">this answer</a>:</p> <blockquote> <p>...bash isn't for writing applications it's for, well, scripting. So sure, your application might have some housekeeping scripts but don't go writing <code>critical-business-logic.sh</code> because another language is probably better for stuff like that.</p> </blockquote> <p>As programmer who's worked in many languages, this seems to be C, Java and other compiled language snobbery. I'm not looking for reenforcement of my opinion or hand-wavy answers. Rather, I genuinely want to know what technical differences are being referred to.</p> <p>(And I use C in my day job, so I'm not just being defensive.)</p>
<p>Traditionally a program is compiled and a script is interpreted, but that is not really important anymore. You can generate a compiled version of most scripts if you really want to, and other 'compiled' languages like Java are in fact interpreted (at the byte code level.)</p> <p>A more modern definition might be that a program is intended to be used by a customer (perhaps an internal one) and thus should include documentation and support, while a script is primarily intended for the use of the author.</p> <p>The web is an interesting counter example. We all enjoy looking things up with the Google search engine. The bulk of the code that goes into creating the 'database' it references is used only by its authors and maintainers. Does that make it a script?</p>
<p>A scripting language doesn't have a standard library or platform (or not much of one). It's small and light, designed to be embedded into a larger application. Bash and Javascript are great examples of scripting languages because they rely absolutely on other programs for their functionality.</p> <p>Using this definition, a script is code designed to drive a larger application (suite). A Javascript might call on Firefox to open windows or manipulate the DOM. A Bash script executes existing programs or other scripts and connects them together with pipes.</p> <hr> <p>You also ask why not scripting languages, so:</p> <p>Are there even any unit-testing tools for scripting languages? That seems a very important tool for "real" applications that is completely missing. And there's rarely any real library bindings for scripting languages.</p> <p>Most of the times, scripts could be replaced with a real, light language like Python or Ruby anyway.</p>
12,373
<p>I Have created an SSRS Report for retrieving 55000 records using a Stored Procedure. When executing from the Stored Proc it is taking just 3 seconds but when executing from SSRS report it is taking more than one minute. How can I solve this problem?</p>
<p>The additional time could be due to Reporting Services rendering the report in addition to querying the data. For example if you have 55,000 rows returned for the report and the report server then has to group, sort and/or filter those rows to render the report then that could take additional time.</p> <p>I would have a look at the way the data is being grouped and filtered in the report, then review your stored procedure to see if you could offload some of that processing to the SQL code, maybe using some parameters. Try and aim to reduce the the amount of rows returned to the report to be the minimum needed to render the report and preferably try to avoid doing the grouping and filtering in the report itself.</p>
<p>Obviously getting the report running correctly (i.e. taking the same order of magnitude of time to select the data as SSMS) would be preferable but as a work around, would your report support execution snapshots (i.e. no parameters, or parameter defaults stored in the report)?</p> <p>This will allow a scheduled snapshot of the data to be retrieved and stored beforehand, meaning SSRS only needs to process and render the report when the user opens it. Should reduce the wait down to a few seconds (depending on what processing the report requires. YMMV, test to see if you get a performance improvement). </p> <p>Go to the report's properties tab in Report manager, select Execution, change to Render this report from a report execution snapshot, specify your schedule.</p>
44,216
<p><a href="http://www.capify.org/" rel="noreferrer">Capistrano</a> is a great solution for building scripts that automatically deploy a website and/or a database. But, it's also very *nix centric, and from I've read it would probably be more trouble than it's worth to get it working with a Windows server. Is there a similar solution that would allow me to deploy an ASP.Net website to an IIS server and a SQL Server database? </p> <p>What I'm looking for is something that would allow the same kind of flexibility that Capistrano allows, as far customizing how I want the site to be deployed, what version control system I want to pull from, how it will handle rollbacks to a previous version of a site, etc. So far, I haven't been able to find a free solution that has the same sort of functionality that Capistrano has. </p>
<p>We use msi files created by Setup Factory. It pretty much allows you to put any setup parameters you need. We are also staring to use AntHill Pro which is probably more inline with what you are looking for, but it is a lot of money.</p> <p>Everything in IIS can be modified by vb scripts. As far as going the free route that is probably the cheapest. I am sure you can use this in combination with batch files and a little custom programming and you can deploy what ever you need to iis and sql server.</p>
<p>I don't know about something with as many features as Capistrano, but there's good old <a href="http://nant.sourceforge.net/" rel="nofollow noreferrer">nant</a></p>
28,724
<p>How can I resize an image, with the image quality unaffected?</p>
<p>As <a href="https://stackoverflow.com/questions/87753/resizing-an-image-without-losing-any-quality#87763">rcar</a> says, you can't without losing some quality, the best you can do in c# is:</p> <pre><code>Bitmap newImage = new Bitmap(newWidth, newHeight); using (Graphics gr = Graphics.FromImage(newImage)) { gr.SmoothingMode = SmoothingMode.HighQuality; gr.InterpolationMode = InterpolationMode.HighQualityBicubic; gr.PixelOffsetMode = PixelOffsetMode.HighQuality; gr.DrawImage(srcImage, new Rectangle(0, 0, newWidth, newHeight)); } </code></pre>
<p>Here is a <a href="http://forums.asp.net/t/1038068.aspx" rel="nofollow noreferrer">forum thread</a> that provides a C# image resizing code sample. You could use one of the <a href="http://www.libgd.org/Binders" rel="nofollow noreferrer">GD library</a> binders to do resampling in C#.</p>
11,332
<p>how do you go about saving images and displaying them from a SQL Server Image field when using ASP.NET MVC?</p> <p>Many thanks Nick</p>
<p>The MvcFutures <a href="http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=18459" rel="nofollow noreferrer">http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=18459</a> project has a FileResult which is a type of ActionResult. You could probably use that to return a binary stream to the browser.</p>
<p>You can also do this pretty simply yourself with a controller action:</p> <pre><code>public void RenderImage(int imageId) { // TODO: Replace this with your API to get the image blob data. byte[] data = this.repo.GetImageData(imageId); if (data != null) { // This assumes you're storing JPEG data Response.ContentType = "image/jpeg"; Response.Expires = 0; Response.Buffer = true; Response.Clear(); Response.BinaryWrite(data); } else { this.ControllerContext.HttpContext.ApplicationInstance.CompleteRequest(); } } </code></pre>
33,278
<p>I have a web application that should behave differently for internal users than external ones. The web application is available over the Internet, and therefore obviously to the internal users as well.</p> <p>All the users are anonymous, not authenticated, but the page should render differently for internal users than external. What I'm doing in my code is use <code>Request.UserHostName</code> and then <code>Dns.GetHostEntry</code>. The result is then compared to a setting in my <code>web.config</code> (that holds something like <code>*.mydomain.local</code>) . If the comparison gives a positive result then I render the HTML that the internal user should see otherwise I render the HTML the external user should see.</p> <p>However, my problem is that I don't always get the expected value from <code>Request.UserHostName</code>. on the development site I get the <code>IP-number</code> (?) of the machine running the browser but on the customer site I don't get the <code>IP-number</code> of the user machine, I get some other <code>IP-number</code>. The browsers don't have any proxies set or anything like that.</p> <p>Should I be using something else than <code>Request.UserHostName</code>?</p>
<p>I recommend using IP addresses as well. I'm dealing with this exact same situation setting up an authentication system right now as well and the conditions described by Epso and Robin M are exactly what is happening. External users coming to the site give me their actual IP address while all internal users provide the IP of the gateway machine(router) on to the private subnet the webservers sit on.</p> <p>To deal with it I just check for that one IP. If I get the IP of the gateway, I provide the internal access. If I get anything else they get the external one which requires additional authentication in my case. In yours, it would just mean a different interface.</p>
<p>There might be a firewall that is doing some sort of NAT, to enable inside clients to use the external dns-name to reach the server.</p> <p>Is the IP-number you get on customer site the same at the external customer-server ip? In that case you can hard code for that one IP-address. All internal computers behind that firewall will appear to have to same ip-address and you can classify them as "internal".</p>
6,748