instruction
stringlengths
21
27.8k
chosen
stringlengths
18
28.2k
rejected
stringlengths
18
33.6k
__index_level_0__
int64
0
50k
<p>I need to do some memory profiling of a .NET Framework application. Should I use a debug or a release build? </p>
<p>A release build, built with debug symbols. </p> <p>That way there's no debug build overhead (like extra memory added after arrays for overrun detection), but you still have the names needed to associate addresses with variables.</p>
<p>You should profile the builds that are causing the problems. I'm assuming you are giving your users a Release build and so that's the one you should profile.</p>
21,231
<p>I want to use an AOP framework, but I have two constraints.</p> <p>Any framework that I choose</p> <ol> <li><p>Must be fairly independent. I plan to use this in a legacy code base, and hence cannot upgrade prospective dependencies like commons-logging-XXX.jar to commons-logging-newest.jar.</p></li> <li><p>Must be fairly well documented, should not be too complex to understand and integrate.</p></li> </ol>
<p><a href="http://www.eclipse.org/aspectj/" rel="nofollow noreferrer">AspectJ</a> as far as I can tell is just a compiler and imposes no dependencies on compiled programs other than including the AspectJ runtime jar. </p> <p>It is also actively maintained, part of the Eclipse project and has a nice development environment (<a href="http://www.eclipse.org/ajdt/" rel="nofollow noreferrer">AJDT</a>, a plugin to Eclipse).</p>
<p>Okay, this one doesn't fit all your requirements, but I think, it's worth a look: <a href="http://dynamicaspects.sourceforge.net/" rel="nofollow noreferrer">http://dynamicaspects.sourceforge.net/</a></p> <p>Positives</p> <ul> <li>No dependencies except needs java 1.5 due to using the JavaAgent </li> <li>No XML markup needed and just works with POJO classes</li> <li>Tried myself and found it very easy to use (not very complex)</li> </ul> <p>Negatives</p> <ul> <li>No more activly maintained afaik</li> <li>Poor documentation</li> <li>You cannot do everything a full fledged AOP framework allows you to do</li> </ul> <p>I tested it out some time ago and was pretty impressed but found some glitches which I don't remember right now. Though you might give it a try.</p> <p>Greetz, GHad</p>
26,858
<p>How do I get the <code>GridView</code> control to render the <code>&lt;thead&gt;</code> <code>&lt;tbody&gt;</code> tags? I know <code>.UseAccessibleHeaders</code> makes it put <code>&lt;th&gt;</code> instead of <code>&lt;td&gt;</code>, but I cant get the <code>&lt;thead&gt;</code> to appear.</p>
<p>This should do it:</p> <pre><code>gv.HeaderRow.TableSection = TableRowSection.TableHeader; </code></pre>
<p>You can also use jQuery to add it. This avoids the problem with TableRowSection.TableHeader where gets dropped on PostBack.</p> <p><code>$('#myTableId').prepend($("&lt;thead&gt;&lt;/thead&gt;").append($(this).find("#myTableId tr:first")));</code></p>
39,826
<p>I'm just about wrapped up on a project where I was using a commercial SVN provider to store the source code. The web host the customer ultimately picked includes a repository as part of the hosting package, so, now that the project is over, I'd like to relocate the repository to their web host and discontinue the commercial account.</p> <p>How would I go about doing this?</p>
<p>If you want to move the repository and keep history, you'll probably need filesystem access on both hosts. The simplest solution, if your backend is FSFS (the default on recent versions), is to make a filesystem copy of the entire repository folder.</p> <p>If you have a Berkley DB backend, if you're not sure of what your backend is, or if you're changing SVN version numbers, you're going to want to use svnadmin to dump your old repository and load it into your new repository. Using <code>svnadmin dump</code> will give you a single file backup that you can copy to the new system. Then you can create the new (empty) repository and use <code>svnadmin load</code>, which will essentially replay all the commits along with its metadata (author, timestamp, etc).</p> <p>You can read more about the dump/load process here:</p> <p><a href="http://svnbook.red-bean.com/en/1.8/svn.reposadmin.maint.html#svn.reposadmin.maint.migrate" rel="noreferrer">http://svnbook.red-bean.com/en/1.8/svn.reposadmin.maint.html#svn.reposadmin.maint.migrate</a></p> <p>Also, if you do <code>svnadmin load</code>, make sure you use the <code>--force-uuid</code> option, or otherwise people are going to have problems switching to the new repository. Subversion uses a UUID to identify the repository internally, and it won't let you switch a working copy to a different repository.</p> <p>If you don't have filesystem access, there may be other third party options out there (or you can write something) to help you migrate: essentially you'd have to use the svn log to replay each revision on the new repository, and then fix up the metadata afterwards. You'll need the pre-revprop-change and post-revprop-change hook scripts in place to do this, which sort of assumes filesystem access, so YMMV. Or, if you don't want to keep the history, you can use your working copy to import into the new repository. But hopefully this isn't the case.</p>
<p>Assuming you have the necessary privileges to run svnadmin, you need to use the <a href="http://svnbook.red-bean.com/en/1.4/svn.ref.svnadmin.c.dump.html" rel="nofollow noreferrer">dump</a> and <a href="http://svnbook.red-bean.com/en/1.4/svn.ref.svnadmin.c.load.html" rel="nofollow noreferrer">load</a> commands.</p>
7,201
<p>What is the best way to get a file (in this case, a .PDF, but any file will do) from a WebResponse and put it into a MemoryStream? Using .GetResponseStream() from WebResponse gets a Stream object, but if you want to convert that Stream to a specific type of stream, what do you do?</p>
<p>There is a serious issue with SoloBold's <a href="https://stackoverflow.com/questions/179676/how-do-i-put-a-webresponse-into-a-memory-stream/179712#179712">answer</a> that I discovered while testing it. When using it to read a file via an <code>FtpWebRequest</code> into a <code>MemoryStream</code> it intermittently failed to read the entire stream into memory. I tracked this down to <code>Peek()</code> sometimes returning -1 after the first 1460 bytes even though a <code>Read()</code> would have succeeded (the file was significantly larger than this). </p> <p>Instead I propose the solution below:</p> <pre><code>MemoryStream memStream; using (Stream response = request.GetResponseStream()) { memStream = new MemoryStream(); byte[] buffer = new byte[1024]; int byteCount; do { byteCount = stream.Read(buffer, 0, buffer.Length); memStream.Write(buffer, 0, byteCount); } while (byteCount &gt; 0); } // If you're going to be reading from the stream afterwords you're going to want to seek back to the beginning. memStream.Seek(0, SeekOrigin.Begin); // Use memStream as required </code></pre>
<p>I found the following at <a href="http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/eeeefd81-8800-41b2-be63-71acdaddce0e/" rel="nofollow noreferrer">http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/eeeefd81-8800-41b2-be63-71acdaddce0e/</a></p> <pre><code> Dim request As WebRequest Dim response As WebResponse = Nothing Dim s As Stream = Nothing Dim fs As FileStream = Nothing Dim file As MemoryStream = Nothing Dim uri As New Uri(String.Format("http://forums.microsoft.com/forums/ShowPost.aspx?PostID=2992978&amp;SiteID=1")) request = WebRequest.Create(uri) request.Timeout = 10000 response = request.GetResponse s = response.GetResponseStream '2 - Receive file as memorystream Dim read(256) As Byte Dim count As Int32 = s.Read(read, 0, read.Length) File = New MemoryStream Do While (count &gt; 0) File.Write(read, 0, count) count = s.Read(read, 0, read.Length) Loop File.Position = 0 'Close responsestream s.Close() response.Close() '3 - Save file fs = New FileStream("c:\test.html", FileMode.CreateNew) count = file.Read(read, 0, read.Length) Do While (count &gt; 0) fs.Write(read, 0, count) count = file.Read(read, 0, read.Length) Loop fs.Close() File.Close() </code></pre>
21,672
<p>I'd like to bind a configuration file to my executable. I'd like to do this by storing an MD5 hash of the file inside the executable. This should keep anyone but the executable from modifying the file.</p> <p>Essentially if someone modifies this file outside of the program the program should fail to load it again.</p> <p>EDIT: The program processes credit card information so being able to change the configuration in any way could be a potential security risk. This software will be distributed to a large number of clients. Ideally client should have a configuration that is tied directly to the executable. This will hopefully keep a hacker from being able to get a fake configuration into place.</p> <p>The configuration still needs to be editable though so compiling an individual copy for each customer is not an option.</p> <hr> <p>It's important that this be dynamic. So that I can tie the hash to the configuration file as the configuration changes.</p>
<p>A better solution is to store the MD5 in the configuration file. But instead of the MD5 being just of the configuration file, also include some secret "key" value, like a fixed guid, in the MD5.</p> <pre><code>write(MD5(SecretKey + ConfigFileText)); </code></pre> <p>Then you simply remove that MD5 and rehash the file (including your secret key). If the MD5's are the same, then no-one modified it. This prevents someone from modifying it and re-applying the MD5 since they don't know your secret key.</p> <p>Keep in mind this is a fairly weak solution (as is the one you are suggesting) as they could easily track into your program to find the key or where the MD5 is stored. </p> <p>A better solution would be to use a public key system and sign the configuration file. Again that is weak since that would require the private key to be stored on their local machine. Pretty much anything that is contained on their local PC can be bypassed with enough effort.</p> <p>If you REALLY want to store the information in your executable (which I would discourage) then you can just try appending it at the end of the EXE. That is usually safe. Modifying executable programs is <em>virus like</em> behavior and most operating system security will try to stop you too. If your program is in the Program Files directory, and your configuration file is in the Application Data directory, and the user is logged in as a non-administrator (in XP or Vista), then you will be unable to update the EXE.</p> <p><strong>Update:</strong> I don't care if you are using Asymmetric encryption, RSA or Quantum cryptography, if you are storing your keys on the user's computer (which you <em>must</em> do unless you route it all through a web service) then the user can find your keys, even if it means inspecting the registers on the CPU at run time! You are only buying yourself a moderate level of security, so stick with something that is simple. To prevent modification the solution I suggested is the best. To prevent reading then encrypt it, and if you are storing your key locally then use AES Rijndael.</p> <p><strong>Update:</strong> The FixedGUID / SecretKey could alternatively be generated at install time and stored somewhere "secret" in the registry. Or you could generate it every time you use it from hardware configuration. Then you are getting more complicated. How you want to do this to allow for moderate levels of hardware changes would be to take 6 different signatures, and hash your configuration file 6 times - once with each. Combine each one with a 2nd secret value, like the GUID mentioned above (either global or generated at install). Then when you check you verify each hash separately. As long as they have 3 out of 6 (or whatever your tolerance is) then you accept it. Next time you write it you hash it with the new hardware configuration. This allows them to slowly swap out hardware over time and get a whole new system. . . Maybe that is a weakness. It all comes down to your tolerance. There are variations based on tighter tolerances.</p> <p><strong>UPDATE:</strong> For a Credit Card system you might want to consider some real security. You should retain the services of a <em>security and cryptography consultant</em>. More information needs to be exchanged. They need to analyze your specific needs and risks. </p> <p>Also, if you want security with .NET you need to first start with a really good .NET obfuscator (<a href="http://www.google.com/search?hl=en&amp;q=.NET%20obfuscator&amp;aq=f&amp;oq=" rel="nofollow noreferrer">just Google it</a>). A .NET assembly is way to easy to disassemble and get at the source code and read all your secrets. Not to sound a like a broken record, but anything that depends on the security of your user's system is fundamentally flawed from the beginning. </p>
<p>just make a const string that holds the md5 hash and compile it into your app ... your app can then just refer to this const string when validating the configuration file</p>
5,554
<p>Had anybody found a way to migrate MediaWiki pages over to WSS Wikis? We just put up Sharepoint 2007 and while it appears to meet our needs, it doesn't appear to be any tool provided by Microsoft to migrate MediaWiki pages over to WSS wikis.</p>
<p>There is no such tool provided by Microsoft at this time.</p> <p>There is one being developed though in the <a href="http://blogs.msdn.com/sharepoint/archive/2007/06/18/community-kit-for-sharepoint-2-0-pre-release-announcement.aspx" rel="nofollow noreferrer">SharePoint Community Kit</a>.</p> <blockquote> <p><strong>Wiki Import/Export Tool</strong></p> <p>The EWE team is at a very early stage of designing an import/export tool for the SharePoint wiki. The goal is for this tool to be able to import from other wiki products such as FlexWiki, MediaWiki, and TWiki, and Confluence and also from Word and OneNote as well as to export to Word via HTML (per page) and MHTML (entire wiki) formats.</p> <p>For this CKS 2.0 pre-release, the EWE team is making available a fairly stable build of the FlexWiki Import Tool, for which the source code was graciously donated by Michael Cheng, a developer in the SharePoint product group. This is a one-off tool that will ultimately be converted to a plug-in for the Wiki Import/Export Tool, so if you’re currently using FlexWiki, please test the tool and provide feedback.</p> </blockquote>
<p>You can't expect even remotely similar functionality from such imported pages. See <a href="http://wikiworks.com/enterprise-mediawiki-vs-sharepoint.html" rel="nofollow noreferrer">http://wikiworks.com/enterprise-mediawiki-vs-sharepoint.html</a> for an explanation of why you might want to reconsider this kind of migration. You will lose 1. reliable infinite versioning and archiving 2. easy multi-author editing 3. all the capabilities of mediawiki extensions, over 2000 at last count.</p> <p>In some businesses, e.g. insurance, law firms or accounting, losing 1. could have legal implications. </p> <p>If your intent however is to simply make pages visible in SharePoint that are maintained in MediaWiki, then, you can do that by configuring SharePoint to search within the mediawiki - addressed by some other questions here on StackExchange.</p>
17,902
<p>If I have a sorted list (say quicksort to sort), if I have a lot of values to add, is it better to suspend sorting, and add them to the end, then sort, or use binary chop to place the items correctly while adding them. Does it make a difference if the items are random, or already more or less in order?</p>
<p>If you add enough items that you're effectively building the list from scratch, you should be able to get better performance by sorting the list afterwards.</p> <p>If items are mostly in order, you can tweak both incremental update and regular sorting to take advantage of that, but frankly, it usually isn't worth the trouble. (You also need to be careful of things like making sure some unexpected ordering can't make your algorithm take much <em>longer</em>, q.v. naive quicksort)</p> <p>Both incremental update and regular list sort are O(N log N) but you can get a better constant factor sorting everything afterward (I'm assuming here that you've got some auxiliary datastructure so your incremental update can access list items faster than O(N)...). Generally speaking, sorting all at once has a lot more design freedom than maintaining the ordering incrementally, since incremental update has to maintain a complete order at all times, but an all-at-once bulk sort does not.</p> <p>If nothing else, remember that there are lots of highly-optimized bulk sorts available.</p>
<p>Inserting an item into a sorted list is O(log n), while sorting a list is O(n log N) Which would suggest that it's always better to sort first and then insert</p> <p>But remeber big 'O' only concerns the scaling of the speed with number of items, it might be that for your application an insert in the middle is expensive (eg if it was a vector) and so appending and sorting afterward might be better.</p>
20,384
<p>I'm going to try to ask my question in the context of a simple example...</p> <p>Let's say I have an abstract base class Car. Car has-a basic Engine object. I have a method StartEngine() in the abstract Car class that delegates the starting of the engine to the Engine object.</p> <p>How do I allow subclasses of Car (like Ferrari) to declare the Engine object as a specific type of engine (e.g., TurboEngine)? Do I need another Car class (TurboCar)?</p> <p>I'm inheriting a plain old Engine object and I cannot re-declare (or override) it as a TurboEngine in my Car subclasses. </p> <p><strong>EDIT:</strong> I understand that I can plug any subclass of Engine into myEngine reference within my Ferrari class...but how can I call methods that only the TurboEngine exposes? Because myEngine is inherited as a base Engine, none of the turbo stuff is included. </p> <p>Thanks!</p>
<p>The Abstract Factory pattern is precisely for this problem. Google GoF Abstract Factory {your preferred language}</p> <p>In the following, note how you can either use the concrete factories to produce "complete" objects (enzo, civic) or you can use them to produce "families" of related objects (CarbonFrame + TurboEngine, WeakFrame + WeakEngine). Ultimately, you always end up with a Car object that responds to accelerate() with type-specific behavior.</p> <hr> <pre><code> using System; abstract class CarFactory { public static CarFactory FactoryFor(string manufacturer){ switch(manufacturer){ case "Ferrari" : return new FerrariFactory(); case "Honda" : return new HondaFactory(); default: throw new ArgumentException("Unknown car manufacturer. Please bailout industry."); } } public abstract Car createCar(); public abstract Engine createEngine(); public abstract Frame createFrame(); } class FerrariFactory : CarFactory { public override Car createCar() { return new Ferrari(createEngine(), createFrame()); } public override Engine createEngine() { return new TurboEngine(); } public override Frame createFrame() { return new CarbonFrame(); } } class HondaFactory : CarFactory { public override Car createCar() { return new Honda(createEngine(), createFrame()); } public override Engine createEngine() { return new WeakEngine(); } public override Frame createFrame() { return new WeakFrame(); } } abstract class Car { private Engine engine; private Frame frame; public Car(Engine engine, Frame frame) { this.engine = engine; this.frame = frame; } public void accelerate() { engine.setThrottle(1.0f); frame.respondToSpeed(); } } class Ferrari : Car { public Ferrari(Engine engine, Frame frame) : base(engine, frame) { Console.WriteLine("Setting sticker price to $250K"); } } class Honda : Car { public Honda(Engine engine, Frame frame) : base(engine, frame) { Console.WriteLine("Setting sticker price to $25K"); } } class KitCar : Car { public KitCar(String name, Engine engine, Frame frame) : base(engine, frame) { Console.WriteLine("Going out in the garage and building myself a " + name); } } abstract class Engine { public void setThrottle(float percent) { Console.WriteLine("Stomping on accelerator!"); typeSpecificAcceleration(); } protected abstract void typeSpecificAcceleration(); } class TurboEngine : Engine { protected override void typeSpecificAcceleration() { Console.WriteLine("Activating turbo"); Console.WriteLine("Making noise like Barry White gargling wasps"); } } class WeakEngine : Engine { protected override void typeSpecificAcceleration() { Console.WriteLine("Provoking hamster to run faster"); Console.WriteLine("Whining like a dentist's drill"); } } abstract class Frame { public abstract void respondToSpeed(); } class CarbonFrame : Frame { public override void respondToSpeed() { Console.WriteLine("Activating active suspension and extending spoilers"); } } class WeakFrame : Frame { public override void respondToSpeed() { Console.WriteLine("Loosening bolts and vibrating"); } } class TestClass { public static void Main() { CarFactory ferrariFactory = CarFactory.FactoryFor("Ferrari"); Car enzo = ferrariFactory.createCar(); enzo.accelerate(); Console.WriteLine("---"); CarFactory hondaFactory = CarFactory.FactoryFor("Honda"); Car civic = hondaFactory.createCar(); civic.accelerate(); Console.WriteLine("---"); Frame frame = hondaFactory.createFrame(); Engine engine = ferrariFactory.createEngine(); Car kitCar = new KitCar("Shaker", engine, frame); kitCar.accelerate(); Console.WriteLine("---"); Car kitCar2 = new KitCar("LooksGreatGoesSlow", hondaFactory.createEngine(), ferrariFactory.createFrame()); kitCar2.accelerate(); } } </code></pre>
<p>There are lots of ways it could be done. </p> <p>I would favour having a <code>setEngine()</code> method on <code>Car</code>, then having the <code>Ferrari</code> constructor call <code>setEngine()</code> and pass in an instance of a <code>TurboEngine</code>.</p>
35,261
<p>For those of you who are decent with subsonic!</p> <pre><code> TblNewsCollection col = new Select().From(Tables.TblNews) .InnerJoin(Tables.TblContent) .Paged(currentPage, pageSize) .OrderDesc(TblContent.Columns.PubDate) .ExecuteAsCollection&lt;TblNewsCollection&gt;(); </code></pre> <p>The above works, no problem, but when I try to add a where clause</p> <pre><code> TblNewsCollection col = new Select().From(Tables.TblNews) .InnerJoin(Tables.TblContent) .Where(TblContent.Columns.UserFK) .IsEqualTo(guidUserFK) .Paged(currentPage, pageSize) .OrderDesc(TblContent.Columns.PubDate) .ExecuteAsCollection&lt;TblNewsCollection&gt;(); </code></pre> <p>I get this message</p> <pre><code>System.InvalidCastException: Object must implement IConvertible. at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider) at System.Data.SqlClient.SqlParameter.CoerceValue(Object value, MetaType destinationType) System.InvalidCastException: Failed to convert parameter value from a Guid to a String. </code></pre> <p>I've tried it from other fields, for example a bit field in a database it says it can't convert from bool to bit!</p> <p>Seems to only be an issue on where statements after joins</p>
<p>I found that joins work better using the TableColumnSchema as in the above Northwind example as opposed to the column name.</p>
<pre><code>Northwind.CustomerCollection customersByCategory = new Select() .From(Northwind.Customer.Schema) .InnerJoin(Northwind.Order.Schema) .InnerJoin(Northwind.OrderDetail.OrderIDColumn, Northwind.Order.OrderIDColumn) .InnerJoin(Northwind.Product.ProductIDColumn, Northwind.OrderDetail.ProductIDColumn) .Where("CategoryID").IsEqualTo(5) .ExecuteAsCollection&lt;Northwind.CustomerCollection&gt;(); </code></pre> <p>There's an example that supposedly works. If that helps anyone help me!</p>
38,231
<p>I have two routes I want mapped in my ASP.NET MVC application</p> <ol> <li>/User/Login</li> <li>/User/{userid}/{username}/{action} (e.g. /User/1/blah/profile)</li> </ol> <p>Here are the routes I've defined: </p> <pre><code> routes.MapRoute( "Profile", "Users/{userID}/{username}/{action}", new { controller = "Users", action = "Profile" } ); routes.MapRoute( "Default", "{controller}/{action}/{id}", new { controller = "Home", action = "Index", id = "" } ); </code></pre> <p>This works great so far in most instances. The following URLs work from my home page:</p> <pre><code>&lt;%= Html.ActionLink((UsersController x) =&gt; x.Login(), "Login") %&gt; &lt;%= Html.ActionLink((UsersController x) =&gt; x.Profile(1, "blah") %&gt; </code></pre> <p>These map to (respectfully):</p> <p>/Users/Login /Users/1/blah</p> <p>However, once I've navigated to /Users/1/blah, the login url immediately turns to /Users/1/blah/login. Any idea how to fix this?</p>
<p>You want to use <code>&lt;%=Html.RouteLink%&gt;</code></p> <p>This is very similar to the <a href="https://stackoverflow.com/questions/323572/asp-mvc-routing-with-1-parameter">problem I had which you can view here</a></p>
<p>is your route hitting an Authorize filter? Is there a requirement to be logged in to view the /Users/1/blah page? (ie. is there an [Authorize] attribute on the UsersController class, or on the Profile Action?)</p> <p>well then, if it is not an Authorize filter, I <em>highly</em> suggest you implement this <a href="http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx" rel="nofollow noreferrer">Routing Debugger Tool</a> into your project.</p>
48,614
<p>The title is a bit abstract so maybe it is easier to explain with a specific example:</p> <p>I find it useful to have my exception classes take an enum parameter instead of a string message. </p> <pre><code>throw new SpecificException(SpecificExceptionCode.ThisThingWentWrong); </code></pre> <p>There are few reasons for this, including:</p> <ul> <li>I can encapulate all the logic for accessing localized string resources in one place</li> <li>I can easily make sure I have string resources for all my exception messages</li> <li>Checking for correct exception messages in unit tests is simpler</li> </ul> <p>I would like to write a base class for this type of exception. Derived exception classes generally just want to provide their own System.Resources.ResourceManager but may also provide additional constructors. The trouble comes because I can only call static methods in calls to base class constructors. This leads me to something like:</p> <pre><code>public abstract class BaseException : ApplicationException { protected static ResourceManager m_resources; public BaseException(System.Enum errorCode, params object[] messageArgs) : base(ProcessError(errorCode, messageArgs)) {} private static string ProcessError(Enum errorCode, params object[] messageArgs) { string errorMessage = m_resources.GetString(errorCode.ToString()); // Handling of messageArgs and trace logging // .... return finalError; } } </code></pre> <p>and </p> <pre><code>public class SpecificException : BaseException { static SpecificException() { m_resources = //.. Get an appropriate resource manager instance } public SpecificException(SpecificExceptionCode errorCode, params object[] messageArgs) : base(errorCode, messageArgs) {} } </code></pre> <p>This works, but I am unhappy with it as there is no compile time hint that the derived class must provide its own <code>System.ResourceManager</code>. I would like to have a base class such as:</p> <pre><code>public abstract class BaseException : ApplicationException { protected abstract static ResourceManager Resources{get;} public BaseException(System.Enum errorCode, params object[] messageArgs) : base(ProcessError(errorCode, messageArgs)) {} private static string ProcessError(Enum errorCode, params object[] messageArgs) { string errorMessage = Resources.GetString(errorCode.ToString()); // Handling of messageArgs and trace logging // .... return finalError; } } </code></pre> <p>...but I cannot have an abstract static method. Is there a better way?</p>
<p>Your current code is broken... there is only one static field; the last static ctor to execute wins.</p> <p>Re using a non-static method - note that calling virtual/abstract methods in a constructor is a bit dangerous - the concrete class won't have initialized yet, so the override could attempt to use data that isn't yet available.</p> <p>Can ResourceManager not be an argument to the base-constructor? If they pass null, you use a sensible default... ProcessError would then accept a ResourceManager, etc.</p> <pre><code>public abstract class BaseException : ApplicationException { static ResourceManager defaultManager; static ResourceManager DefaultManager { get { if (defaultManager == null) defaultManager = TODO; // sensible default return defaultManager; } } public BaseException(System.Enum errorCode, params object[] messageArgs) : this(DefaultManager, errorCode, messageArgs) {} public BaseException(ResourceManager resourceManager, System.Enum errorCode, params object[] messageArgs) : base(ProcessError(resourceManager, errorCode, messageArgs)) { } private static string ProcessError(ResourceManager resourceManager, Enum errorCode, params object[] messageArgs) { if (resourceManager == null) throw new ArgumentNullException("resourceManager"); string errorMessage = resourceManager.GetString(errorCode.ToString()); // Handling of messageArgs and trace logging // .... return finalString; } } </code></pre> <p>and:</p> <pre><code>public class SpecificException : BaseException { static ResourceManager customManager; static SpecificException() { customManager = //TODO - init manager } public SpecificException(SomeEnum errorCode, params object[] messageArgs) : base(customManager, errorCode, messageArgs) { } } </code></pre> <p>Classes that don't want to provide their own manager just use the other ctor:</p> <pre><code>: base(errorCode, messageArgs) </code></pre>
<p>Why does it have to be a static property? You can make the Resources normal property:</p> <pre><code>protected abstract static ResourceManager Resources{get;} </code></pre> <p>and just leave it for the implementer to implement it to return a static object:</p> <pre><code>private static ResourceManager resources = .... protected override static ResourceManager Resources{get {return resources; }} </code></pre>
41,903
<p>I have an HTML form with two buttons as follows:</p> <pre><code>&lt;input type="submit" name="confirm" value="Yes, Delete" /&gt; &lt;button name="confirm" type="button" onclick="history.back()" value="No, Go Back"&gt;No, Go Back&lt;/button&gt; </code></pre> <p>Now, when I click on either in Firefox, the behavior is as expected. If I click the submit button, then "Yes, Delete" gets posted and if I click "No, Go Back" it's as if I hit the back button on the browser. However, in Internet Explorer (6 or 8), if I click on "Yes, Delete" then "No, Go Back" gets posted. Why is that?</p>
<p>Firefox, Safari, Chrome, Opera <strong><em>all play</em></strong> the "<strong><em>first match wins</em></strong>" game, but IE plays the "<em>last match wins</em>" game.</p> <p>(<a href="http://webbugtrack.blogspot.com/2008/06/bug-or-feature-round-three.html" rel="nofollow noreferrer">see bug/feature report here</a>)</p> <p>In general, I would name the buttons differently unless they are part of a radio/checkbox set.</p>
<p>I believe this is because the names of both buttons are the same. The second button must be "overriding" the attributes of the first button. At any rate, changing the name of the second button solved the problem.</p>
48,054
<p>I went to <a href="http://www.json.org/js.html" rel="nofollow noreferrer">http://www.json.org/js.html</a> and downloaded the json2.js, thinking i'd be fine, afterall that site is on the top in a google search for 'json javascript' - also they have this really cool url :)</p> <p>So i've been working a bit with it and it seemed fine, but now i start running into trouble with it - it simply won't parse certain stuff i encode with Newtonsoft's JSON .NET serializer. Ok so perhaps the .net seralizer messes up? Not how i see it - it produces a fine javascript string that looks like perfect json.</p> <p>The problem comes when it has to encode a single quote ' and perhaps double quotes ". Take a look at these examples (only parts of the full string)</p> <pre><code>{"Id":10651,"Text":"\'69"} {"Id":184,"Text":"13\""} </code></pre> <p>Am I missing something? it's part of a bigger string and all put in a javascript variable like this</p> <pre><code>var jsonObject = '[{"Id":46,"Type":2,..................... </code></pre> <p>I'm thinking it has to escape the singlequote in the string to avoid conflicting with my wrapping of the string in single quotes, and escape the double quote to avoid conflicting with the json format?</p> <p>So either i'm doing something wrong or the json2.js is not doing it right? Or yeah perhaps the .net json is messing up - i'm kinda thinking i'm messing it up, but i've been trying to do all sorts of stuff to help with the parsing like escaping/unescaping etc. before the serializing/deserializing.</p>
<p><a href="https://blog.codinghorror.com/obscenity-filters-bad-idea-or-incredibly-intercoursing-bad-idea/" rel="nofollow noreferrer" title="Obscenity Filters: Bad Idea, or Incredibly Intercoursing Bad Idea?">Obscenity Filters: Bad Idea, or Incredibly Intercoursing Bad Idea?</a> ^_^</p> <p>Also see <a href="https://stackoverflow.com/questions/273516/how-do-you-implement-a-good-profanity-filter" title="How do you implement a good profanity filter?">How do you implement a good profanity filter?</a>.</p>
<p>Well, what we (*) did is to create a two-tiered list of "bad words" (using regex to hopefully catch some variations). Using a Tier 1 word will get you a warning saying that you are violating the Terms of Service, and you cannot save that message until you fix it. If you use a Tier 2 word, the message is posted, but an objection is automatically filed against it. All message with an objection flagged (either system or user generated) are reviewed by a human who determined if it stays or goes.</p> <p>(*) "We" being the e-commerce arm of a large, staid brick-and-mortar chain-store, which has just started allowing user-generated content on it's website.</p>
38,365
<p>I'm writing an application and I'm trying to tie simple AJAX functionality in. It works well in Mozilla Firefox, but there's an interesting bug in Internet Explorer: Each of the links can only be clicked once. The browser must be completely restarted, simply reloading the page won't work. I've written a <a href="http://static.stillinbeta.com/page/" rel="noreferrer">very simple example application</a> that demonstrates this.</p> <p>Javascript reproduced below:</p> <pre><code>var xmlHttp = new XMLHttpRequest(); /* item: the object clicked on type: the type of action to perform (one of 'image','text' or 'blurb' */ function select(item,type) { //Deselect the previously selected 'selected' object if(document.getElementById('selected')!=null) { document.getElementById('selected').id = ''; } //reselect the new selcted object item.id = 'selected'; //get the appropriate page if(type=='image') xmlHttp.open("GET","image.php"); else if (type=='text') xmlHttp.open("GET","textbox.php"); else if(type=='blurb') xmlHttp.open("GET","blurb.php"); xmlHttp.send(null); xmlHttp.onreadystatechange = catchResponse; return false; } function catchResponse() { if(xmlHttp.readyState == 4) { document.getElementById("page").innerHTML=xmlHttp.responseText; } return false; } </code></pre> <p>Any help would be appreciated.</p>
<p>This happens because Internet Explorer ignores the no-cache directive, and caches the results of ajax calls. Then, if the next request is identical, it will just serve up the cached version. There's an easy workaround, and that is to just append random string on the end of your query.</p> <pre><code> xmlHttp.open("GET","blurb.php?"+Math.random(); </code></pre>
<blockquote> <p>xmlHttp.open("GET","blurb.php?"+Math.random();</p> </blockquote> <p>I agree with this one.. it works perfectly as a solution to this problem. the problem is that IE7's caching of urls were terrible, ignoring the no-cache header and save the resource to its cache using its url as key index, so the best solution is to add a random parameter to the GET url.</p>
30,383
<p>I'd like to create an application that would run on Google's appengine.</p> <p>However, this application needs to be able to generate PDFs dynamically.</p> <p>How could I do this?</p>
<p>You can use the <a href="http://www.reportlab.org/rl_toolkit.html" rel="noreferrer"><code>reportlab</code> library</a> to generate a PDF from Python. You can just include the ReportLab files in with your application's code, or you can include a <a href="http://code.google.com/appengine/articles/django10_zipimport.html" rel="noreferrer">zip archive</a> of the ReportLab code, and insert it into your application's <code>sys.path</code>.</p>
<p>I would recommend <strong>PyFPDF</strong>, which is a pure-Python port of the lightweight yet highly powerful PHP FPDF library. It is hardly a few dozen kilobytes.</p> <p>See <a href="http://code.google.com/p/pyfpdf/" rel="nofollow">http://code.google.com/p/pyfpdf/</a></p>
42,476
<p>I need to alter the length of a column <code>column_length</code> in say more than 500 tables and the tables might have no of records ranging from 10 records to 3 or 4 million records.</p> <ol> <li>The column may just be a normal column</li> </ol> <pre><code>CREATE TABLE test(column_length varchar(10)) </code></pre> <ol start="2"> <li>The column might contain non-clustered index on it.</li> </ol> <pre><code>CREATE TABLE test(column_length varchar(10)) CREATE UNIQUE NONCLUSTERED INDEX column_length_ind ON test (column_length) </code></pre> <ol start="3"> <li>The column might contain <code>PRIMARY KEY</code> clustered index on it</li> </ol> <pre><code>CREATE TABLE test(column_length varchar(10)) ALTER TABLE test ADD PRIMARY KEY CLUSTERED INDEX ON column_length </code></pre> <ol start="4"> <li><p>The column might be a composite primary key</p> </li> <li><p>The column might have a foreign key reference</p> </li> </ol> <p>In short the column <code>column_length</code> might be anything.</p> <p>All I need is to create scripts to alter the length of the column_length from <code>varchar(10)</code> to <code>varchar(50)</code>. Should I drop the indexes before altering and then recreate them? What about the primary key and foreign key?</p> <p>Through my research and testing I figured out that I can just alter the column's length without dropping the primary key or any indexes but have to drop and recreate the foreign key alone.</p> <p>Is this assumption right?</p>
<p>Yes you should be able to just modify the columns. From my experience it is faster to leave the index and primary key in place.</p>
<p>Likely you will need to do alter column on the foreign key tables as well to increase the size. SO first you drop the fk constraint, then fix the forign kkey fields, then fix the primary key field then put the constraints back on.</p>
16,227
<p>What are you favorite LogParser 2.2 Scripts to run against IIS logs and Event logs?</p> <p>I am putting a list of scripts together to run against our production environment to proactively look for issues and to help when isolating performance problems.</p> <p>Do you have a certain list of LogParser 2.2 scripts that you use?</p>
<p>I like to run queries to identify the top pages requested, the pages that have the highest sum of "time taken" as well as the pages with the highest average "time taken".</p> <p>With these it helps to identify heavy load sections, and sometimes leads to areas that can be improved with caching ETC.</p>
<p>We usually yank the lot back into SQL server then query what we're after from there. I work for a shared hoster and one of the things we look for is excessive scripting errors in the IIS logs and ASP.NET exceptions logged to the event log. On shared box with 1200 sites these can bring it to it's knees if not kept in check, exceptions and errors are always expensive. We then use the data to let the culprits know their sites need fixing.</p>
21,072
<p>I have some .net apps running that I need to monitor for example, then MethodA is called in App1, my monitor app should detect this. I have a lot of running apps and the solution proposed here is to recompile all those apps and include a new line in the desired methods that we want to monitor. I want to do this only if there is absolutely no way. So did anybody ever done something like this? Basically, I need to create a new app that when I click a button on it, it will tell me: MethodA was called in App1, in real time...</p> <p>thanks!</p>
<p>There are several ways you could do this. One is to use log4Net, 'sprinkle' your methods with calls to log4Net's write methods. You can choose a variety of logging appenders (destinations) such as email or a database, but a less known tip is to download the standalone program, <a href="http://technet.microsoft.com/en-us/sysinternals/bb896647.aspx" rel="nofollow noreferrer">DebugView</a> (SysInternals -> now Microsoft) which listens for the default messages.</p>
<p>System.Diagnostics.PerformanceCounter is a good place to start. You can create new counters that can be viewed in the Performance control panel applet. They're a little confusing at the start, but when you realize average counters need two components to calculate a percentage it gets a lot easier.</p>
13,963
<p>How long will it take to enroll in the iPhone developer program after paying the $99?</p> <p>Is there anything to do after paying it? (I mean paperwork, faxing or sending physical stuff)</p> <p>How will Apple pay your revenues? (In what form and intervals, and what will they do if you are not in US?)</p>
<p>About 1 week after the $99 - perhaps a little less or a little more.</p> <p>Yes, you have to manage certificates and provisions. Also, you have to submit your contact, tax, and bank information. Nothing complicated though - just the standard stuff.</p> <p>Apple pays by depositing funds into your bank account and providing a detailed statement of your sales.</p>
<p>You also might have to fax them a copy of your passport/ID if your contact address differs from the creditcard billing address.</p>
45,000
<p>I need to develop a CRM system which will allow users to have a local copy of the DB which can then be synched with the main server system. The idea is that a sales team can travel to non-internet enabled areas and still operate with relatively up to date information and then synch up when they get back to the office.</p> <p>Ive never done something like this before, can anyone recommend a synch solution? </p>
<p>Having written just such a system myself, I'd recommend avoiding it if possible. The ways that users can mess up such a system are legion, particularly when the users are the sales team. A CRM system named Act! (you are probably familiar with) has offered such a sync option in the past, and maybe they still do. Whenever my company is selling to a company that has been using Act!'s sync system, the company always complains of corrupted and mis-synced databases.</p> <p>If you really need to do such a thing, then I'd recommend database-level replication (which wasn't available at the time we wrote our sync application). Many databases offer replication, including MS-SQL Server. You can eliminate many of the problems we experienced by tracking changes at the database level, and making the database responsible for transporting those changes to a remote database.</p>
<p>You might want to take a look at the <a href="http://msdn.microsoft.com/en-us/sync/default.aspx" rel="nofollow noreferrer">Microsoft Synch Framework</a>. I haven't used it yet, so I cannot give a personal opinion on it though.</p>
41,053
<p>I am using RedCloth with Rails 2.1.1. The Textile <code>&lt;del&gt;</code> tag markup format (i.e. -delete-) was not translating at all. Tried a few choice options.</p> <pre><code>&gt; x=RedCloth.new('foobar -blah-') =&gt; "foobar -blah-" &gt; x.to_html =&gt; "&lt;p&gt;foobar &lt;del&gt;blah&lt;/del&gt;&lt;/p&gt;" # WORKED! &gt; x=RedCloth.new('foobar * -blah-') =&gt; "foobar * -blah-" &gt; x.to_html =&gt; "&lt;p&gt;foobar * &lt;del&gt;blah&lt;/del&gt;&lt;/p&gt;" # WORKED! &gt; x=RedCloth.new("foobar\n* -blah-") =&gt; "foobar\n* -blah-" &gt; x.to_html =&gt; "&lt;p&gt;foobar&lt;/p&gt;\n&lt;ul&gt;\n\t&lt;li&gt;-blah-&lt;/li&gt;\n&lt;/ul&gt;" # DID NOT WORK! </code></pre> <p>It appears to me that newlines are the culprit in throwing RedCloth up-in-arms. Any solutions to getting RedCloth to properly recognize '-delete-'? I have tried RedCloth 4.0.1, 4.0.3, and 4.0.4.</p>
<p>Looks like RedCloth needs a little more syntax to interpret the delete tag as the first element after a list item...</p> <pre><code>&gt;&gt; RedCloth.new("foobar\n* [-blah-]").to_html =&gt; "&lt;p&gt;foobar&lt;/p&gt;\n&lt;ul&gt;\n\t&lt;li&gt;&lt;del&gt;blah&lt;/del&gt;&lt;/li&gt;\n&lt;/ul&gt;" </code></pre>
<p>This is because <strong>a star on a new line represents a list item</strong>, and it is ignoring delete markers without explicitly telling it to render them as Michael points out.</p>
28,658
<p>I am wondering what is best practice when it comes to dependencies and how releases should be done. In my case I have a library that relies on log4net and I am wondering if I should distribute log4net.dll (set the log4net reference to copy local) along with the release? </p> <p>Could I simply state that log4net should be installed in the GAC?</p>
<p>Testing your function plus curl plus the server is more integration test than unit test. That being said, you don't have to be that dogmatic, if you only have one test like that this certainly is viable. I've written, and still have tests that are not pure unit tests, but they do their job. I'll keep them as far as they don't go in my way. </p> <p>The only thing I'd be bothered with is the five seconds timeout, which is very long for an unit test. Now, it depends on how often it occurs. Did you consider a basic test (e.g. pinging the server) prior launching curl to avoid starting a needless test. </p> <p>If you're looking for alternatives, what about splitting your test in two parts: 1/ test how curl is invoked ; 2/ test what your function does with the result ? That way you'll be isolated from the server and you won't need any timeout. </p>
<p>I think you should be mocking the method the function uses to detect that it has spent long enough waiting, then you can test the timeout instantly and not wait in real time.</p>
39,197
<p>I am confronted with a new kind of problem which I haven't encountered yet in my very young programming "career" and would like to know your opinion about how to tackle it best.</p> <p><strong>The situation</strong> A research application (php/mysql) gathers stress related health data from users. User gets a an analyses after filling in the questionnaire. Value for each parameter is transformed into a percentile value using a benchmark (mean and standard devitation of existing data set).</p> <p><strong>The task</strong> Since more and more ppl are filling in the questionnaire, there is the potential to make the benchmark values (mean/SD) more accurate by recalculating them using the new user data. I would like the database to regularly run a script that updates the benchmark values.</p> <p><strong>The question</strong> I've never used stored precedures so far and I only have a slight notion of what they are but somehow I have a feeling they could maybe help me with this? Or should I write the script as php and then set up a cron job?</p> <p>[edit]After the first couple of answers it looks like cron is clearly the way to go.[/edit]</p>
<p>What you're considering could be done in a number of ways.</p> <ol> <li><p>You could setup a trigger in your DB to recalculate the values whenever a new record is updated. You could store the code needed to update the values in a sproc if necessary.</p></li> <li><p>You could write a PHP script and run it regularly via cron.</p></li> </ol> <p>#1 will slow down inserts to your database but will make sure your data is <em>always</em> up to date. #2 may lock the tables while it updates the new values, and your data will only be accurate until the next update. #2 is much easier to back up, as the script can easily be stored in your versioning system, whereas you'd need to store the trigger and sproc creation scripts in whatever backup you'd make.</p> <p>Obviously you'll have to weigh up your requirements before you pick a method.</p>
<p>If the volume of data is big enough that calculating it on the fly is too much, then either:</p> <ol> <li>Cron job with php script to denormalise the totals</li> <li>Trigger on inserts that increments totals </li> </ol>
10,879
<p>I need to create a configuration section, that is able to store key-value pairs in an app.config file and the key-value pairs can be added runtime regardless of their type. It is also important that the value keeps its original type. I need to extend the following interface </p> <pre><code>public interface IPreferencesBackend { bool TryGet&lt;T&gt;(string key, out T value); bool TrySet&lt;T&gt;(string key, T value); } </code></pre> <p>At runtime, I can say something like: </p> <pre><code>My.Foo.Data data = new My.Foo.Data("blabla"); Pref pref = new Preferences(); pref.TrySet("foo.data", data); pref.Save(); My.Foo.Data date = new My.Foo.Data(); pref.TryGet("foo.data", out data); </code></pre> <p>I tried with System.Configuration.Configuration.AppSettings, but the problem with that that it is storing the key-value pairs in a string array. </p> <p>What I need is to have an implementation of System.Configuration.ConfigurationSection, where I can control the how the individual setting is serialized. I noticed that the settings generated by Visual Studio kind of do this. It is using reflection to create all the setting keys. what I need is to do this runtime and dynamically. </p> <pre><code>[System.Configuration.UserScopedSettingAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.Configuration.DefaultSettingValueAttribute("2008-09-24")] public global::System.DateTime DateTime { get { return ((global::System.DateTime)(this["DateTime"])); } set { this["DateTime"] = value; } } </code></pre>
<p>I found two great articles on codeproject.com that are explaining these issues in great detail. </p> <p>Unraveling the Mysteries of .NET 2.0 Configuration <a href="http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx" rel="nofollow noreferrer">http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx</a></p> <p>User Settings Applied <a href="http://www.codeproject.com/KB/dotnet/user_settings.aspx?display=PrintAll&amp;fid=1286606&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;select=2647446&amp;fr=26" rel="nofollow noreferrer">http://www.codeproject.com/KB/dotnet/user_settings.aspx?display=PrintAll&amp;fid=1286606&amp;df=90&amp;mpp=25&amp;noise=3&amp;sort=Position&amp;view=Quick&amp;select=2647446&amp;fr=26</a></p>
<p>That's all you get in a an ASCII text file - strings. :-)</p> <p>However, you can encode the "value" strings to include a type parameter like:</p> <pre><code>&lt;key="myParam" value="type, value" /&gt; </code></pre> <p>for example:</p> <pre><code>&lt;key="payRate" value="money,85.79"/&gt; </code></pre> <p>then have your app do the conversion ...</p>
15,253
<p>Mixing the use of primitive data types and their respective wrapper classes, in Java, can lead to a lot of bugs. The following example illustrates the issue:</p> <pre><code>int i = 4; ... if (i == 10) doStuff(); </code></pre> <p>Later on you figure that you want the variable <em>i</em> to be either defined or undefined, so you change the above instantiation to:</p> <pre><code>Integer i = null; </code></pre> <p>Now the equality check fails.</p> <p>Is it good Java practise to always use the primitive wrapper classes? It obviously would get some bugs out of the way early, but what are the downsides to this? Does it impact performance or the application's memory footprint? Are there any sneaky gotchas?</p>
<p>Using the boxed types <em>does</em> have both performance and memory issues.</p> <p>When doing comparisons (eg <code>(i == 10)</code> ), java has to unbox the type before doing the comparison. Even using <code>i.equals(TEN)</code> uses a method call, which is costlier and (IMO) uglier than the == syntax.</p> <p>Re memory, the object has to be stored on the heap (which also takes a hit on performance) as well as storing the value itself.</p> <p>A sneaky gotcha? <code>i.equals(j)</code> when i is <code>null</code>.</p> <p>I always use the primitives, except when it <em>may</em> be <code>null</code>, but always check for <code>null</code> before comparison in those cases.</p>
<p>Thee java POD types are there for a reason. Besides the overhead, you can't do normal operations with objects. An Integer is an object, which need to be allocated and garbage collected. An int isn't.</p>
15,100
<p>In Python, I want to make <strong>selected</strong> instance attributes of a class be readonly to code outside of the class. I want there to be no way outside code can alter the attribute, except indirectly by invoking methods on the instance. I want the syntax to be concise. What is the best way? (I give my current best answer below...)</p>
<p>You should use the <code>@property</code> decorator.</p> <pre><code>&gt;&gt;&gt; class a(object): ... def __init__(self, x): ... self.x = x ... @property ... def xval(self): ... return self.x ... &gt;&gt;&gt; b = a(5) &gt;&gt;&gt; b.xval 5 &gt;&gt;&gt; b.xval = 6 Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; AttributeError: can't set attribute </code></pre>
<p>You could use a metaclass that auto-wraps methods (or class attributes) that follow a naming convention into properties (shamelessly taken from <a href="http://www.python.org/download/releases/2.2/descrintro/#metaclasses" rel="nofollow noreferrer">Unifying Types and Classes in Python 2.2</a>:</p> <pre><code>class autoprop(type): def __init__(cls, name, bases, dict): super(autoprop, cls).__init__(name, bases, dict) props = {} for name in dict.keys(): if name.startswith("_get_") or name.startswith("_set_"): props[name[5:]] = 1 for name in props.keys(): fget = getattr(cls, "_get_%s" % name, None) fset = getattr(cls, "_set_%s" % name, None) setattr(cls, name, property(fget, fset)) </code></pre> <p>This allows you to use:</p> <pre><code>class A: __metaclass__ = autosuprop def _readonly(self): return __x </code></pre>
15,200
<p>In my small WPF project, I have a <code>TabControl</code> with three tabs. On each tab is a <code>ListBox</code>. This project keeps track of groceries we need to buy. (No, it's not homework, it's for my wife.) So I have a list of <code>ShoppingListItem</code>s, each of which has a <code>Name</code> and a <code>Needed</code> property: <code>true</code> when we need the item, and <code>false</code> after we buy it.</p> <p>So the three tabs are All, Bought, and Needed. They should all point to the same <code>ShoppingListItemCollection</code> (which inherits from <code>ObservableCollection&lt;ShoppingListItem&gt;</code>). But Bought should only show the items where Needed is false, and Needed should only show items where Needed is true. (The All tab has checkboxes on the items.)</p> <p>This doesn't seem <em>that</em> hard, but after a couple hours, I'm no closer to figuring this out. It seems like a CollectionView or CollectionViewSource is what I need, but I can't get anything to happen; I check and uncheck the boxes on the All tab, and the items on the other two tabs just sit there staring at me.</p> <p>Any ideas?</p>
<p>You can use a <a href="http://msdn.microsoft.com/en-us/library/system.windows.data.collectionviewsource.aspx" rel="nofollow noreferrer">CollectionViewSource</a> to reuse the original collection with a filter. </p> <pre><code>&lt;Window.Resources&gt; &lt;CollectionViewSource x:Key="NeededItems" Source="{Binding Items}" Filter="NeededCollectionViewSource_Filter" /&gt; &lt;CollectionViewSource x:Key="BoughtItems" Source="{Binding Items}" Filter="BoughtCollectionViewSource_Filter" /&gt; &lt;/Window.Resources&gt; &lt;TabControl&gt; &lt;TabItem Header="All"&gt; &lt;ListBox DisplayMemberPath="Name" ItemsSource="{Binding Items}" /&gt; &lt;/TabItem&gt; &lt;TabItem Header="Bought"&gt; &lt;ListBox DisplayMemberPath="Name" ItemsSource="{Binding Source={StaticResource BoughtItems}}" /&gt; &lt;/TabItem&gt; &lt;TabItem Header="Needed"&gt; &lt;ListBox DisplayMemberPath="Name" ItemsSource="{Binding Source={StaticResource NeededItems}}" /&gt; &lt;/TabItem&gt; &lt;/TabControl&gt; </code></pre> <p>Some code behind is required for the filter.</p> <pre><code>private void NeededCollectionViewSource_Filter(object sender, FilterEventArgs e) { e.Accepted = ((ShoppingListItem) e.Item).Needed; } private void BoughtCollectionViewSource_Filter(object sender, FilterEventArgs e) { e.Accepted = !((ShoppingListItem) e.Item).Needed; } </code></pre>
<p>Here are a couple of ideas:</p> <ol> <li>When tabs Bought and Needed load, filter them yourself by creating new collections with the items you want, or</li> <li>when tabs Bought and Needed load, override the list item databind and toggle visability based on Needed</li> </ol>
34,560
<p>I'd like to be able to switch the sound output source in Mac OS X without any GUI interaction.</p> <p>There are tools to do control the sound output, such as <a href="http://rogueamoeba.com/freebies/" rel="noreferrer">SoundSource</a> and an <a href="http://www.macosxhints.com/article.php?story=20050614171126634" rel="noreferrer">applescript to open the preferences dialog</a>.</p> <p>What I am looking for is something that switches the preference instantly, like <a href="http://rogueamoeba.com/freebies/" rel="noreferrer">SoundSource</a> but it has to be scriptable. The goal is to switch between my digital and analog output with one keystroke. I have a <a href="http://www.blacktree.com/?quicksilver" rel="noreferrer">helper application</a> that will launch a program or applescript on one keypress. All I need now is the applescript or application that switches the sound source quickly without any user interaction.</p> <p>I'm willing to write some Objective-C if that is what it takes, but I'm pretty much a newbie at Cocoa development.</p> <p>Do you have a one-click solution or can point me to a good tutorial on controlling sound system preferences from a Cocoa App or command line?</p> <p><strong>EDIT</strong>: I created a command-line application to do exactly this. You may download it at <a href="http://code.google.com/p/switchaudio-osx/downloads" rel="noreferrer">http://code.google.com/p/switchaudio-osx/downloads</a>. Source code is available on the project site as well.</p>
<p>Don’t think of it in terms of preferences; there’s no centralized system preference framework for this sort of thing. I believe what you need to do is use Core Audio to set the <code>kAudioHardwarePropertyDefaultOutputDevice</code> and <code> kAudioHardwarePropertyDefaultSystemOutputDevice</code> properties of the <code>AudioSystemObject</code> (using <code>AudioHardwareSetProperty()</code>).</p>
<p>I created a command-line application to do exactly this.</p> <p>You may download it at <a href="http://code.google.com/p/switchaudio-osx/downloads" rel="nofollow noreferrer">http://code.google.com/p/switchaudio-osx/downloads</a>. Source code is available on the project site as well.</p> <p><strong>UPDATE</strong> (Dec. 2014): the code is now hosted on github -- <a href="https://github.com/deweller/switchaudio-osx" rel="nofollow noreferrer">https://github.com/deweller/switchaudio-osx</a>. And works just fine in Yosemite.</p>
20,548
<p>for some reason, templatetags do not render in templates for django admin.</p> <p>with this snippet from: <a href="http://docs.djangoproject.com/en/dev/ref/templates/api/?from=olddocs#shortcut-for-simple-tags" rel="nofollow noreferrer">http://docs.djangoproject.com/en/dev/ref/templates/api/?from=olddocs#shortcut-for-simple-tags</a></p> <pre><code>{% if is_logged_in %}Thanks for logging in!{% else %}Please log in.{% endif %} </code></pre> <p>when placed in admin index.html, if a user is logged in, it shows "Please log in"</p> <p>same with templatetags, can not get any app ones to show, do anything. there is no error/they do not get processed either </p>
<p>That's only an example, the <code>is_logged_in</code> variable is not actually defined in any templates unless you put it in the context.</p> <p>If you added that line and got <code>Please log in.</code> it does mean that the tag is rendering. If it fails the <code>if</code> and goes to the <code>else</code> it is clearly being run. You need to find something in the template you can actually use for the <code>if</code> case, though. I haven't messed with the admin templates in newforms-admin, but depending if they use RequestContext and on which ContextProcessors you have enabled - you might be able to say <code>{% if not request.user.is_anonymous %} ...</code> or something similar.</p>
<p>I just tried this one:</p> <p>request.user.is_authenticated</p> <p>Right in the template and just worked as we wish!</p>
31,148
<p>Does anyone know any good tool that I can use to perform stress tests on a video streaming server? I need to test how well my server handles 5,000+ connections. </p>
<p>One option is to use VLC. You can specify a url on the command line. (see <a href="http://wiki.videolan.org/VLC_command-line_help" rel="nofollow noreferrer">here</a> for details). You could then write a brief shell script to open up all 5000 connections.</p> <p>eg. the following perl script (very quick hack - check before running, might cause explosions etc.)</p> <pre class="lang-perl prettyprint-override"><code>$i = 0; $myurl = "udp://someurl"; @cmdline = ("/usr/bin/vlc", ""); for( $i = 1; $i &lt;= 5000; $i++ ) { if( $pid = fork ) { # parent - ignore } elsif( defined $pid ) { $cmdline[1] = sprintf "%s:%d", $myurl, $i; exec(@cmdline); } # elseif - do more error checking here } </code></pre> <p>If your video streaming server is doing multicast it should be sufficient to open sockets and make them members of your 5000 multicast groups (without necessarily doing anything with the stream. By not actually decoding the stream you will reduce performance issues on the client end).</p> <p>I'm not aware of any tools that will do this for you, but if you're up for writing your own utility you can start <a href="http://tldp.org/HOWTO/Multicast-HOWTO-6.html" rel="nofollow noreferrer">here</a> for details.</p> <p>edit: The second option assumes that the OS on your client machine has multicast capability. I mention that because (from memory) the linux kernel doesn't by default, and I'd like to save you that pain. :-)</p> <p>Easy way to tell (again on Linux) is to check for the presence of <code>/proc/net/igmp</code></p>
<p>This <a href="http://www.mocomsoft.com/en-US/products/HLSAnalyzer.aspx" rel="nofollow">HLS Analyzer</a> software can be used for stress testing HTTP Live Streaming server and monitoring downloading performance. </p>
18,247
<p>or "How do I answer questions on SO in Firefox using gVim inside the textboxes?"</p>
<p><a href="https://addons.mozilla.org/en-US/firefox/addon/4125" rel="noreferrer">It's All Text!</a></p> <p>From the extension page:</p> <blockquote> <p>At the bottom right corner of any edit box, a little edit button will appear. Click it. If this is the first time you've used "It's All Text!" then you will be asked to set your preferences, most importantly the editor.</p> <p>The web page will pop up in your selected editor. When you save it, it'll refresh in the web page. Wait for the magic yellow glow that means that the radiation has taken effect!</p> </blockquote>
<p>With Firefox-57 on Linux, I installed textern <a href="https://addons.mozilla.org/en-US/firefox/addon/textern/" rel="nofollow noreferrer">https://addons.mozilla.org/en-US/firefox/addon/textern/</a>, and found it to be a suitable replacement for ViewSourceWith for editing text boxes.</p>
10,125
<p>I am developing an application, and have URLs in the format <code>www.example.com/some_url/some_parameter/some_keyword</code>. I know by design that there is a maximum length that these URLs will have (and still be valid). Should I validate the URL length with every request in order to protect against buffer overflow/injection attacks? I believe this is an obvious yes but I'm not a security expert so perhaps I am missing something.</p>
<p>If you are not expecting that input, reject it.</p> <p>You should always validate your inputs, and certainly discard anything outside of the expected range. If you already know that your URL's honestly won't be beyond a certain length then rejecting it before it gets to the application seems wise.</p>
<p>I think this may give you some modicum of safety and might save you a little bandwidth if people do send you crazy long URLs, but largely you should just validate your data in the actual application as well. Multiple levels of security are generally better, but don't make the mistake of thinking that because you have a (weak) safeguard at the beginning that you won't have issues with the rest.</p>
11,804
<p>Given a table of votes (users vote for a choice, and must supply an email address):</p> <pre><code>votes -- id: int choice: int timestamp: timestamp ip: varchar email: varchar </code></pre> <p>What's the best way to count "unique" votes (a user being a unique combination of email + ip) given the constraint they may only vote <em>twice</em> per hour?</p> <p>It's possible to count the number of hours between first and last vote and determine the maximum number of allowed votes for that timeframe, but that allows users to compress all their votes into say, a single hour-long window, and still have them counted.</p> <p>I realize anonymous online voting is inherently flawed, but I'm not sure how to do this with SQL. Should I be using an external script or whatever instead? (For each choice, for each email+ip pair, get a vote, calculate the next +1h timestamp, count/discard/tally votes, move on to the next hour, etc...)</p>
<p>Something like </p> <pre><code>select email, ip, count(choice) from votes group by email, ip, datepart(hour, timestamp) </code></pre> <p>If I understand correctly</p>
<p>You could rewrite your insert statement to only allow votes to be inserted based on your contrainsts:</p> <pre><code>Insert Into Votes (Choice, Timestamp, IP, Email) Select Top 1 @Choice, @Timestamp, @IP, @Email From Votes Where (Select Count(*) From Votes Where IP = @IP and Email = @Email and Timestamp &gt; DateAdd(h, -2, GetDate())) &lt; 3 </code></pre> <p>You didn't mention which SQL language you were using so this is in SQL Server 2005.</p>
9,688
<p>I am trying to show and hide an inline element (eg a span) using jQuery.</p> <p>If I just use toggle(), it works as expected but if I use toggle("slow") to give it an animation, it turns the span into a block element and therefore inserts breaks.</p> <p>Is animation possible with inline elements? I would prefer a smooth sliding if possible, rather than a fade in.</p> <pre><code>&lt;script type="text/javascript"&gt; $(function(){ $('.toggle').click(function() { $('.hide').toggle("slow") }); }); &lt;/script&gt; &lt;p&gt;Hello &lt;span class="hide"&gt;there&lt;/span&gt; jquery&lt;/p&gt; &lt;button class="toggle"&gt;Toggle&lt;/button&gt; </code></pre>
<p><code>toggle()</code> has a bunch of weird things with it, including hiding or transforming odd elements at times. here's a similar solution:</p> <pre><code>$('.toggle').click(function() { $('.hide').animate({ 'opacity' : 'toggle', }); }); </code></pre> <p><strong>edit</strong>: here's a way to add smooth sliding, with minimal extra HTML markup:</p> <pre><code>var hidepos = $('.hide').offset().left; var slidepos = $('.slide').offset().left; $('.toggle').click(function() { var goto = ($('.slide').offset().left &lt; slidepos) ? slidepos : hidepos; $('.slide').css({ 'left' : $('.slide').offset().left, 'position' : 'fixed', }).animate({ 'left' : goto, }, function() { $(this).css('position', 'static'); }); $('.hide').animate({ 'opacity' : 'toggle', }); }); </code></pre> <p>html:</p> <pre><code>&lt;p&gt;Hello &lt;span class="hide"&gt;there&lt;/span&gt; &lt;span class="slide"&gt;jquery&lt;/span&gt;&lt;/p&gt; &lt;button class="toggle"&gt;Toggle&lt;/button&gt; </code></pre>
<p>As other answers have shown, fading is possible. However, I don't think "smooth sliding" will be. Simply put, a specific property of the element has to be animated. An inline span like you mention has no specific height or width, though it does have an opacity.</p>
28,713
<p>The default seems to be upper case, but is there really any reason to use upper case for keywords?</p> <p>I started using upper case, because I was just trying to match what <a href="https://en.wikipedia.org/wiki/Microsoft_SQL_Server" rel="nofollow noreferrer">SQL Server</a> gives me whenever I tried to create something, like a new <a href="https://en.wikipedia.org/wiki/Stored_procedure" rel="nofollow noreferrer">stored procedure</a>. But then, I felt terrible for my baby (5th) finger, that always needs to hold down the <kbd>Shift</kbd> button, so I stopped using upper case. Is there a reason why I should go back to upper case?</p>
<p>It's just a matter of style, probably originating in the days when editors didn't do code colouring.</p> <p>I used to prefer all upper case, but I'm now leaning towards all lower.</p> <p>Either way, be consistent.</p>
<p>I call most of my mySQL code from within PHP, and I do all of my PHP editing within vim (or I suppose in this case, VIM ;-). Now I am sure there are plugins out there to highlight the mySQL code within PHP, but I have not found it, and I don't have to the time to go looking for it. Therefore, I prefer to have <strong>everything</strong> in allcaps. I find this:</p> <pre><code>if ( !$bla ) { echo "select something from something where something"; } if ( !$beepboop ) { echo "create table if not exists loremIpsum; } $query = " CREATE TABLE IF NOT EXISTS HISTORY ( ID INT NOT NULL AUTO_INCREMENT, INSERTDATE TIMESTAMP DEFAULT NOW(), ALTERDATE TIMESTAMP(8) DEFAULT NOW(), DELETEDATE TIMESTAMP(8), ALTERCOUNT INT DEFAULT 0, SELECTCOUNT INT DEFAULT 0, PRIMARY KEY(ID), )ENGINE=InnoDB "; mysqlQuery( $query, $con ); </code></pre> <p>Helps me distinguish between PHP versus SQL a lot better than this:</p> <pre><code>if ( !$bla ) { echo "select something from something where something"; } if ( !$beepboop ) { echo "create table if not exists loremIpsum; } $query = " create table if not exists history ( id int not null auto_increment, insertdate timestamp default now(), alterdate timestamp(8) default now(), deletedate timestamp(8), altercount int default 0, selectcount int default 0, primary key(id), )engine=InnoDB "; mysqlQuery( $query, $con ); </code></pre> <p>Also, for some reason, I hate mixing allcaps with camel case, like so:</p> <pre><code>CREATE TABLE IF NOT EXISTS history ( ID INT NOT NULL AUTO_INCREMENT, insertDate TIMESTAMP DEFAULT NOW(), alterDate TIMESTAMP(8) DEFAULT NOW(), deleteDate TIMESTAMP(8), alterCount INT DEFAULT 0, selectCount INT DEFAULT 0, PRIMARY KEY(ID), )ENGINE=InnoDB </code></pre> <p>That <code>ID</code> irks me. Should it instead be <code>id</code>? or <code>iD</code>?</p>
37,256
<p>Is there some way to block access from a referrer using a .htaccess file or similar? My bandwidth is being eaten up by people referred from <a href="http://www.dizzler.com" rel="nofollow noreferrer">http://www.dizzler.com</a> which is a flash based site that allows you to browse a library of crawled publicly available mp3s.</p> <p><strong>Edit:</strong> Dizzler was still getting in (probably wasn't indicating referrer in all cases) so instead I moved all my mp3s to a new folder, disabled directory browsing, and created a robots.txt file to (hopefully) keep it from being indexed again. Accepted answer changed to reflect futility of my previous attempt :P</p>
<p>That's like saying you want to stop spam-bots from harvesting emails on your publicly visible page - it's very tough to tell the difference between users and bots without forcing your viewers to log in to confirm their identity.</p> <p>You could use robots.txt to disallow the spiders that actually follow those rules, but that's on their side, not your server's. There's a page that explains how to catch the ones that break the rules and explicitly ban them : <a href="http://www.evolt.org/article/Using_Apache_to_stop_bad_robots/18/15126/" rel="nofollow noreferrer">Using Apache to stop bad robots</a> [evolt.org]</p> <p>If you want an easy way to stop dizzler in particular using the .htaccess, you should be able to pop it open and add:</p> <pre><code>&lt;Directory /directoryName/subDirectory&gt; Order Allow,Deny Allow from all Deny from 66.232.150.219 &lt;/Directory&gt; </code></pre>
<p>It's not a very elegant solution, but you could block the site's crawler bot, then rename your mp3 files to break the links already on the site.</p>
10,682
<p>I have a few huge tables on a production SQL 2005 DB that need a schema update. This is mostly an addition of columns with default values, and some column type change that require some simple transformation. The whole thing can be done with a simple "SELECT INTO" where the target is a table with the new schema.</p> <p>Our tests so far show that even this simple operation, done entirely inside the server (Not fetching or pushing any data), could take hours if not days, on a table with many millions of rows.</p> <p>Is there a better update strategy for such tables?</p> <p>edit 1: We are still experimenting with no definitive conclusion. What happens if one of my transformations to a new table, involve merging every five lines to one. There is some code that has to run on every transformation. The best performance we could get on this got us at a speed that will take at least a few days to convert a 30M rows table</p> <p>Will using SQLCLR in this case (doing the transformation with code running inside the server) give me a major speed boost?</p>
<p>We have a similar problem and I've found that the fastest way to do it is to export the data to delimited files (in chunks - depending on the size of the rows - in our case, each file had 500,000 rows), doing any transforms during the export, drop and recreate the table with the new schema, and then do a bcp import from the files.</p> <p>A 30 million row table took a couple of hours using that method, where an alter table took over 30 hours.</p>
<p>Add the column allowing null, then do the update to the default value manually, then re-alter the table to add the default value. This way you can control the updates and do them in smaller chunks.</p>
46,970
<p>Is there anything out there freeware or commercial that can facilitate analysis of memory usage by a PHP application? I know xdebug can produce trace files that shows memory usage by function call but without a graphical tool the data is hard to interpret. </p> <p>Ideally I would like to be able to view not only total memory usage but also what objects are on the heap and who references them similar to <a href="http://www.codework.com/jprofiler/product.htm" rel="noreferrer">Jprofiler</a>.</p>
<p>As you probably know, Xdebug dropped the memory profiling support since the 2.* version. Please search for the &quot;removed functions&quot; string here: <a href="http://www.xdebug.org/updates.php" rel="noreferrer">http://www.xdebug.org/updates.php</a></p> <blockquote> <p><strong>Removed functions</strong></p> <p>Removed support for Memory profiling as that didn't work properly.</p> </blockquote> <p>So I've tried another tool and it worked well for me.</p> <p><a href="https://github.com/arnaud-lb/php-memory-profiler" rel="noreferrer">https://github.com/arnaud-lb/php-memory-profiler</a></p> <p>This is what I've done on my Ubuntu server to enable it:</p> <pre><code>sudo apt-get install libjudy-dev libjudydebian1 sudo pecl install memprof echo &quot;extension=memprof.so&quot; &gt; /etc/php5/mods-available/memprof.ini sudo php5enmod memprof service apache2 restart </code></pre> <p>And then in my code:</p> <pre><code>&lt;?php memprof_enable(); // do your stuff memprof_dump_callgrind(fopen(&quot;/tmp/callgrind.out&quot;, &quot;w&quot;)); </code></pre> <p>Finally open the <code>callgrind.out</code> file with <a href="http://kcachegrind.sourceforge.net/html/Home.html" rel="noreferrer">KCachegrind</a></p> <h1>Using Google gperftools (recommended!)</h1> <p>First of all install the <strong>Google gperftools</strong> by downloading the latest package here: <a href="https://code.google.com/p/gperftools/" rel="noreferrer">https://code.google.com/p/gperftools/</a></p> <p>Then as always:</p> <pre><code>sudo apt-get update sudo apt-get install libunwind-dev -y ./configure make make install </code></pre> <p>Now in your code:</p> <pre><code>memprof_enable(); // do your magic memprof_dump_pprof(fopen(&quot;/tmp/profile.heap&quot;, &quot;w&quot;)); </code></pre> <p>Then open your terminal and launch:</p> <pre><code>pprof --web /tmp/profile.heap </code></pre> <p><em>pprof</em> will create a new window in your existing browser session with something like shown below:</p> <p><img src="https://i.stack.imgur.com/EAnGC.png" alt="PHP memory profiling with memprof and gperftools" /></p> <h1>Xhprof + Xhgui (the best in my opinion to profile both cpu and memory)</h1> <p>With <strong>Xhprof</strong> and <strong>Xhgui</strong> you can profile the cpu usage as well or just the memory usage if that's your issue at the moment. It's a very complete solutions, it gives you full control and the logs can be written both on mongo or in the filesystem.</p> <p>For more details <a href="https://stackoverflow.com/questions/16787462/php-xdebug-how-to-profile-forked-process/31388948#31388948">see my answer here</a>.</p> <h1>Blackfire</h1> <p>Blackfire is a PHP profiler by SensioLabs, the Symfony2 guys <a href="https://blackfire.io/" rel="noreferrer">https://blackfire.io/</a></p> <p>If you use <a href="https://puphpet.com/" rel="noreferrer">puphpet</a> to set up your virtual machine you'll be happy to know it's supported ;-)</p>
<p>A graphical tool for xdebug output is <a href="http://kcachegrind.sourceforge.net/" rel="nofollow noreferrer">KCacheGrind</a>.</p>
31,939
<p>What is a good way to represent sparse set of integers (really C memory addresses) in a compact and fast way. I already know about the obvious things like bit-vectors and run-length encoding. but I want something much more compact than one word per set element. I need to add and remove elements and test for membership. I do not need other set operations, like union.</p> <p>I read about one such library many years ago but have since forgotten its name. I think it was released as open source by HP and had a womans name.</p>
<p>You are referring to a judy array. It was a HP project. I think they are used in ruby and are available in c. Very interesting data structure. Making use of the fact that allocations are (at least) word aligned, having separate structures for dense and sparse ranges.</p> <p><a href="http://judy.sourceforge.net/index.html" rel="noreferrer">http://judy.sourceforge.net/index.html</a></p>
<p>If you want the structure smaller than the data set than you should probably look at some kind of tree arrangement. Make each level of a 4 way the tree key off 2 bits starting at the high end and it might compact quite well (if the pointers have any degree of spacial locality). The trick would be encoding it compactly enough (indexes into arrays of nodes? an array mapped tree?).</p>
47,116
<p>I have an application that has many different types of objects that each persist themselves back to the db. This has worked fine so far without transactions and I'm not looking to go hog wild adding them. But there is an occasional need to start a transaction before a whole collection of the objects start updating to ensure that the database is only actually updated if all objects in the collection succeed.</p> <p>For example, say I have a collection of apples. The command is issued to the collection to update all the apples. [transaction starting should be here] The each apples executes the code to update itself. [transaction commit/rollback should happen here].</p> <p>The hitch I have is that each update is atomic right now (not explicitly wrapped in a transaction). I could pass an id to each "apple" to identify a transaction that has been stashed in some kind of cache, but then there's the risk that the cache would be invalidated mid-update and cause an unnecessary problem.</p> <p>So what's the best approach to this?</p>
<p>First, I wouldn't be handling the transactional logic in the page. Write a business class of some sort to do this - a service, a data utility class, something you can abstract away from ASP.Net. </p> <p>Next, you might look at using the <em>TransactionScope</em> class (in System.Transactions namespace, reference System.Transactions.dll) if you are using a database that can subscribe to distributed transaction like SQL Server.</p> <pre><code>using(TransactionScope scope = new TransactionScope()) { SaveObjectOne(); //these are just psuedo-code statements SaveObjectTwo(); //replace these with your code that saves various objs SaveObjectThree(); scope.Complete(); //this commits the transaction, unless exception throws } </code></pre> <p>TransactionScope implements IDisposable, so when <em>using</em> calls <em>Dispose()</em> the transaction will roll back if <em>Complete()</em> was never called. You do need to enable the Distributed Transaction Coordinator to use <em>TransactionScope</em>.</p>
<ol> <li>I would prefer declarative transactions over trying to do manual DB transactions.</li> <li>As Mitch Wheat already mentioned, a transaction has context and is connection based, so it will include your changes happening in the page/method, and commit if all ok, or rollback if there was an exception.</li> <li><strong>I might be wrong here</strong>, but I have a feeling that "Page Transaction" is using Enterprise Services model from .NET 1.1 and works through MSDTC (Distributed transaction coordinator, registered COM+ service)...</li> <li>I would prefer System.Transactions and LTM (light-weight transaction manager) for declarative transactions in .NET 2.0</li> <li>I would prefer Spring.NET framework transactions (available for both ADO.NET and NHibernate versions), because I believe they support better AOP-based (aspect oriented programming) separation of concerns, you will not have to couple your code with transaction code, and mostly because these guys have been doing transactions in Java for many years and I just trust them that they know what to do.</li> </ol>
40,376
<p>I've had some trouble forking of processes from a Perl CGI script when running on Windows. The main issue seems to be that 'fork' is emulated when running on windows, and doesn't actually seem to create a new process (just another thread in the current one). This means that web servers (like IIS) which are waiting for the process to finish continue waiting until the 'background' process finishes.</p> <p>Is there a way of forking off a background process from a CGI script under Windows? Even better, is there a single function I can call which will do this in a cross platform way?</p> <p>(And just to make life extra difficult, I'd really like a good way to redirect the forked processes output to a file at the same time).</p>
<p>If you want to do this in a platform independent way, <a href="http://search.cpan.org/~bzajac/Proc-Background/lib/Proc/Background.pm" rel="nofollow noreferrer">Proc::Background</a> is probably the best way.</p>
<p><a href="http://www.xav.com/perl/lib/Pod/perlfork.html" rel="nofollow noreferrer">perlfork</a>:</p> <blockquote> <p>Perl provides a fork() keyword that corresponds to the Unix system call of the same name. On most Unix-like platforms where the fork() system call is available, Perl's fork() simply calls it.</p> <p>On some platforms such as Windows where the fork() system call is not available, Perl can be built to emulate fork() at the interpreter level. While the emulation is designed to be as compatible as possible with the real fork() at the the level of the Perl program, there are certain important differences that stem from the fact that all the pseudo child ``processes'' created this way live in the same real process as far as the operating system is concerned.</p> </blockquote>
6,779
<p><em>[This question is related to but not the same as <a href="https://stackoverflow.com/questions/206106/is-a-safe-way-to-convert-to-bool-in-c">this one</a>.]</em></p> <p>My compiler warns about implicitly converting or casting certain types to bool whereas explicit conversions do not produce a warning:</p> <pre><code>long t = 0; bool b = false; b = t; // performance warning: forcing long to bool b = (bool)t; // performance warning b = bool(t); // performance warning b = static_cast&lt;bool&gt;(t); // performance warning b = t ? true : false; // ok, no warning b = t != 0; // ok b = !!t; // ok </code></pre> <p>This is with Visual C++ 2008 but I suspect other compilers may have similar warnings.</p> <p>So my question is: what is the performance implication of casting/converting to <code>bool</code>? Does explicit conversion have better performance in some circumstance (e.g., for certain target architectures or processors)? Does implicit conversion somehow confuse the optimizer?</p> <p>Microsoft's <a href="http://msdn.microsoft.com/en-us/library/b6801kcy.aspx" rel="noreferrer">explanation</a> of their warning is not particularly helpful. They imply that there is a good reason but they don't explain it.</p>
<p>I was puzzled by this behaviour, until I found this link:</p> <p><a href="http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99633" rel="noreferrer">http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=99633</a></p> <p>Apparently, coming from the Microsoft Developer who "owns" this warning:</p> <blockquote> <p><i> This warning is surprisingly helpful, and found a bug in my code just yesterday. I think Martin is taking "performance warning" out of context.</p> <p><b>It's not about the generated code, it's about whether or not the programmer has signalled an intent to change a value from int to bool</b>. There is a penalty for that, and the user has the choice to use "int" instead of "bool" consistently (or more likely vice versa) to avoid the "boolifying" codegen. [...]</p> <p><b>It is an old warning, and may have outlived its purpose, but it's behaving as designed here.</b> </i></p> </blockquote> <p>So it seems to me the warning is more about style and avoiding some mistakes than anything else.</p> <p>Hope this will answer your question...</p> <p>:-p</p>
<p>I don't think performance is the issue here. The reason you get a warning is that information is lost during conversion from int to bool.</p>
25,306
<p>I am playing movie using MPMoviePlayerController,</p> <p>I am using TableView,what happening with my application is when I press accessory button it will display detailed view and when I press cell area it will play movie that I wanted,(the way youtube application does)</p> <p>but when I press "DONE" while playin movie it'll navigate to a view which is not my detail view but some empty view.</p> <p>Any idea what should I do to achieve it so that when user press "DONE" it will nevigate me to my detail view instead of some empty view.</p> <p>I tried to push view when "movieFinishedCallback" is executed but it'll pushing one more view on that empty view.</p>
<p>Ideally if your code is correct, pressing the Done button on MPMoviePlayerController object would close the MPMOviePlayerController and return to the controller which invoked it (which in your case is the detail view)</p> <p>You do not need to do anything in the movieDidFinishCallback except maybe release the movieplayer object.</p>
<pre><code>-(void)myMovieFinishedCallback:(NSNotification*)aNotification { MPMoviePlayerController* theMovie = [aNotification object]; theMovie.initialPlaybackTime = -1.0; } </code></pre>
49,762
<p>I have a J2EE project in Eclipse 3.2 and at the end of every build I want to automatically create and deploy a WAR file. At the moment I have to do this by hand which is 5 or 6 mouse-cliks and it would be nice to automate it.</p> <p>I know I can do this with a custom build script using ANT but I am hoping for an Eclipse native solution.</p> <p>I have the J2EE standard tools (JST) and Web Standard Tools (WST) plug-ins installed in my Eclipse environment.</p>
<p>If you can implement it as an Ant script, then you can have Eclipse invoke that Ant script on each build automatically (and inside the Eclipse environment). Use Project->Properties->Builders->Add->Ant Builder. Give that builder you custom Ant script and it will automatically be executed after the "normal" builders of your project.</p>
<p>Right click on your project: Export -> Web -> WAR File Do what you want to do.</p>
45,251
<p>I have a SQL SELECT query which has a LIKE clause containing an underscore, which should specifically look for an underscore, not treat it as a wildcard: </p> <pre><code>SELECT * FROM my_table WHERE name LIKE '_H9%'; </code></pre> <p>I understand that I can change the actual clause to '[_]H9%' for this to work as I expect, but the problem is that this clause is being generated by Hibernate.</p> <p>Is there a way to configure Hibernate to escape all underscores in all queries in this way? Failing that, is there a way to configure SQL Server (2008 in my case) to <em>not</em> treat underscores as wildcards?</p>
<p>If you're using Criteria to create the query, you can create your own expression which subclasses org.hibernate.criterion.LikeExpression, using one of the protected constructors that takes in 'Character escapeChar', and does substitution in the value for you. Assuming that '!' is a known value that won't be in any search strings (you can pick any you like, I guess), you can just do:</p> <pre><code>public class EscapingLikeExpression extends LikeExpression { public EscapingLikeExpression(String propertyName, String value) { super(propertyName, escapeString(value), '!', false); } static String escapeString(String inputString) { inputString = inputString.replace("_", "!_"); return inputString; } } </code></pre> <p>if there ARE no such characters (that won't appear in your search value as literals) then add the following as the first line of escapeString() to escape those too:</p> <pre><code> inputString = inputString.replace("!", "!!"); </code></pre>
<p>Why can you not do a string replacement on the value? How is this being used so that this is a non-workable solution?</p>
37,814
<p>I would like to print multiple parts continuously (non-interactively), so I can leave the printer alone for a longer time. So after finish, parts could be moved somehow out from the printing area, so the next can start.</p> <p>Are there any methods of achieving that with standard desktop printers without having to use multiple printers?</p>
<p>The only thing I can think of off hand is an old mod for the early MakerBot machines. It first was released for the Thing-O'-Matic I believe, but is compatible with Replicator 1 machines (and its knock-offs). Here's the <a href="http://www.thingiverse.com/thing:4056" rel="noreferrer">Thingiverse page</a>, but look up Automatic Build Plate.</p> <p>Essentially, you can use the Replicator G slicing program and there is a setting for "ABP" or Automatic Build Plate. This will basically tell the ABP to run its routine after the controller receives the response that the printing program is done and roll the finished part off the edge of the build plate, then start the same program over again.</p> <p>Drawbacks:</p> <ul> <li>I don't think it's easily compatible with newer machines/slicers. But, it's open source</li> <li>Pretty sure you have to use Replicator G, which is outdated now and may make your machine sound like it's going to fall apart (I know from experience)</li> </ul> <p>Going off of @Pete's answer about solenoids. It reminded me that someone integrated a <a href="http://www.thingiverse.com/thing:872617" rel="noreferrer">solenoid "ejector"</a> (aka Boxing Glove) for their machine.</p> <p>Update (06/08/2016):</p> <p>Forgot to mention that if you choose to create your own "Boxing Glove" or conveyor belt, some software such as Octo-Pi and Repetier-Host allow plugins. So, you could interface with your hardware via customized code and integrate the functionality directly into the slicing application for the full closed loop operation.</p>
<p>I Don't really think that it is possible without hardware modifications, or maybe some small parts that will fit in the bed of the printer all on the same time</p>
106
<p>I am considering making use of GWT as the front-end to an <strong>existing</strong> web application.</p> <p>I can't justify a complete rewrite to 100% GWT in one go. It is likely that I would migrate parts of the system to GWT gradually. However for consistency I would like to make use of the GWT TabPanel, MenuBar, etc as global interface elements from day one.</p> <p>As an experiment to see how 'legacy' parts of the system could be incorporated, I have done the following. </p> <p>The application's main page template now loads a small 'wrapper' GWT module on every page. This GWT module looks for a selection of DIVs in the dynamically generated host page. If the DIV is found, a suitable widget is slotted into place, i.e. menuBar, tabPanel.</p> <p>A lot of the configuration for the included widgets can also be slotted into the host page as JSON structures. For instance, I have implemented an adapter that dynamically sets up a TabPanel in this way. I've also added some very simple widgets that load remote HTML, etc.</p> <p>As a prototype, this all appears to work <strong>perfectly</strong> and loads quickly. However, it seems that GWT apps are really designed to be run from a single host page, not hundreds of dynamically generated ones.</p> <p>Can anyone highlight any issues that the above approach may run into, particularly as the GWT module increases in size? I would aim to keep the legacy wrapper module intentionally lean. Other functionality would be implemented in separate modules.</p> <p>How have other people integrated GWT into their front end in a gradual fashion?</p>
<p>One of the ways GWT was designed to be used is exactly as you've used it. We have done that in many of our apps - where there is one GWT module with multiple 'parts' that are loaded based on whether a given id exists on a page or not. So I don't see that you'll have any issues at all going this way. We often use this approach even for new web applications, where we just want a few 'widgets' on the page, rather than coding the whole application in GWT. </p> <p>It won't make a huge difference, but one thing I would suggest is not putting the GWT javascript code into your main template, but rather only put it on the pages that need it. It's true that if you're not running HTTPs it is cached basically forever, but it seems wrong to get people to load in the module if it's not actually needed on that page. This of course depends on how people use your site, if they are likely to download it anyway then it won't make any difference.</p>
<p>You're doing it right. Avoid avoid avoid the temptation to try to 'minimize' the GWT footprint by breaking it up into multiple separate apps. </p> <p>The key to GWT performance is to have as few downloads as possible and to make sure they're cached. Loading a 250k bundle once is much better than two 200k bundles and because compression get's better with larger files you really start to reap benefits as things grow. </p> <p>y-slow &amp; firebug can be really helpful when it comes to convincing yourself of this. </p> <p>One performance trick you might check out is available in the sample chapter here: <a href="http://www.infoq.com/articles/progwt" rel="nofollow noreferrer">http://www.infoq.com/articles/progwt</a> It shows a mini-architecture around loading GWT widgets into any number of slots and pre-populating data in JavaScript variables. This allows your GWT widgets to load and not require a second HTTP GET to get the data they use. In practice I found that this was a nice performance boost. </p>
47,403
<p>I'm trying to create a cube with a single measure. This measure is a distinct count of a "name" column. The cube works perfectly if the measure is set to "count" type. However when I set distinct count I get this error:</p> <p>"Errors in the OLAP storage engine: The sort order specified for distinct count records is incorrect"</p> <p>I have read in some blogs that you can only have a distinct count on a numeric column. I can't see a good reason for this, and I can't find that info on official documentation. However, it may be true. Anyways, I'm really stuck with this issue. What are my options? </p>
<p>my answer may be too late for you, but hope this can help other which have the same problem. </p> <ol> <li>Go to the data source view in Solution Explorer</li> <li>Find a table which contains the GUID column which needs to be aggregated</li> <li>Right-click on the header of the selected table and select 'Create Named Calculation'</li> <li>Give it a name</li> <li>Type the following in the Expression field: <strong>CAST(ColumnName as varchar(36))</strong></li> </ol> <p>This solution is from this link <a href="http://www.bi-dw.info/sql-server-tips/distinct_count-measure-on-uniqueidentifier.htm" rel="noreferrer">http://www.bi-dw.info/sql-server-tips/distinct_count-measure-on-uniqueidentifier.htm</a></p>
<p>I will answer myself, maybe this is helpful for somebody else.</p> <p>The short answer is YES.</p> <p>I have created some test tables with the same structure but just a few test rows. The cube works perfectly with this data.</p> <p>So, I guess there are some corrupt data on the original tables, or maybe some rare chars. </p>
41,446
<p>My web application generates pdf files and either e-mails or faxes them to our customers. Somehow IIS6 is keeping hold of the file and blocking any other requests for it claiming the old '..the process cannot access the file 'xxx.pdf' because it is being used by another process.'</p> <p>When I recycle the application pool all is ok. Does anybody know why this is happening and how can I stop it.</p> <p>Thanks</p>
<p>As with everyone said, do call the <code>Close</code> and <code>Dispose</code> method on any IO objects you have open when reading/writing the PDF files.</p> <p>But I suppose you'd incorporated a <strong>3rd party component?</strong> to do the PDF writing for you? If that's the case you might want to check with the vendor and/or its documentation to make sure that you are doing things in the way the vendors intended them to be. Don't trust the black box you got from someone else unless it has proven itself.</p> <p>Another place to look might be what happens during multiple web request to the PDF files, are you sure that the file is not written simultaneously from multiple places? e.g. 2-3 requests genrating PDF simultaneously? or 2-3 pages along the PDF generation process?</p> <p>And lastly, you might want to check the exception logs to make sure that nothing is crashing/thread exiting and leaving the file handle open without you noticing it. It happens a lot in multiple threading scenarios, sometimes the thread just crashes and exits - which could happen especially if you use 3rd party components, they might be performing some <em>magic</em> tricks, you'd never know.</p>
<p>I'd look through your code and make sure all handles to open (generated) files have been closed properly. Sometimes you just can't rely on the garbage collector to sort these things out.</p>
9,752
<p>I am getting the following error when I get to the line that invokes a REALLY BASIC web service I have running on Tomcat/Axis.</p> <pre><code>Element or attribute do not match QName production: QName::=(NCName':')?NCName </code></pre> <p>Have I got something wrong with QName?- I can't even find any useful information about it.</p> <p>My client code is below:</p> <pre><code>import javax.xml.namespace.QName; import org.apache.axis.client.Call; import org.apache.axis.client.Service; public class TestClient { public static void main(String [] args) { try{ String endpoint = "http://localhost:8080/TestWebService/services/DoesMagic"; Service service = new Service(); Call call = (Call) service.createCall(); call.setTargetEndpointAddress( new java.net.URL(endpoint) ); call.setOperationName( new QName("http://testPackage.fc.com/, doBasicStuff") ); String ret = (String) call.invoke( new Object[] {"some kind of message"} ); System.out.println(ret); }catch(Exception e){ System.err.println(e.toString()); } } } </code></pre> <p>My web serivce code is really basic - just a simple class that returns your input string with a bit of concat text:</p> <pre><code>public String doBasicStuff(String message) { return "This is your message: " + message; } </code></pre>
<p>As the exception says, you call the QName constructor incorrectly:</p> <pre><code>new QName("http://testPackage.fc.com/, doBasicStuff") </code></pre> <p>is incorrect. I think you have to pass two strings, one containing the namespace, one the localname. The documentation will typically contain a description on how to use that class.</p>
<p>You should use one of these:</p> <pre><code>public QName(String localPart) or public QName(final String namespaceURI, final String localPart) </code></pre> <p>but new QName("<a href="http://testPackage.fc.com/" rel="nofollow noreferrer">http://testPackage.fc.com/</a>, doBasicStuff") is wrong, since both values are in the same string ".., .."</p> <p>Regards</p>
24,600
<p>I'm running some JUnit tests on my applications. Every test has a for loop calling respective method 10000 times. The tested methods produce a lot of log. These logs are also automatically collected by JUnit as test output. This situation takes to OutOfMemoryError because the string buffer where JUnit keeps the output becomes too large. I dont' need these logs during tests, so if there is a way to tell JUnit "don't keep program output" it would be enough. Any ideas?</p>
<p>What type of logging are you using? Is there some way you can override the default logging behavior to just disregard all log messages?</p>
<p>I would just increase the available memory.. Try adding -Xmx256m -Xmx256m to your VM.</p>
12,910
<p>I need to rename the database but when I do in <code>PGAdmin : ALTER DATABASE "databaseName" RENAME TO "databaseNameOld"</code> it told me that it cannot.</p> <p>How can I do it?</p> <p>(<strong>Version 8.3 on WindowsXP</strong>)</p> <p><strong>Update</strong></p> <ul> <li><p>The first error message : Cannot because I was connect to it. So I selected an other database and did the queries.</p></li> <li><p>I get a second error message telling me that it has come user connect. I see in the <code>PGAdmin</code> screen that it has many <code>PID</code> but they are inactive... I do not see how to kill them.</p></li> </ul>
<p>Try not quoting the database name:</p> <pre><code>ALTER DATABASE people RENAME TO customers; </code></pre> <p>Also ensure that there are no other clients connected to the database at the time. Lastly, try posting the error message it returns so we can get a bit more information.</p>
<p>For anyone running into this issue using DBeaver and getting an error message like this:</p> <pre><code>ERROR: database "my_stubborn_db" is being accessed by other users Detail: There is 1 other session using the database. </code></pre> <p>Disconnect your current connection, and reconnect to the same server with a connection that doesn't target the database you are renaming.</p> <p>Changing the active database is not enough.</p>
17,346
<p>How do I extract the value of a property in a PropertyCollection?</p> <p>If I drill down on the 'Properties' in the line below is visual studion I can see the value but how do I read it?</p> <pre><code>foreach (string propertyName in result.Properties.PropertyNames) { MessageBox.Show(ProperyNames[0].Value.ToString()); &lt;--Wrong! } </code></pre>
<p>Try this:</p> <pre><code>foreach (string propertyName in result.Properties.PropertyNames) { MessageBox.Show(result.Properties[propertyName].ToString()); } </code></pre> <p>Or this:</p> <pre><code>foreach (object prop in result.Properties) { MessageBox.Show(prop.ToString()); } </code></pre> <p>Also: there are a couple different PropertyCollections classes in the framework. These examples are based on the System.Data class, but you might also be using the System.DirectoryServices class. However, neither of those classes are really "reflection". Reflection refers to something different- namely the System.Reflection namespace plus a couple special operators.</p>
<p>Try:</p> <pre><code>foreach (string propertyName in result.Properties.PropertyNames) { MessageBox.Show(properyName.ToString()); &lt;--Wrong! } </code></pre>
30,185
<p>Here is one trivial question, that I am not sure how to handle. I need to display list of categories on every page, and to be able to choose items from a specific category to be displayed. I use asp.net MVC, and have chosen to create a user control that will display categories. My question is: what is the best approach to pass data to a user control. I already found some information in these blog posts:</p> <p><a href="http://weblogs.asp.net/stephenwalther/archive/2008/08/12/asp-net-mvc-tip-31-passing-data-to-master-pages-and-user-controls.aspx" rel="nofollow noreferrer">http://weblogs.asp.net/stephenwalther/archive/2008/08/12/asp-net-mvc-tip-31-passing-data-to-master-pages-and-user-controls.aspx</a></p> <p><a href="http://blog.matthidinger.com/2008/02/21/ASPNETMVCUserControlsStartToFinish.aspx" rel="nofollow noreferrer">http://blog.matthidinger.com/2008/02/21/ASPNETMVCUserControlsStartToFinish.aspx</a></p> <p>I would like also to hear your opinion.</p> <p>PS. I'd like to hear Jeff's opinion, especially because of his experience with UC's on Stackoverflow</p>
<p>I'm using mvc components, which replaced ascx user controls in preview 4.<br> Example: <a href="http://blog.wekeroad.com/blog/asp-net-mvc-preview-4-componentcontroller-is-now-renderaction/" rel="nofollow noreferrer">http://blog.wekeroad.com/blog/asp-net-mvc-preview-4-componentcontroller-is-now-renderaction/</a><br> So, you call components action from View, which then choose View to render. You can pass data in this call also. </p>
<p>it is the mvc futures project. i will probably try this <a href="http://forums.asp.net/t/1303328.aspx" rel="nofollow noreferrer">http://forums.asp.net/t/1303328.aspx</a>. I need to render menu with categories.</p>
3,449
<p>Some of my script are using different encoding, and when I try to combine them, this has becom an issue.</p> <p>But I can't change the encoding they use, instead I want to change the encodig of the result from script A, and use it as parameter in script B. </p> <p>So: is there any simple way to change a string from UTF-8 to ISO-88591 in PHP? I have looked at utf_encode and _decode, but they doesn't do what i want. Why doesn't there exsist any "utf2iso()"-function, or similar?</p> <p>I don't think I have characters that can't be written in ISO-format, so that shouldn't be an huge issue.</p>
<p>Have a look at <a href="http://php.net/function.iconv" rel="noreferrer"><code>iconv()</code></a> or <a href="http://php.net/function.mb-convert-encoding" rel="noreferrer"><code>mb_convert_encoding()</code></a>. Just by the way: why don't <a href="http://php.net/function.utf8-encode" rel="noreferrer"><code>utf8_encode()</code></a> and <a href="http://php.net/function.utf8-decode" rel="noreferrer"><code>utf8_decode()</code></a> work for you?</p> <blockquote> <p><strong>utf8_decode</strong> — Converts a string with ISO-8859-1 characters encoded with UTF-8 to single-byte ISO-8859-1</p> <p><strong>utf8_encode</strong> — Encodes an ISO-8859-1 string to UTF-8</p> </blockquote> <p>So essentially</p> <pre><code>$utf8 = 'ÄÖÜ'; // file must be UTF-8 encoded $iso88591_1 = utf8_decode($utf8); $iso88591_2 = iconv('UTF-8', 'ISO-8859-1', $utf8); $iso88591_2 = mb_convert_encoding($utf8, 'ISO-8859-1', 'UTF-8'); $iso88591 = 'ÄÖÜ'; // file must be ISO-8859-1 encoded $utf8_1 = utf8_encode($iso88591); $utf8_2 = iconv('ISO-8859-1', 'UTF-8', $iso88591); $utf8_2 = mb_convert_encoding($iso88591, 'UTF-8', 'ISO-8859-1'); </code></pre> <p>all should do the same - with <code>utf8_en/decode()</code> requiring no special extension, <code>mb_convert_encoding()</code> requiring ext/mbstring and <code>iconv()</code> requiring ext/iconv.</p>
<pre><code>function parseUtf8ToIso88591(&amp;$string){ if(!is_null($string)){ $iso88591_1 = utf8_decode($string); $iso88591_2 = iconv('UTF-8', 'ISO-8859-1', $string); $string = mb_convert_encoding($string, 'ISO-8859-1', 'UTF-8'); } } </code></pre>
48,965
<p>I have the next function:</p> <pre><code>function setImagesWidth(id,width) { var images = document.getElementById(id).getElementsByTagName("img"); for(var i = 0; i &lt; images.length;i++) { // If the real width is bigger than width parameter images[i].style.width=width; //} } } </code></pre> <p>I would like to set the css width attribute of all my img tags to a particular value only when the image real width is bigger than the attribute value. If it is possible, i would like a solution which does not use any particular framework. </p> <hr> <p><code>images[i].offsetWidth</code> returns 111 for an image of 109px width. Is this because 1px each side border? </p>
<p>Here is, hopefully, enough sample code to give you what you want:</p> <pre><code>var myImage = document.getElementById("myImagesId"); var imageWidth = myImage.offsetWidth; var imageHeight = myImage.offsetHeight; </code></pre> <p>That should give you the numbers you need to derive the solution you want. I think you can write the rest of the code yourself. :)</p> <hr> <p>EDIT: Here, I couldn't help myself - is this what you are after?</p> <pre><code>function setImagesWidth(id,width) { var images = document.getElementById(id).getElementsByTagName("img"); for(var i = 0; i &lt; images.length;i++) { if(images[i].offsetWidth &gt; width) { images[i].style.width= (width + "px"); } } } </code></pre>
<p>Careful, it looks like you might rather want <code>clientWidth</code>:</p> <p><a href="http://developer.mozilla.org/en/Determining_the_dimensions_of_elements" rel="nofollow noreferrer">http://developer.mozilla.org/en/Determining_the_dimensions_of_elements</a></p>
6,376
<p>I have a MySQL table consisting of:</p> <pre><code>CREATE TABLE `url_list` ( `id` int(10) unsigned NOT NULL auto_increment, `crc32` int(10) unsigned NOT NULL, `url` varchar(512) NOT NULL, PRIMARY KEY (`id`), KEY `crc32` (`crc32`) ); </code></pre> <p>When inserting data into a related table I need to lookup the primary key from this table, and using the crc32 really speeds that up whilst allowing a small index. The URLs do need to be unique, but I'd like to avoid having more index than actual data.</p> <p>If the value isn't present I need to insert it, but using structures such as <code>INSERT IGNORE</code>, or ON <code>DUPLICATE KEY</code> either requires me to put a unique on the huge varchar, or don't take advantage of my index.</p> <p>How can I "SELECT id else INSERT", whilst preserving the lookup speed for the 80-90% of hits that are already in the table?</p>
<p>I would recommend ditching the <code>id</code> column and the <code>crc32</code> because they're not necessary.</p> <p>You can use an <code>MD5()</code> hash to provide a fixed-length, virtually unique value computed from the lengthy URL data, and then use that hash as the primary key.</p> <pre><code>CREATE TABLE `url_list` ( `url_hash` BINARY(16) NOT NULL PRIMARY KEY `url` VARCHAR(512) NOT NULL ); DELIM !! CREATE TRIGGER `url_ins` BEFORE INSERT ON `url_list` FOR EACH ROW BEGIN SET NEW.`url_hash` = UNHEX( MD5( NEW.`url` ) ); END!! </code></pre> <p>Then you can use <code>INSERT..ON DUPLICATE KEY UPDATE</code> because unlike <code>crc32</code>, the hash should have a very low chance of collision.</p> <p><strong>edit:</strong> See <a href="http://en.wikipedia.org/wiki/Birthday_attack" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Birthday_attack</a>. If you log 1 million distinct URL's per day for 2,000 years, the MD5 hashes of these URL's are still less likely to include a collision than your hard disk is to have an uncorrectable bit error.</p>
<p><a href="http://blogs.msdn.com/miah/archive/2008/02/17/sql-if-exists-update-else-insert.aspx" rel="nofollow noreferrer">This website</a> offers a solution to a similar problem.</p>
41,054
<p>I am building a web page to show a customer what software they purchased and to give them a link to download said software. Unfortunately, the data on what was purchased and the download information are in separate databases so I can't just take care of it with joins in an SQL query.</p> <p>The common item is SKU. I'll be pulling a list of SKUs from the customer purchases database and on the download table is a comma delineated list of SKUs associated with that download. My intention, at the moment, is to create from this one datatable to populate a <code>GridView</code>.</p> <p>Any suggestions on how to do this efficiently would be appreciated. If it helps, I can pretty easily pull back the data as a <code>DataSet</code> or a <code>DataReader</code>, if either one would be better for this purpose.</p>
<p>As long as the two databases are on the same physical server (assuming MSSQL) and the username/password being used in the connection string has rights to both DBs, then you should be able to perform a join across the two databases. Example: </p> <pre><code>select p.Date, p.Amount, d.SoftwareName, d.DownloadLink from PurchaseDB.dbo.Purchases as p join ProductDB.dbo.Products as d on d.sku = p.sku where p.UserID = 12345 </code></pre>
<p>I am thinking off the top of my head here. If you load both as Data Tables in the same Data Sets, and define a relation between the two over SKU, and then run a query on the Data Set which produces the desired result.</p>
2,445
<p>I'm looking for a cross-browser method - I know IE has something (I've already forgotten what), and the way to do it in Mozilla may have to do with a focusNode thing I found, that seems related to getting text selections.</p> <p>Methods involving jQuery or another common JS library are fine by me.</p> <p>Thanks!</p>
<p>Check out the <a href="http://www.softwareunity.com/sandbox/JQueryMoreSelectors/" rel="nofollow noreferrer">extra selectors plugin</a> for <a href="https://jquery.com/" rel="nofollow noreferrer">jQuery</a>, it includes a <code>:focus</code> selector that answers your need. You can use just the implementation of that selector if you don't the rest.</p>
<p>OK then, so use jQuery.</p> <p>There is no current, available way to just ask this. You need to track the focus events when they happen, so this sample (thanks to Karl Rudd <a href="http://groups.google.com/group/jquery-en/browse_thread/thread/e31e21ba4ef3160c/21c2d4c016336fad?lnk=raot&amp;pli=1" rel="nofollow noreferrer">here</a>) does that across all elements. This is for inputs but you can adjust the selector to fit your needs, even across the entire DOM.</p> <pre><code>var currentFocus = null; $(':input').focus( function() { currentFocus = this; }).blur( function() { currentFocus = null; }); </code></pre>
18,241
<p>What is the best way to scale a 2D image array? For instance, suppose I have an image of 1024 x 2048 bytes, with each byte being a pixel. Each pixel is a grayscale level from 0 to 255. I would like to be able to scale this image by an arbitrary factor and get a new image. So, if I scale the image by a factor of 0.68, I should get a new image of size 0.68*1024 x 0.68*2048. some pixels will be collapsed onto each other. And, if I scale by a factor of say 3.15, I would get a larger image with pixels being duplicated. So, what's the best way to accomplish this?</p> <p>Next, I would like to be able to rotate an image by an arbitrary angle, in the range of 0 to 360 degrees (0 - 2Pi). Cropping of the image after rotating isn't an issue. What would be the best way to do this?</p>
<p>There is no simple way of accomplishing this. Neither <a href="http://en.wikipedia.org/wiki/Image_scaling" rel="nofollow noreferrer">scaling</a> nor rotating are trivial processes.</p> <p>It is therefore advisable to use a 2d imaging library. <a href="http://www.imagemagick.org/Magick++/" rel="nofollow noreferrer">Magick++</a> can be an idea as divideandconquer.se point out, but there are others.</p>
<pre><code>point scaling(point p,float sx,float sy) { point s; int c[1][3]; int a[1][3]={p.x,p.y,1}; int b[3][3]={sx,0,0,0,sy,0,0,0,1}; multmat(a,b,c); s.x=c[0][0]; s.y=c[0][1]; return s; } </code></pre>
38,333
<p>The fundamental equation of weight loss/gain is:</p> <pre><code>weight_change = convert_to_weight_diff(calories_consumed - calories_burnt); </code></pre> <p>I'm going on a health kick, and like a good nerd I thought I'd start keeping track of these things and write some software to process my data. I'm not attentive and disciplined enough to count calories in food, so I thought I'd work backwards:</p> <ul> <li>I can weigh myself every day</li> <li>I can calculate my BMR and hence how many calories I burn doing nothing all day</li> <li>I can use my heart-rate monitor to figure out how many calories I burn doing exercise</li> </ul> <p>That way I can generate an approximate "calories consumed" graph based on my exercise and weight records, and use that to motivate myself when I'm tempted to have a donut.</p> <p>The thing I'm stuck on is the function:</p> <pre><code>int convert_to_weight_diff(int calorie_diff); </code></pre> <p>Anybody know the pseudo-code for that function? If you've got some details, make sure you specify if we're talking calories, Calories, kilojoules, pounds, kilograms, etc.</p> <p>Thanks! </p>
<p>Look at <a href="http://www.fourmilab.ch/hackdiet/www/hackdiet.html" rel="nofollow noreferrer">The Hacker's Diet</a> and <a href="http://www.physicsdiet.com/" rel="nofollow noreferrer">physicsdiet.com</a> - this wheel has already been invented.</p>
<p>I dunno how accurate this is because it's Wikipedia but it looks like a good basis for a rule-of-thumb-o-meter.</p> <p><a href="http://en.wikipedia.org/wiki/Food_energy" rel="nofollow noreferrer">http://en.wikipedia.org/wiki/Food_energy</a></p>
28,850
<p>In Ruby (forgive me for mentioning it's name) I noticed you could do a anchor link with "link to unless current", which would remove the link if it was the current page.</p> <p>I know there's nothing built into CodeIgniter to do something similar, but I'm trying to come up with the best way to do this. I've got a few options, but they're all too long and cumbersome. Does anyone have any ideas (maybe using the URI segment)?</p>
<p>Why not write your own helper that follows the html helper link_tag checker... put one more condition inside there to check if your in the current controller. Looking at codeIgniter with xdebug, the object returned by get_instance provides access to pretty much everything the controller had. so ci->router->uri->rsegments could be used to check for your controller action. </p> <p>Edit: Sorry forgot the "uri" part in that chain above.</p>
<p>You can</p> <p>A. Use an if statement around the link</p> <p>or</p> <p>B. Make your own function</p> <p>CodeIgniter is a significantly smaller framework than ruby on rails as far as features go. I doubt they have a copy of every useful function rails has. </p>
33,058
<p>I have a validation control that has the following expression:</p> <pre><code>(?=(.*\\d.*){2,})(?=(.*\\w.*){2,})(?=(.*\\W.*){1,}).{8,} </code></pre> <p>That's a password with at least <strong>2 digits</strong>, <strong>2 alpha characters</strong>, <strong>1 non-alphanumeric</strong> and <strong>8 character minimum</strong>. Unfortunately this doesn't seem to be cross-browser compliant.</p> <p>This validation works perfectly in Firefox, but it does not in Internet Explorer.</p> <p><strong><em>A combination of each of your answers results in:</em></strong></p> <pre><code>var format = "^(?=.{" + minLength + ",})" + (minAlpha &gt; 0 ? "(?=(.*[A-Za-z].*){" + minAlpha + ",})" : "") + (minNum &gt; 0 ? "(?=(.*[0-9].*){" + minNum + ",})" : "") + (minNonAlpha &gt; 0 ? "(?=(.*\\W.*){" + minNonAlpha + ",})" : "") + ".*$"; EX: "^(?=.{x,})(?=(.*[A-Za-z].*){y,})(?=(.*[0-9].*){z,})(?=(.*\W.*){a,}).*$" </code></pre> <p>The important piece is having the (?.{x,}) for the length <strong>first</strong>.</p>
<p><code>(?=(.*\W.*){0,})</code> is not 0 non-alphanumeric characters. It is <em>at least 0</em> non-alphanumeric characters. If you wanted the password to not contain any non-alphanumeric characters you could do either <code>(?!.*\W)</code> or <code>(?=\w*$)</code>.</p> <p>A simpler solution would be to skip the <code>\W</code> look-ahead, and use <code>\w{8,}</code> instead of <code>.{8,}</code>.</p> <p>Also, <code>\w</code> includes <code>\d</code>. If you wanted just the alpha you could do either <code>[^\W\d]</code> or <code>[A-Za-z]</code>.</p> <pre><code>/^(?=(?:.*?\d){2})(?=(?:.*?[A-Za-z]){2})\w{8,}$/ </code></pre> <p>This would validate the password to contain at least <strong>two digits</strong>, <strong>two alphas</strong>, be <strong>at least 8 characters long</strong>, and contain <strong>only alpha-numeric characters</strong> (including underscore).</p> <ul> <li><code>\w</code> = <code>[A-Za-z0-9_]</code></li> <li><code>\d</code> = <code>[0-9]</code></li> <li><code>\s</code> = <code>[ \t\n\r\f\v]</code></li> </ul> <p><strong>Edit:</strong> To use this in all browsers you probably need to do something like this:</p> <pre><code>var re = new RegExp("^(?=(?:.*?\\d){2})(?=(?:.*?[A-Za-z]){2})\\w{8,}$"); if (re.test(password)) { /* ok */ } </code></pre> <p><strong>Edit2:</strong> The recent update in the question almost invalidates my whole answer. <code>^^;;</code></p> <p>You should still be able to use the JavaScript code in the end, if you replace the pattern with what you had originally.</p> <p><strong>Edit3:</strong> OK. Now I see what you mean.</p> <pre><code>/^(?=.*[a-z].*[a-z])(?=.*[0-9].*[0-9]).{3,}/.test("password123") // matches /^(?=.*[a-z].*[a-z])(?=.*[0-9].*[0-9]).{4,}/.test("password123") // does not match /^(?=.*[a-z].*[a-z]).{4,}/.test("password123") // matches </code></pre> <p>It seems <code>(?= )</code> isn't really zero-width in Internet Explorer.</p> <p><a href="http://development.thatoneplace.net/2008/05/bug-discovered-in-internet-explorer-7.html" rel="noreferrer">http://development.thatoneplace.net/2008/05/bug-discovered-in-internet-explorer-7.html</a></p> <p><strong>Edit4:</strong> More reading: <a href="http://blog.stevenlevithan.com/archives/regex-lookahead-bug" rel="noreferrer">http://blog.stevenlevithan.com/archives/regex-lookahead-bug</a></p> <p>I think this can solve your problem:</p> <pre><code>/^(?=.{8,}$)(?=(?:.*?\d){2})(?=(?:.*?[A-Za-z]){2})(?=(?:.*?\W){1})/ new RegExp("^(?=.{8,}$)(?=(?:.*?\\d){2})(?=(?:.*?[A-Za-z]){2})(?=(?:.*?\\W){1})") </code></pre> <p>The <code>(?=.{8,}$)</code> needs to come first.</p>
<p>How about one of the existing jQuery based password strength validators - like: <a href="http://scripts.simplythebest.net/4/Ajax-Password-Strength-Meter-software.html" rel="nofollow noreferrer">http://scripts.simplythebest.net/4/Ajax-Password-Strength-Meter-software.html</a></p>
24,247
<p>During the load of my cocoa application, my program crashes with the messsage EXC_BAD_ACCESS. The stack trace is not helpful. Any clues to how I can find the problem?</p>
<p>I've seen times where this can happen when you are trying to access a object that you didn't retain properly so its either not pointing to a valid copy of your object or its pointing to an object of another type. Placing breakpoints early and analyzing the objects as you step through startup using po and print in gdb is your best bet.</p>
<p>This is one possible reason. There is a IBOutlet object that isn't being initialized and a message is being invoked on nil. The stack trace might look like this:</p> <pre><code>#0 0x90a594c7 in objc_msgSend #1 0xbffff7b8 in ?? #2 0x932899d8 in loadNib #3 0x932893d9 in +[NSBundle(NSNibLoading) _loadNibFile:nameTable:withZone:ownerBundle:] #4 0x9328903a in +[NSBundle(NSNibLoading) loadNibFile:externalNameTable:withZone:] #5 0x93288f7c in +[NSBundle(NSNibLoading) loadNibNamed:owner:] #6 0x93288cc3 in NSApplicationMain #7 0x00009f80 in main at main.mm:17 </code></pre> <p>Since the stack trace is not helpful you will have to step through your code to find the error. If for some reason you aren't able to set breakpoints early in your execution, try inserting some Debugger(); calls which will break to the debugger.</p>
9,054
<p>I need a short code snippet to get a directory listing from an HTTP server.</p> <p>Thanks</p>
<p>A few important considerations before the code:</p> <ol> <li>The HTTP Server has to be configured to allow directories listing for the directories you want;</li> <li>Because directory listings are normal HTML pages there is no standard that defines the format of a directory listing;</li> <li>Due to consideration <strong>2</strong> you are in the land where you have to put specific code for each server.</li> </ol> <p>My choice is to use regular expressions. This allows for rapid parsing and customization. You can get specific regular expressions pattern per site and that way you have a very modular approach. Use an external source for mapping URL to regular expression patterns if you plan to enhance the parsing module with new sites support without changing the source code.</p> <p>Example to print directory listing from <a href="http://www.ibiblio.org/pub/" rel="noreferrer">http://www.ibiblio.org/pub/</a></p> <pre><code>namespace Example { using System; using System.Net; using System.IO; using System.Text.RegularExpressions; public class MyExample { public static string GetDirectoryListingRegexForUrl(string url) { if (url.Equals("http://www.ibiblio.org/pub/")) { return "&lt;a href=\".*\"&gt;(?&lt;name&gt;.*)&lt;/a&gt;"; } throw new NotSupportedException(); } public static void Main(String[] args) { string url = "http://www.ibiblio.org/pub/"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { using (StreamReader reader = new StreamReader(response.GetResponseStream())) { string html = reader.ReadToEnd(); Regex regex = new Regex(GetDirectoryListingRegexForUrl(url)); MatchCollection matches = regex.Matches(html); if (matches.Count &gt; 0) { foreach (Match match in matches) { if (match.Success) { Console.WriteLine(match.Groups["name"]); } } } } } Console.ReadLine(); } } } </code></pre>
<p>You can't, unless the particular directory you want has directory listing enabled and no default file (usually index.htm, index.html or default.html but always configurable). Only then will you be presented with a directory listing, which will usually be marked up with HTML and require parsing.</p>
15,150
<p>I'm missing something here, but I've stared at it too long to see it. I've got a simple ListView, with the typical Edit/Update/Cancel buttons. I've got the following set up in my EditITemTemplate when the row goes into edit mode:</p> <pre><code>&lt;EditItemTemplate&gt; &lt;asp:Label ID="AccountIdLabel" runat="server" Text='&lt;%#Eval("lan_id")%&gt;' /&gt; &lt;asp:TextBox ID="EmployeeIdTextBox" runat="server" Text='&lt;%#Eval("emp_id")%&gt;' Columns="5" /&gt; &lt;/EditItemTemplate&gt; </code></pre> <p>At this point the user types a value in the EmployeeIdTextBox. When they press Update, it's trying to do the following:</p> <pre><code>Private Sub ListView_ItemUpdating(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ListViewUpdateEventArgs) Handles EmployeeListView.ItemUpdating Dim accountId = CType(EmployeeListView.EditItem.FindControl("AccountIdLabel"), Label).Text Dim employeeId = CType(EmployeeListView.EditItem.FindControl("EmployeeIdTextBox"), TextBox).Text UpdateMap(accountId, employeeId) EmployeeListView.EditIndex = -1 GetData() End Sub </code></pre> <p>The problem is that "employeeId" is coming back with the original value in the text box, not what the user entered. What am I missing?</p> <p>UPDATE: <a href="https://stackoverflow.com/questions/321819/getting-edit-value-from-listview#322175">Found it</a>. As usual, caused by other code not included here in an effort to ask a simple question. :)</p>
<p>Found it - I had code in the ItemCommand event that was handling other events, but it was doing the GetData() at the end regardless of the command, so basically the data was being refreshed right before the ItemUpdating event fired. I tightened up ItemCommand, and it's now working as expected.</p>
<p>I think this is because the ItemUpdating event fires before the ListView updates the record. You probably want to put this code in the ItemUpdated event instead.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemupdating.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.listview.itemupdating.aspx</a></p>
41,656
<p>I am particularly interested in Document Libraries, but in terms of general SharePoint lists, can anyone answer the following...?</p> <ol> <li>What is the maximum number of items that a SharePoint list can contain?</li> <li>What is the maximum number of lists that a single SharePoint server can host?</li> <li>When the number of items in the list approaches the maximum, does filtering slow down, and if so, what can be done to improve it?</li> </ol>
<p>In SharePoint v.2:</p> <ul> <li><strong>Max # list items</strong> : 2000 (per folder level)</li> <li><strong>Max lists per site</strong> : 2000 is a "reasonable" number</li> <li><strong>Effect when we reach the limit</strong> : Exponential degradation of performance.</li> </ul> <p>More info: <a href="http://technet.microsoft.com/en-us/library/cc287743.aspx" rel="noreferrer">http://technet.microsoft.com/en-us/library/cc287743.aspx</a></p> <p>In SharePoint v.3:</p> <ul> <li><strong>Max # list items</strong> : 2000 (per view, you can have million items as long as you don't display in a single view more than 2000 items)</li> <li><strong>Max lists per site</strong> : 2000 is a "reasonable" number</li> <li><strong>Effect when we reach the limit</strong> : Exponential degradation of performance when we enumerate more than 2000 items using the OM. An alternative is to use Search API or CAML queries.</li> </ul> <p>More info: <a href="http://technet.microsoft.com/en-us/library/cc287790.aspx" rel="noreferrer">http://technet.microsoft.com/en-us/library/cc287790.aspx</a></p>
<p>Beware, the Performance of SiteDataQuery degrades heavily he more subsites you have. A hundred subsites can take 20 seconds to query.</p>
5,509
<p>I am using Java back end for creating an XML string which is passed to the browser. Currently I am using simple string manipulation to produce this XML. Is it essential that I use some XML library in Java to produce the XML string? I find the libraries very difficult to use compared to what I need.</p>
<p>It's not essential, but advisable. However, if string manipulation works for you, then go for it! There are plenty of cases where small or simple XML text can be safely built by hand.</p> <p>Just be aware that creating XML text is harder than it looks. Here's some criteria I would consider:</p> <ul> <li>First: how much <em>control</em> do you have on the information that goes into the xml?</li> </ul> <p>The less control you have on the source data, the more likely you will have trouble, and the more advantageous the library becomes. For example: (a) Can you <em>guarantee</em> that the element names will never have a character that is illegal in a name? (b) How about quotes in an attribute's content? Can they happen, and are you handling them? (c) Does the data ever contain anything that might need to be encoded as an <a href="http://en.wikipedia.org/wiki/XML_entity" rel="noreferrer">entity</a> (like the less-than which often needs to be output as <strong>&amp;lt;</strong>); are you doing it correctly?</p> <ul> <li>Second, maintainability: is the code that builds the XML easy to understand <em>by someone else</em>?</li> </ul> <p>You probably don't want to be stuck with the code for life. I've worked with second-hand C++ code that hand-builds XML and it can be surprisingly obscure. Of course, if this is a personal project of yours, then you don't need to worry about "others": substitute "in a year" for "others" above.</p> <p>I wouldn't worry about performance. If your XML is simple enough that you can hand-write it, any overhead from the library is probably meaningless. Of course, your case might be different, but you should measure to prove it first.</p> <p>Finally, Yes; you can hand build XML text by hand if it's simple enough; but not knowing the libraries available is <em>probably</em> not the right reason.</p> <p>A modern XML library is a quite powerful tool, but it can also be daunting. However, learning the essentials of your XML library is not that hard, and it can be quite handy; among other things, it's almost a requisite in today's job marketplace. Just don't get bogged down by namespaces, schemas and other fancier features until you get the essentials.</p> <p>Good luck.</p>
<p>No - especially for generating (parsing I would be less inclined to as input text can always surprise you). I think its fine - but be prepared to shift to a library should you find yourself spending more then a few minutes maintaining your own code. </p>
4,450
<p>I've been for the past few hours trying to figure out why <code>openCV</code> doesn't compile on leopard. I've been googling for references but all point to a dead google group.</p> <p>So my question is quite simple: I've read INSTALL file, read all documentation <em>i</em> could find and still couldn't figure a solution for this.</p> <p>The compile breaks here (this is generated through the Makefile):</p> <blockquote> <p><code>rm -fr</code> <code>.libs/libcxcore.lax/lib_cxcore.a mkdir</code> <code>.libs/libcxcore.lax/lib_cxcore.a</code> <code>Extracting /Users/fmsf/Projects/Motion</code> <code>Tracking/Libs/opencv-1.1.0/cxcore/src/./.libs/lib_cxcore.a (cd .libs/libcxcore.lax/lib_cxcore.a</code> <code>&amp;&amp; ar x /Users/fmsf/Projects/Motion</code> <code>Tracking/Libs/opencv-1.1.0/cxcore/src/./.libs/lib_cxcore.a) ar: /Users/fmsf/Projects/Motion: No</code> <code>such file or directory make[2]: ***</code> <code>[libcxcore.la] Error 1 make[1]: ***</code> <code>[check-recursive] Error 1 make: ***</code> <code>[check-recursive] Error 1</code></p> </blockquote> <p>Does anyone know what <em>i</em> could do to build it? I'm using mac os 1.5 leopard, while reading <em>i</em> found the full port for Mac OS is still unfinished, but I don't really believe it's the missing of this library. </p>
<p>Based on the error, my suggestion is:</p> <p>Try building it in a folder that doesn't have spaces in the name.</p> <p>("/Users/fmsf/Projects/Motion Tracking/" vs "ar: /Users/fmsf/Projects/Motion: No such file or directory")</p>
<p>you may be trying 1.1. this is pretty new. consider trying 1.0. i have built 1.0 on windows and ubuntu.</p>
30,833
<p>I plan to serialize a Django model to XML when it's saved or updated. (The XML's going to be imported into a flash movie). Is it better to listen for a post_save() or pre_save() signal and then perform the serialization, or to just handle it in the model's save() methon</p>
<p>If it's core functionality for saving the model you'll want it as part of the save method. However, if you already have a functioning model and you want to extend it for other purposes then signals are your best bet since they allow for properly decoupled modules.</p> <p>A good example might be that you want to add event logging to your site, so you simply listen for the signals that signify an event rather than modifying the original site code.</p> <p>post_save() is usually best because it means the model has been successfully saved, using pre_save() doesn't guarantee that the save will be successful so shouldn't be used for anything that would depend on the save being completed.</p>
<p>Post save. That way the new data (the reason for performing the serialization) is already in the database. It'll make for a much cleaner bit of code that simply takes from the database and doesn't have to worry about adding an extra value.</p> <p>The other way that comes to mind is to maintain the xml file in parallel to the database. That is to say, in your save() add the data to the database, and to the xml file. This would have a much less overhead if you're dealing with huge tables.</p>
15,940
<p>What is the most efficient way of setting values in C# multi-dimensional arrays using a linear index? For example given an array...</p> <pre><code>int[,,] arr2 = { {{0,1,2}, {3,4,5}, {6,7,8}} , {{9,10,11}, {12,13,14}, {15,16,17}} , {{18,19,20}, {21,22,23}, {24,25,26}} }; </code></pre> <p>How do I set all the elements to 30 using a linear index ...</p> <pre><code>//This code does not work for (int i = 0; i &lt; arr.Length; i++) { arr.SetValue(30, i); } </code></pre> <p>Apparently the SetValue() above does not work with multidimensional arrays.</p> <p>Here is the best solution that I could come up with...</p> <p>EDIT: Added some clarifications to the code...</p> <pre><code>static class Program { static void Main(string[] args) { //Sample input. int[,,] arr2 = { {{0,1,2}, {3,4,5}, {6,7,8}} , {{9,10,11}, {12,13,14}, {15,16,17}} , {{18,19,20}, {21,22,23}, {24,25,26}} }; int[] arr1 = { 1, 2, 3, 4 }; setElementsTo30(arr2); setElementsTo30(arr1); } //Must be able to process int arrays of arbitrary dimensions and content private static void setElementsTo30(Array arr) { IList&lt;int&gt; cumulativeLength = getCumulativeLengths(arr); for (int i = 0; i &lt; arr.Length; i++) { SetValue(arr, i, 30, cumulativeLength); } } public static void SetValue(this Array arr, int index, object value, IList&lt;int&gt; cumulativeLength) { int[] arrayIndex = new int[arr.Rank]; for (int dim = arr.Rank-1; dim &gt;= 0; dim--) { arrayIndex[dim] = index / cumulativeLength[dim] % arr.GetLength(dim); } arr.SetValue(value, arrayIndex); } private static IList&lt;int&gt; getCumulativeLengths(Array arr) { List&lt;int&gt; lengths = new List&lt;int&gt;(arr.Rank); for (int dim = 0; dim &lt; arr.Rank; dim++) { int prod = 1; for (int i = dim + 1; i &lt; arr.Rank; i++) { prod *= arr.GetLength(i); } lengths.Add(prod); } return (IList&lt;int&gt;)lengths; } } </code></pre> <p>Is there a way to do the same more efficiently and possibly using something provided by the framework itself (i.e. something which can be used without much hassle.)</p> <p>Thanks,<br> SDX2000.</p>
<p>why do you need the IList ? </p> <pre><code>static void SetValue2(this Array a, object value, int i) { int[] indices = new int[a.Rank]; for (int d = a.Rank - 1; d &gt;= 0; d--) { var l = a.GetLength(d); indices[d] = i % l; i /= l } a.SetValue(value, indices); } </code></pre> <p>Test Code:</p> <pre><code>static void Main(string[] args) { int[, ,] arr2 = { {{0,1,2}, {3,4,5}, {6,7,8}}, {{9,10,11}, {12,13,14}, {15,16,17}}, {{18,19,20}, {21,22,23}, {24,25,26}} }; for (int i = 0; i &lt; arr2.Length; i++) { arr2.SetValue2(30, i); } } </code></pre>
<p><code>SetValue()</code> should work. Take a look at <a href="http://msdn.microsoft.com/en-us/library/758awxk7.aspx" rel="nofollow noreferrer">this</a> for a little more inspiration.</p> <p>EDIT: Could you not just do</p> <pre><code>{{30,30,30}, {30,30,30}, {30,30,30}} , {{30,30,30}, {30,30,30}, {30,30,30}} , {{30,30,30}, {30,30,30}, {30,30,30} } </code></pre> <p>As a side note, are you sure you want to return an <code>IList&lt;int&gt;</code> from <code>getCumulativeLengths</code>?</p> <p>I always thought, be generous on input, and strict on output. </p>
46,956
<p>Is there ever a good reason to <em>not</em> declare a virtual destructor for a class? When should you specifically avoid writing one?</p>
<p>There is no need to use a virtual destructor when any of the below is true:</p> <ul> <li>No intention to derive classes from it</li> <li>No instantiation on the heap</li> <li>No intention to store with access via a pointer to a superclass</li> </ul> <p>No specific reason to avoid it unless you are really so pressed for memory.</p>
<p>The performance answer is the only one I know of which stands a chance of being true. If you've measured and found that de-virtualizing your destructors really speeds things up, then you've probably got other things in that class that need speeding up too, but at this point there are more important considerations. Some day someone is going to discover that your code would provide a nice base class for them and save them a week's work. You'd better make sure they do that week's work, copying and pasting your code, instead of using your code as a base. You'd better make sure you make some of your important methods private so that no one can ever inherit from you.</p>
38,593
<h1>My situation</h1> <ul> <li>Input: a set of rectangles </li> <li>each rect is comprised of 4 doubles like this: (x0,y0,x1,y1)</li> <li>they are not "rotated" at any angle, all they are "normal" rectangles that go "up/down" and "left/right" with respect to the screen</li> <li>they are randomly placed - they may be touching at the edges, overlapping , or not have any contact</li> <li>I will have several hundred rectangles</li> <li>this is implemented in C#</li> </ul> <h1>I need to find</h1> <ul> <li>The area that is formed by their overlap - all the area in the canvas that more than one rectangle "covers" (for example with two rectangles, it would be the intersection)</li> <li>I don't need the geometry of the overlap - just the area (example: 4 sq inches)</li> <li>Overlaps shouldn't be counted multiple times - so for example imagine 3 rects that have the same size and position - they are right on top of each other - this area should be counted once (not three times)</li> </ul> <h1>Example</h1> <ul> <li>The image below contains thre rectangles: A,B,C</li> <li>A and B overlap (as indicated by dashes)</li> <li>B and C overlap (as indicated by dashes)</li> <li>What I am looking for is the area where the dashes are shown</li> </ul> <p>-</p> <pre><code>AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAAAAAAAAAAAAAAAA AAAAAAAAAAAAAAAA--------------BBB AAAAAAAAAAAAAAAA--------------BBB AAAAAAAAAAAAAAAA--------------BBB AAAAAAAAAAAAAAAA--------------BBB BBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBB BBBBBBBBBBBBBBBBB BBBBBB-----------CCCCCCCC BBBBBB-----------CCCCCCCC BBBBBB-----------CCCCCCCC CCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCC CCCCCCCCCCCCCCCCCCC </code></pre>
<p>An efficient way of computing this area is to use a sweep algorithm. Let us assume that we sweep a vertical line L(x) through the union of rectangles U: </p> <ul> <li>first of all, you need to build an event queue Q, which is, in this case, the ordered list of all x-coordinates (left and right) of the rectangles. </li> <li>during the sweep, you should maintain a 1D datastructure, which should give you the total length of the intersection of L(x) and U. The important thing is that this length is constant between two consecutive events q and q' of Q. So, if l(q) denotes the total length of L(q+) (i.e. L just on the rightside of q) intersected with U, the area swept by L between events q and q' is exactly l(q)*(q' - q).</li> <li>you just have to sum up all these swept areas to get the total one.</li> </ul> <p>We still have to solve the 1D problem. You want a 1D structure, which computes dynamically a union of (vertical) segments. By dynamically, I mean that you sometimes add a new segment, and sometimes remove one. </p> <p>I already detailed in my answer to this <a href="https://stackoverflow.com/questions/149577/need-an-algorithm-for-collapsing-netblock-ranges-into-lists-of-superset-ranges">collapsing ranges question</a> how to do it in a static way (which is in fact a 1D sweep). So if you want something simple, you can directly apply that (by recomputing the union for each event). If you want something more efficient, you just need to adapt it a bit:</p> <ul> <li>assuming that you know the union of segments S<sub>1</sub>...S<sub>n</sub> consists of disjoints segments D<sub>1</sub>...D<sub>k</sub>. Adding S<sub>n+1</sub> is very easy, you just have to locate both ends of S<sub>n+1</sub> amongs the ends of D<sub>1</sub>...D<sub>k</sub>.</li> <li>assuming that you know the union of segments S<sub>1</sub>...S<sub>n</sub> consists of disjoints segments D<sub>1</sub>...D<sub>k</sub>, removing segment S<sub>i</sub> (assuming that S<sub>i</sub> was included in D<sub>j</sub>) means recomputing the union of segments that D<sub>j</sub> consisted of, except S<sub>i</sub> (using the static algorithm).</li> </ul> <p>This is your dynamic algorithm. Assuming that you will use sorted sets with log-time location queries to represent D<sub>1</sub>...D<sub>k</sub>, this is probably the most efficient non-specialized method you can get.</p>
<p>You can find the overlap on the x and on the y axis and multiply those. </p> <pre><code>int LineOverlap(int line1a, line1b, line2a, line2b) { // assume line1a &lt;= line1b and line2a &lt;= line2b if (line1a &lt; line2a) { if (line1b &gt; line2b) return line2b-line2a; else if (line1b &gt; line2a) return line1b-line2a; else return 0; } else if (line2a &lt; line1b) return line2b-line1a; else return 0; } int RectangleOverlap(Rect rectA, rectB) { return LineOverlap(rectA.x1, rectA.x2, rectB.x1, rectB.x2) * LineOverlap(rectA.y1, rectA.y2, rectB.y1, rectB.y2); } </code></pre>
30,314
<p>Today I had a coworker suggest I refactor my code to use a label statement to control flow through 2 nested for loops I had created. I've never used them before because personally I think they decrease the readability of a program. I am willing to change my mind about using them if the argument is solid enough however. What are people's opinions on label statements?</p>
<p>Many algorithms are expressed more easily if you can jump across two loops (or a loop containing a switch statement). Don't feel bad about it. On the other hand, it may indicate an overly complex solution. So stand back and look at the problem.</p> <p>Some people prefer a "single entry, single exit" approach to all loops. That is to say avoiding break (and continue) and early return for loops altogether. This may result in some duplicate code.</p> <p>What I would strongly avoid doing is introducing auxilary variables. Hiding control-flow within state adds to confusion.</p> <p>Splitting labeled loops into two methods may well be difficult. Exceptions are probably too heavyweight. Try a single entry, single exit approach.</p>
<p>Personally whenever I need to use nested loops with the innermost one having to break out of all the parent loops, I just write everything in a method with a return statement when my condition is met, it's far more readable and logical.</p> <p>Example Using method:</p> <pre class="lang-java prettyprint-override"><code> private static boolean exists(int[][] array, int searchFor) { for (int[] nums : array) { for (int num : nums) { if (num == searchFor) { return true; } } } return false; } </code></pre> <p>Example Using label (less readable imo):</p> <pre class="lang-java prettyprint-override"><code>boolean exists = false; existenceLoop: for (int[] nums : array) { for (int num : nums) { if (num == searchFor) { exists = true; break existenceLoop; } } } return exists; </code></pre>
6,864
<p>What would be the disadvantages (if any) of automating business process for a Enterprise/organization?</p>
<ul> <li>Loosing discretionary error checking, i.e. numbers that look out of line;</li> <li>Potentially, knowledge of how a process is operated could be lost if it is automated but not documented. More often than not, manual processes are passed on;</li> <li>Accountability for the process becomes muddled.</li> </ul>
<p>Automating a business process just for the sake of automation is a fools errand. And is likely to cost your business A LOT (in every way you can imagine - financial impact, business disruption, new technical issues, morale, etc...).</p> <p>Without care, automating a business process can:</p> <ul> <li>cost lots of money (without necessarilly the possibility of making it back somehow)</li> <li>take a long time to implement (use of resources that would be better used elsewhere)</li> <li>make the proces more brittle (loss of flexibility / adaptibility)</li> <li>uncover issues with the current process that are minor and blow them out of proportion</li> <li>create errors if something in the process is overlooked</li> <li>demoralize your staff</li> </ul>
28,376
<p>I need to encrypt a small block of data (16 bytes) using 512 bit RSA public key -- quite an easy task for most cryptography libraries known to me, except for MS CSP API, as it seems. Documentation for <a href="http://msdn.microsoft.com/en-us/library/aa379924(VS.85).aspx" rel="nofollow noreferrer">CryptEncrypt</a> function states that</p> <blockquote> <p>The Microsoft Enhanced Cryptographic Provider supports direct encryption with RSA public keys and decryption with RSA private keys. The encryption uses PKCS #1 padding.</p> </blockquote> <p>It didn't work to me though. Well, my code works and produces encrypted block of data with correct size, but openssl fails to decypher it. It looks much like CryptEncrypt still uses symmetric cypher.</p> <p>Unfortunately all the examples I've found refer to combined cryptography with symmetric cypher, so I don't have a working example on hands which definitely would make things easier.</p> <p>Could please anyone point me to such an example or let me know if there are some not that obvious pitfalls I've missed?</p> <p>Thank you.</p>
<p>For who still needs this: I just created this article here that shows how to do it in WPF. <a href="http://www.codeproject.com/Articles/642151/Pixel-shaders-in-a-background-thread-in-WPF" rel="nofollow">http://www.codeproject.com/Articles/642151/Pixel-shaders-in-a-background-thread-in-WPF</a></p> <p>The relevant code copied below. it is from a class with some stored variables</p> <ul> <li>Source: an ImageSource</li> <li>DpiX, DpiY: doubles containing Dpi of source</li> <li>img: WPF Image control</li> <li>viewbox: WPF ViewBox control</li> <li>WPF_DPI_X, WPF_DPI_Y: const doubles with value 96.0</li> </ul> <p>1.the Image img is embedded in a Viewbox (also off-screen)</p> <pre><code>//prepare images img = new Image(); img.Stretch = Stretch.None; viewbox = new Viewbox(); viewbox.Stretch = Stretch.None; viewbox.Child = img; //control to render </code></pre> <p>2.img and viewbox are sized to the correct proportions, also some layout functions are called on viewbox. this make the controls render with the shader applied. </p> <pre><code>/// &lt;summary&gt; /// Loads the image and viewbox for off-screen rendering. /// &lt;/summary&gt; public void LoadImage(double width, double height) { img.BeginInit(); img.Width = width; img.Height = height; img.Source = Source; img.EndInit(); viewbox.Measure(new Size(img.Width, img.Height)); viewbox.Arrange(new Rect(0, 0, img.Width, img.Height)); viewbox.UpdateLayout(); } </code></pre> <p>3.And to get the contents of the image, a "screenshot" if you will: </p> <pre><code>void SaveUsingEncoder(BitmapEncoder encoder, Stream stream) { RenderTargetBitmap bitmap = new RenderTargetBitmap((int)(img.Width * DpiX / WPF_DPI_X), (int)(img.Height * DpiY / WPF_DPI_Y), DpiX, DpiY, PixelFormats.Pbgra32); bitmap.Render(viewbox); BitmapFrame frame = BitmapFrame.Create(bitmap); encoder.Frames.Add(frame); encoder.Save(stream); } </code></pre> <p>Also, if you want to run this in a separate thread you will need to create a thread with </p> <pre><code>thread.SetApartmentState(ApartmentState.STA); </code></pre> <p>for more info and a demo project, see the article.</p>
<p>What is generally done in C++ / DirectX to achive this is:</p> <p>Preparation (done once)</p> <ul> <li>Create render target using CreateRenderTarget</li> <li>Create off-screen surface using CreateOffscreenPlainSurface</li> <li>Set render target surface using SetRenderTarget</li> <li>Create any other input resources needed (Textures, Vertex Buffers ...)</li> </ul> <p>Rendering (done multiple times)</p> <ul> <li>Update input resources (textures, buffers) as needed</li> <li>Render</li> <li>Copy the contents of the render target into the off-screen surface via GetRenderTarget</li> <li>Lock the off-screen surface and read its content on the CPU</li> </ul>
37,742
<p>Based on several report parameters in SQL Server 2005 reporting services, I would like to automatically generate one or several chart(s) for each row in the return result and paginate or space them out. How do I go about that?</p>
<p>If the number of charts will vary for each row, but the variations are known (e.g. it's either just chart 1, or chart 1 and 3, or charts 1 2 and 3) then it's simple enough using a table.</p> <p>In the default detail row add any normal fields you need. Now insert a new detail row for each chart you might need. Lastly set the <a href="http://msdn.microsoft.com/en-us/library/aa337155%28SQL.90%29.aspx" rel="nofollow noreferrer">visibility</a> of each chart row based on your rules, noting that the rule will <strong>hide</strong> the row if your expression evaluates to true. Make sure you select the <strong>row</strong> using the area to the left of the left-most cell, if you got it right you'll see that it's a row in the properties grid.</p> <p>To get the layout you want you can merge cells for the charts to go in, or use a single cell and put a Rectangle in it, then in the Rectangle lay out your other controls.</p> <p>Any rows that are hidden will be collapsed, so you wont get big empty sections like you can if you simply toggle the visibility of the charts themselves.</p>
<p>What you can do is place a <a href="http://msdn.microsoft.com/en-us/library/ms159121(SQL.90).aspx" rel="nofollow noreferrer">List control</a> on the page, set <a href="http://msdn.microsoft.com/en-us/library/ms159660(SQL.90).aspx" rel="nofollow noreferrer">List grouping</a> by record unique key (ID, or several fields if composite), and place a charts on the List. Next, set items visibility expressions to <a href="http://msdn.microsoft.com/en-us/library/aa337155(SQL.90).aspx" rel="nofollow noreferrer">control it with report parameters</a>.</p>
18,801
<p>As much as I generally don't like the discussion/subjective posts on SO, I have really come to appreciate the "Hidden Secrets" set of posts that people have put together. They provide a great overview of some commonly missed tools that you might now otherwise discover.</p> <p>For this question I would like to explore the Visual Studio .NET debugger. What are some of the "hidden secrets" in the VS.NET debugger that you use often or recently discovered and wish you would have known long ago?</p>
<p>One of my favorite features is the <a href="http://msdn.microsoft.com/en-us/library/232dxah7(VS.80).aspx" rel="noreferrer">"When Hit..."</a> option available on a breakpoint. You can print a message with the value of a variable along with lots of other information, such as:</p> <ul> <li><code>$ADDRESS</code> - Current Instruction</li> <li><code>$CALLER</code> - Previous Function Name</li> <li><code>$CALLSTACK</code> - Call Stack</li> <li><code>$FUNCTION</code> - Current Function Name</li> <li><code>$PID</code> - Process ID</li> <li><code>$PNAME</code> - Process Name</li> <li><code>$TID</code> - Thread ID</li> <li><code>$TNAME</code> - Thread Name</li> </ul> <p>You can also have it run a macro, but I've never used that feature.</p>
<p>You can open and place a breakpoint in a source file if the file belongs to another solution (external file). The debugger can still hit the breakpoint. No need to open another Visual Studio instance to debug the external file. Helpful in debugging web services which you source to. This works as long as all the sources are current and compiled. </p>
15,937
<p>We have a web application, which involves a lot of documents. In a typical use case, a document will be generated from our web application. The user download the generated document to the local file system and modify it. After this work, the user upload the modified document back to the web application. </p> <p>I need an easier way, to work with the web application and documents. It should be seamlessly. Maybe, there is a way, to edit the document in a webdav folder similar a sharepoint document list and store it right back in the web application, without storing a temporary document on the local file system.</p> <p>But maybe, there are better ideas.</p> <p>P.S: I don't want to use active x controls and it must be a webapplication :-)</p> <p>Thank you for your help. </p>
<p>I don't think this is possible without a plugin. I've used activex in the past, maybe it would be possible to write a cross-platform java applet?</p>
<p>You can use google docs that give the facility of editing the documents. This is free and you can use it in your web application also. you just have to reference the dlls.</p> <p>Please see the following link for more details.<br /> <a href="http://code.google.com/apis/documents/docs/2.0/developers_guide_dotnet.html" rel="nofollow">http://code.google.com/apis/documents/docs/2.0/developers_guide_dotnet.html</a></p> <p>You can download the google data api from here.<br /> <a href="http://code.google.com/p/google-gdata/downloads/list" rel="nofollow">http://code.google.com/p/google-gdata/downloads/list</a></p> <p>Thanks.</p>
39,810
<p>I have a report that is used by a windows service and a form application. So, I want to put embed the report in a DLL file that can be used by both.</p> <p>The problem is that if I try to set the ReportEmbeddedResource property of a ReportViewer control in my windows form app, it will search the windows form app for the resource, not the dll file.</p> <p>e.g.: Code from the windows form app:</p> <pre><code>rv.LocalReport.ReportEmbeddedResource = "MyReportInMyDLLFile.rdlc" </code></pre> <p>How can I make the above command look for the embedded resource in my DLL file?</p>
<p>Something like this should do it:</p> <pre><code>Assembly assembly = Assembly.LoadFrom("Reports.dll"); Stream stream = assembly.GetManifestResourceStream("Reports.MyReport.rdlc"); reportViewer.LocalReport.LoadReportDefinition(stream); </code></pre>
<p>Probably the best thing to do would be to get a stream to the RDLC resource from the other assembly, then pass that to the "LoadReportDefinition" method of the Report Viewer control.</p> <p>Details of how to get a stream from an embedded resource in a different assembly can be found here : <a href="http://msdn.microsoft.com/en-us/library/aa984408(VS.71).aspx" rel="noreferrer">Retrieving Resources with the ResourceManager Class</a></p> <p>Additionally, you will need to refer to the embedded resource using it's full namespace path.</p> <p>E.g. if you have an application with a default namespace of <strong>TheApp</strong>, and you keep a report called "<strong>MyReport.rdlc</strong>" in a folder called "<strong>Reports</strong>", the report reference call would be:-</p> <pre><code>rv.LocalReport.ReportEmbeddedResource = "TheApp.Reports.MyReport.rdlc"; </code></pre>
31,632
<p>Under Linux, my C++ application is using fork() and execv() to launch multiple instances of OpenOffice so as to view some powerpoint slide shows. This part works.</p> <p>Next I want to be able to move the OpenOffice windows to specific locations on the display. I can do that with the XMoveResizeWindow() function but I need to find the Window for each instance.</p> <p>I have the process ID of each instance, how can I find the X11 Window from that ?</p> <hr> <p><strong>UPDATE</strong> - Thanks to Andy's suggestion, I have pulled this off. I'm posting the code here to share it with the Stack Overflow community.</p> <p>Unfortunately Open Office does not seem to set the _NET_WM_PID property so this doesn't ultimately solve my problem but it does answer the question.</p> <pre><code>// Attempt to identify a window by name or attribute. // by Adam Pierce &lt;adam@doctort.org&gt; #include &lt;X11/Xlib.h&gt; #include &lt;X11/Xatom.h&gt; #include &lt;iostream&gt; #include &lt;list&gt; using namespace std; class WindowsMatchingPid { public: WindowsMatchingPid(Display *display, Window wRoot, unsigned long pid) : _display(display) , _pid(pid) { // Get the PID property atom. _atomPID = XInternAtom(display, "_NET_WM_PID", True); if(_atomPID == None) { cout &lt;&lt; "No such atom" &lt;&lt; endl; return; } search(wRoot); } const list&lt;Window&gt; &amp;result() const { return _result; } private: unsigned long _pid; Atom _atomPID; Display *_display; list&lt;Window&gt; _result; void search(Window w) { // Get the PID for the current Window. Atom type; int format; unsigned long nItems; unsigned long bytesAfter; unsigned char *propPID = 0; if(Success == XGetWindowProperty(_display, w, _atomPID, 0, 1, False, XA_CARDINAL, &amp;type, &amp;format, &amp;nItems, &amp;bytesAfter, &amp;propPID)) { if(propPID != 0) { // If the PID matches, add this window to the result set. if(_pid == *((unsigned long *)propPID)) _result.push_back(w); XFree(propPID); } } // Recurse into child windows. Window wRoot; Window wParent; Window *wChild; unsigned nChildren; if(0 != XQueryTree(_display, w, &amp;wRoot, &amp;wParent, &amp;wChild, &amp;nChildren)) { for(unsigned i = 0; i &lt; nChildren; i++) search(wChild[i]); } } }; int main(int argc, char **argv) { if(argc &lt; 2) return 1; int pid = atoi(argv[1]); cout &lt;&lt; "Searching for windows associated with PID " &lt;&lt; pid &lt;&lt; endl; // Start with the root window. Display *display = XOpenDisplay(0); WindowsMatchingPid match(display, XDefaultRootWindow(display), pid); // Print the result. const list&lt;Window&gt; &amp;result = match.result(); for(list&lt;Window&gt;::const_iterator it = result.begin(); it != result.end(); it++) cout &lt;&lt; "Window #" &lt;&lt; (unsigned long)(*it) &lt;&lt; endl; return 0; } </code></pre>
<p>The only way I know to do this is to traverse the tree of windows until you find what you're looking for. Traversing isn't hard (just see what xwininfo -root -tree does by looking at xwininfo.c if you need an example). <p> But how do you identify the window you are looking for? <b>Some</b> applications set a window property called _NET_WM_PID. <p> I believe that OpenOffice <em>is</em> one of the applications that sets that property (as do most Gnome apps), so you're in luck.</p>
<p>If you use python, I found a way <a href="https://bbs.archlinux.org/viewtopic.php?id=113346" rel="nofollow noreferrer">here</a>, the idea is from <a href="https://github.com/BurntSushi/" rel="nofollow noreferrer">BurntSushi</a></p> <p>If you launched the application, then you should know its cmd string, with which you can reduce calls to <code>xprop</code>, you can always loop through all the xids and check if the pid is the same as the pid you want</p> <pre><code>import subprocess import re import struct import xcffib as xcb import xcffib.xproto def get_property_value(property_reply): assert isinstance(property_reply, xcb.xproto.GetPropertyReply) if property_reply.format == 8: if 0 in property_reply.value: ret = [] s = '' for o in property_reply.value: if o == 0: ret.append(s) s = '' else: s += chr(o) else: ret = str(property_reply.value.buf()) return ret elif property_reply.format in (16, 32): return list(struct.unpack('I' * property_reply.value_len, property_reply.value.buf())) return None def getProperty(connection, ident, propertyName): propertyType = eval(' xcb.xproto.Atom.%s' % propertyName) try: return connection.core.GetProperty(False, ident, propertyType, xcb.xproto.GetPropertyType.Any, 0, 2 ** 32 - 1) except: return None c = xcb.connect() root = c.get_setup().roots[0].root _NET_CLIENT_LIST = c.core.InternAtom(True, len('_NET_CLIENT_LIST'), '_NET_CLIENT_LIST').reply().atom raw_clientlist = c.core.GetProperty(False, root, _NET_CLIENT_LIST, xcb.xproto.GetPropertyType.Any, 0, 2 ** 32 - 1).reply() clientlist = get_property_value(raw_clientlist) cookies = {} for ident in clientlist: wm_command = getProperty(c, ident, 'WM_COMMAND') cookies[ident] = (wm_command) xids=[] for ident in cookies: cmd = get_property_value(cookies[ident].reply()) if cmd and spref in cmd: xids.append(ident) for xid in xids: pid = subprocess.check_output('xprop -id %s _NET_WM_PID' % xid, shell=True) pid = re.search('(?&lt;=\s=\s)\d+', pid).group() if int(pid) == self.pid: print 'found pid:', pid break print 'your xid:', xid </code></pre>
18,249
<p>Can you please let me know the SQL to split date ranges when they overlap?</p> <p>Data (sample data with a date range and possibly other columns):</p> <pre><code> Col1 FromDate ToDate 1. 1 1/1/2008 31/12/2010 2. 1 1/1/2009 31/12/2012 3. 1 1/1/2009 31/12/2014 </code></pre> <p>Output:</p> <pre><code> Col1 From Date ToDate 1. 1 1/1/2008 31/12/2008 (from row 1 above) 2. 1 1/1/2009 31/12/2010 (from rows 1,2 and 3 above) 3. 1 1/1/2011 31/12/2012 (from rows 2 and 3 above) 4. 1 1/1/2013 31/12/2014 (from row 3 above) </code></pre>
<p>This should do the trick (MySQL dialect, but easily adaptable)</p> <p>Initial setup</p> <pre><code>SQL query: SELECT * FROM `test` LIMIT 0, 30 ; Rows: 3 start end 2008-01-01 2010-12-31 2009-01-01 2012-12-31 2009-01-01 2014-12-31 </code></pre> <p>Query</p> <pre><code>SELECT `start` , min( `end` ) FROM ( SELECT t1.start, t2.end FROM test t1, test t2 WHERE t1.start &lt; t2.end UNION SELECT t1.end + INTERVAL 1 DAY , t2.end FROM test t1, test t2 WHERE t1.end + INTERVAL 1 DAY &lt; t2.end UNION SELECT t1.start, t2.start - INTERVAL 1 DAY FROM test t1, test t2 WHERE t1.start &lt; t2.start - INTERVAL 1 DAY ) allRanges GROUP BY `start` </code></pre> <p>Result</p> <pre><code>start min( `end` ) 2008-01-01 2008-12-31 2009-01-01 2010-12-31 2011-01-01 2012-12-31 2013-01-01 2014-12-31 </code></pre>
<p>Skliwz's answer adapted for SQL Server:</p> <pre><code>DECLARE @DateTest TABLE ( FromDate datetime, ToDate datetime ) insert into @DateTest (FromDate, ToDate) ( select cast('1/1/2008' as datetime), cast('12/31/2010' as datetime) union select cast('1/1/2009' as datetime), cast('12/31/2012' as datetime) union select cast('1/1/2009' as datetime), cast('12/31/2014' as datetime) ) SELECT FromDate , min(ToDate) FROM ( SELECT t1.FromDate, t2.ToDate FROM @DateTest t1, @DateTest t2 WHERE t1.FromDate &lt; t2.ToDate UNION SELECT dateadd(DAY, 1, t1.ToDate), t2.ToDate FROM @DateTest t1, @DateTest t2 WHERE dateadd(DAY, 1, t1.ToDate) &lt; t2.ToDate ) allRanges group by FromDate </code></pre>
22,386
<p>I've got a Subversion repository, backed by the berkeley DB. Occasionally it breaks down due to some locks and such not being released, but this morning it was impossible to recover it using the 'svnadmin recover' command. Instead it failed with the following error:</p> <pre><code>svnadmin: Berkeley DB error for filesystem 'db' while opening 'nodes' table: Invalid argument svnadmin: bdb: file nodes (meta pgno = 0) has LSN [1083][429767]. svnadmin: bdb: end of log is [1083][354707] svnadmin: bdb: db/nodes: unexpected file type or format </code></pre> <p>I'm going to restore the repository from the last known good backup, but it would be good to know if there is a way this repository could be fixed.</p> <p>edit: even the db_recover utility does not make a difference. It shows recovery is completed, but the same error persists when verifying the repository using svnadmin.</p>
<blockquote> <p>I've got a Subversion repository, backed by the berkeley DB.</p> </blockquote> <p>Sorry to hear that. I would suggest that at your earliest convenience, you dump that repository (<code>svnadmin dump</code>) and reload it into a new one backed by FSFS (<code>svnadmin load</code>).</p>
<p>have you tried <a href="http://www.google.com/search?q=man+db_recover" rel="nofollow noreferrer">db_recover</a>? the latter tends to be able to correct more issues than svnadmin</p>
14,568
<p>I have some code which returns InnerXML for a XMLNode.</p> <p>The node can contain just some text (with HTML) or XML.</p> <p>For example:</p> <pre><code>&lt;XMLNode&gt; Here is some &amp;lt;strong&amp;gt;HTML&amp;lt;/strong&amp;gt; &lt;XMLNode&gt; </code></pre> <p>or</p> <pre><code>&lt;XMLNode&gt; &lt;XMLContent&gt;Here is some content&lt;/XMLContnet&gt; &lt;/XMLNode&gt; </code></pre> <p>if I get the InnerXML for <code>&lt;XmlNode&gt;</code> the HTML tags are returned as XML entities.</p> <p>I cannot use InnerText because I need to be able to get the XML contents. So all I really need is a way to un-escape the HTML tags, because I can detect if it's XML or not and act accordingly.</p> <p>I guess I could use HTMLDecode, but will this decode all the XML encoded entities?</p> <p><strong>Update:</strong> I guess I'm rambling a bit above so here is a clarified scenario:</p> <p>I have a XML document that looks like this:</p> <pre><code>&lt;content id="1"&gt; &lt;data&gt;&amp;lt;p&amp;gt;A Test&amp;lt;/p&amp;gt;&lt;/data&gt; &lt;/content id="2"&gt; &lt;content&gt; &lt;data&gt; &lt;dataitem&gt;A test&lt;/dataitem&gt; &lt;/data&gt; &lt;/content&gt; </code></pre> <p>If I do:</p> <pre><code>XmlNode xn1 = document.SelectSingleNode("/content[@id=1]/data"); XmlNode xn2 = document.SelectSingleNode("/content[@id=2]/data"); Console.WriteLine(xn1.InnerXml); Console.WriteLine(xn2.InnerXml); </code></pre> <p>xn1 will return </p> <pre><code> &amp;lt;p&amp;gt;A Test&amp;lt;/p&amp;gt; </code></pre> <p>xn2 will return <code>&lt;dataitem&gt;A test&lt;/dataitem&gt;</code></p> <p>I am already checking to see if what is returned is XML (in the case of xn2) so all I need to do is un-escape the <code>&amp;lt;</code> etc in xn1.</p> <p>HTMLDecode does this, but I'm not sure it would work for everything. So the question remains would HTMLDecode handle all the possible entities or is there a class somewhere that will do it for me.</p>
<p>why not inserting them as &amp;lt; and &amp;gt; ? you avoid mixing xml and custom markup stuff with this...</p>
<p>why not inserting them as &amp;lt; and &amp;gt; ? you avoid mixing xml and custom markup stuff with this...</p>
24,628
<p>I have a C# web application that needs to deploy a file to the client computer's hard drive. (A javascript file for Adobe Acrobat)</p> <p>If the client is using a mac, I have an applescript that will search their applications directory for acrobat and then deploy the JS file in the correct location.</p> <p>The problem is that I am currently creating the applescript on a mac, and then moving it to the server. The applescript has at least one message (to say it has finished successfully), and this message needs to be displayed in the user's language of choice (specified in the web app)</p> <p>So, is there some way to create the applescript on my windows C# server (with the embedded language string) and then send it to the client?</p>
<p>I can't think of a good way to dynamically generate an AppleScript (especially on a non-Mac OS platform), but couldn't you have the C# (ASP.NET?) server write to a file, and have the AppleScript read the message from that?</p>
<p>I can't think of a good way to dynamically generate an AppleScript (especially on a non-Mac OS platform), but couldn't you have the C# (ASP.NET?) server write to a file, and have the AppleScript read the message from that?</p>
34,620
<p>I'm starting work on a program which is perhaps most naturally described as a batch of calculations on database tables, and will be executed once a month. All input is in Oracle database tables, and all output will be to Oracle database tables. The program should stay maintainable for many years to come.</p> <p>It seems straight-forward to implement this as a series of stored procedures, each performing a sensible transformation, for example distributing costs among departments according to some business rules. I can then write unit tests to check if the output of each transformation is as I expected.</p> <p>Is it a bad idea to do this all in PL/SQL? Would you rather do heavy batch calculations in a typical object oriented programming language, such as C#? Isn't it more expressive to use a database centric programming language such as PL/SQL?</p>
<p>Normally I say put as little in PL/SQL as possible - it is typically a lot less maintainable - at one of my last jobs I really saw how messy and hard to work with it could get. </p> <p>However, since it is batch processing - and since the input and output are both the DB - it makes good sense to put the logic into PL/SQL - to minimize "moving parts". However, if it were business logic - or components used by other pieces of your system - I would say don't do it.. </p>
<p>It's not usually more expressive because most stored procedure languages suck by design. But it will probably run faster than in an external app.</p> <p>I guess it boils down to how familiar you are with PL/SQL, how much time you have to write this, how important is performance and if you can reasonably expect maintainers to be familiar enough with PL/SQL to maintain a big program written in it.</p> <p>If speed is not relevant and maintainers will probably be not PL/SQL proficient, you might be better using a 'traditional' language.</p> <p>You could also use a hybrid approach, where you use PL/SQL to generate intermediate data (say, table joins and sums or whatever) and a separate application to control flow and check values and errors.</p>
10,407
<p>I know I can configure command line arguments in the Run configuration but I want to run a java file multiple times with different command line arguments. It's a pain to change the Run Configuration every time.</p> <p>Is there a way I can make Eclipse prompt me for command line arguments every time I run the program?</p>
<p>Add <code>string_prompt</code> as a <code>Program Argument</code> in the <code>Run</code> configuration.</p> <pre><code> ${string_prompt} </code></pre> <p>There are also a <code>file_prompt</code> and a <code>folder_prompt</code> if you want specifically files\folders.</p> <p>These are available through the <code>Variables</code> button on the <code>(x)= Arguments</code> tab of the Run Configuration dialog.</p>
<p>In addition you can add a string to the prompt by using ${string_prompt:My Prompt Text} which will show the dialog box with 'Please input a value for My Prompt Text'.</p>
40,385
<p>Is there a more concise/standard idiom (e.g., a JDK method) for "piping" an input to an output in Java than the following?</p> <pre><code>public void pipe(Reader in, Writer out) { CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE); while (in.read(buf) &gt;= 0 ) { out.append(buf.flip()); buf.clear(); } } </code></pre> <p>[EDIT] Please note the <code>Reader</code> and <code>Writer</code> are <em>given</em>. The correct answer will demonstrate how to take <code>in</code> and <code>out</code> and form a pipe (preferably with no more than 1 or 2 method calls). I will accept answers where <code>in</code> and <code>out</code> are an <code>InputStream</code> and an <code>OutputStream</code> (preferably with a conversion from/to <code>Reader</code>/<code>Writer</code>). I will not accept answers where either <code>in</code> or <code>out</code> is a <em>subclass</em> of <code>Reader</code>/<code>InputStream</code> or <code>Writer</code>/<code>OutputStrem</code>.</p>
<p><a href="http://commons.apache.org/io/" rel="noreferrer">IOUtils</a> from the Apache Commons project has a number of <a href="http://commons.apache.org/io/api-1.4/org/apache/commons/io/IOUtils.html" rel="noreferrer">utilily methods</a> that do exactly what you need.</p> <p><code>IOUtils.copy(in, out)</code> will perform a buffered copy of all input to the output. If there is more than one spot in your codebase that requires <code>Stream</code> or <code>Reader</code>/<code>Writer</code> handling, using IOUtils could be a good idea.</p>
<p>Take a look at <a href="http://java.sun.com/javase/6/docs/api/java/io/PipedInputStream.html" rel="nofollow noreferrer">java.io.PipedInputStream</a> and <a href="http://java.sun.com/javase/6/docs/api/java/io/PipedOutputStream.html" rel="nofollow noreferrer">PipedOutputStream</a>, or <a href="http://java.sun.com/javase/6/docs/api/java/io/PipedReader.html" rel="nofollow noreferrer">PipedReader</a>/<a href="http://java.sun.com/javase/6/docs/api/java/io/PipedWriter.html" rel="nofollow noreferrer">PipedWriter</a> from the same package.</p> <p>From the Documentation of PipedInputStream:</p> <p><em>A piped input stream should be connected to a piped output stream; the piped input stream then provides whatever data bytes are written to the piped output stream. Typically, data is read from a PipedInputStream object by one thread and data is written to the corresponding PipedOutputStream by some other thread. Attempting to use both objects from a single thread is not recommended, as it may deadlock the thread. The piped input stream contains a buffer, decoupling read operations from write operations, within limits. A pipe is said to be broken if a thread that was providing data bytes to the connected piped output stream is no longer alive.</em> </p>
15,550
<p>I have a 15x15 cm heating resistor from my current printer (printing area: 12x12 cm).</p> <p>I would like to switch to a glass bed and to rework my printer to increase the printing area to 20 cm (22x22 cm glass plate).</p> <p>Would it be possible to use the old heating resistor placed only in the centre? this way I would have a smaller heated bed for ABS and a bigger one for PLA.</p> <p>Would the glass crack due to non uniform heating? This is because glass has a conductivity of less than 5 W/mK, therefore the hot area will stay hot and basically never really spread the heat to the surrounding area. So the frame will be cold and the center hot, causing stresses.</p> <p>Related: <a href="https://engineering.stackexchange.com/questions/31842/how-much-an-unevenly-heated-glass-plate-bows">https://engineering.stackexchange.com/questions/31842/how-much-an-unevenly-heated-glass-plate-bows</a></p>
<p>If you're using borosilicate glass (aka pyrex) then it won't crack. You can get squares of ~20x20 cheaply off aliexpress.</p> <p>If you're using window glass, picture frame class etc then you might have issues with cracking, it will depend on lots of factors like the wattage of your heater and the temperature of the room.</p> <p>Your biggest problem will be that the bed heats very non-uniformly, which is unlike to give good print adhesion. I'd suggest a sheet of aluminium underneath the glass if possible, it will allow much more even heating. </p>
<p>The glass will be taking up the heat to slowly cover its full area. That means two things:</p> <ol> <li>it will not crack as there is no thermal shock</li> <li>it will put more pressure on the heater as there will be bigger heat absorption, so in an edge case, you could end-up with not getting a required temperature on the glass surface and/or the heating process will be very slow.</li> </ol> <p>In that case, I personally will try that out and then if I have an issue with getting proper temperature, then I will buy a new heater.</p> <hr> <p>A comment regarding heat expansion:</p> <p>my glass is about 20mm longer than the bed and it is warm during the printing process. The 'breaking' stress is connected with temperature shock (an immediate temp change), not a relatively slow heating process. However, borosilicate glass also known as Pyrex (TM) expands very little. Much less than most metals. This is why it doesn't break when exposed to sudden hot and cold changes. So in short words - check tea lighter under your tea-pot and see how te heat is comming out from the centre</p> <p><a href="http://glassproperties.com/expansion/ExpansionMeasurement.htm" rel="nofollow noreferrer">source</a></p>
881
<p>I have a web service application which has suddenly stopped working. I have enabled directory browsing in IIS, and can view the application directory. I can view the xml files within the application directory, but I cannot view the .config files, nor can I view the wsdls of any of the web services. When I try to browse to <code>http://server/app/service.asmx?wsdl</code>, the browser stays in the "loading" state forever.</p> <p>Any ideas what might have gone wrong here?</p>
<p>Have you looked in the server's event log? Many ASP.NET errors will end up there, this sounds like it might qualify</p>
<p>Regarding the first question about loading, are you able to browse to the site on the server?</p> <p>IIS protects Web.config files by default and will typically return a "This type of page is not served" error message. This is a good thing which will keep your connection strings and what not from being casually viewed. There is more information about allowing exceptions for this <a href="https://stackoverflow.com/questions/431233/cassini-error-this-type-of-page-is-not-served">here</a>.</p>
45,703
<p>I'm trying to run a batch file, as another user, from my web app. For some reason, the batch file hangs! I can see "cmd.exe" running in the task manager, but it just sits there forever, unable to be killed, and the batch file is not running. Here's my code:</p> <pre><code>SecureString password = new SecureString(); foreach (char c in "mypassword".ToCharArray()) password.AppendChar(c); ProcessStartInfo psi = new ProcessStartInfo(); psi.WorkingDirectory = @"c:\build"; psi.FileName = Environment.SystemDirectory + @"\cmd.exe"; psi.Arguments = "/q /c build.cmd"; psi.UseShellExecute = false; psi.UserName = "builder"; psi.Password = password; Process.Start(psi); </code></pre> <p>If you didn't guess, this batch file builds my application (a different application than the one that is executing this command).</p> <p>The Process.Start(psi); line returns immediately, as it should, but the batch file just seems to hang, without executing. Any ideas?</p> <p><strong>EDIT:</strong> See my answer below for the contents of the batch file.</p> <ul> <li>The output.txt never gets created.</li> </ul> <p>I added these lines: </p> <pre><code>psi.RedirectStandardOutput = true; Process p = Process.Start(psi); String outp = p.StandardOutput.ReadLine(); </code></pre> <p>and stepped through them in debug mode. The code hangs on the <code>ReadLine()</code>. I'm stumped!</p>
<p>I believe I've found the answer. It seems that Microsoft, in all their infinite wisdom, has blocked batch files from being executed by IIS in Windows Server 2003. Brenden Tompkins has a work-around here:</p> <p><a href="http://codebetter.com/blogs/brendan.tompkins/archive/2004/05/13/13484.aspx" rel="noreferrer">http://codebetter.com/blogs/brendan.tompkins/archive/2004/05/13/13484.aspx</a></p> <p>That won't work for me, because my batch file uses IF and GOTO, but it would definitely work for simple batch files.</p>
<p>My guess would be that the build.cmd is waiting for some sort of user-interaction/reply. If you log the output of the command with the "<strong>> logfile.txt</strong>" operator at the end, it might help you find the problem.</p>
5,437
<p>Does anyone know if there's a way to automatically expand a list in Python, separated by commas? I'm writing some Python code that uses the MySQLdb library, and I'm trying to dynamically update a list of rows in a MySQL database with certain key values.</p> <p>For instance, in the code below, I'd like to have the numeric values in the record_ids list expand into a SQL "<code>IN</code>" clause.</p> <pre><code>import MySQLdb record_ids = [ 23, 43, 71, 102, 121, 241 ] mysql = MySQLdb.connect(user="username", passwd="secret", db="apps") mysql_cursor = mysql.cursor() sqlStmt="UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in ( %s )" mysql_cursor.execute( sqlStmt, record_ids ) mysql.commit() </code></pre> <p>Any help would be appreciated!</p>
<p>try:</p> <pre><code>",".join( map(str, record_ids) ) </code></pre> <p><code>",".join( list_of_strings )</code> joins a list of string by separating them with commas</p> <p>if you have a list of numbers, <code>map( str, list )</code> will convert it to a list of strings</p>
<p>Alternitavely, using <em>replace</em>:</p> <pre><code>sqlStmt="UPDATE apps.sometable SET lastmod=SYSDATE() where rec_id in " + record_ids.__str__().replace('[','(').replace(']',')') </code></pre>
40,750
<p>Doing a refresh after certain action in asp.net seems to make them happen again even when that action doesn't make sense (think double delete). The web way to deal with this situation is to redirect after a post to get a clean version of the page that can be refreshed without reposting an action to the webserver. How can I do this with ASP.NET</p>
<p>I have a feeling there is a deeper problem I'm not getting but here goes. In your postback event:</p> <pre><code>// the post handling logic, e.g. the click event code Response.Redirect(Request.RawUrl); </code></pre>
<p>Use Server.Transfer method.</p> <p>The Server.Transfer method has a second parameter—"preserveForm". If you set this to True, using a statement such as Server.Transfer("WebForm2.aspx", True), the existing query string and any form variables will still be available to the page you are transferring to.</p> <p><a href="http://www.developer.com/net/asp/article.php/3299641" rel="nofollow noreferrer">http://www.developer.com/net/asp/article.php/3299641</a></p>
42,913
<p>The bottom of my prints warp/curve upwards, most often at the corners. This is a very slight curve, only about 1-2 mm.</p> <ul> <li>I print with a raft all the time.</li> <li>I don't have a heated bed.</li> <li>I print with PLA at 199 °C (390 °F) with a print speed of approximately 40 mm/s</li> <li>I have a Sindoh 3DWOX DP201.</li> </ul> <p>What slicer settings might be the cause of this phenomena? Or could it be 3D printer settings?</p>
<p><strong>The first thing to understand is what causes warping</strong>. Warping is caused by the thermal contraction of the plastic when it cools down.</p> <p>Simplifying things a fair bit, you can visualise the process like this:</p> <ol> <li>hot, expanded plastic gets deposited on cooler, shrunk layers,</li> <li>when the hot plastic cools down, it shrinks and pulls the upper part of the layer below inwards</li> <li>at this point, the layer below has a differential in the compression between its upper and lower parts, and curls up</li> <li>the problem is exacerbated at the very first layer (the one touching the bed) as this is "locked" to a rigid body (the bed) and cannot shrink, while subsequent layers are only attached to the somewhat flexible plastic beneath, and thus can contract.</li> </ol> <p><a href="https://i.stack.imgur.com/knXcU.png" rel="noreferrer"><img src="https://i.stack.imgur.com/knXcU.png" alt="diagram of curling plastic"></a></p> <p>Also notice that the larger the part being printed, the stronger is the force trying to curl-up your print.</p> <p>Once one understands all of this, then it is possible to appreciate the many ways the problem can be mitigated.</p> <p>Here are the common ones:</p> <p><strong>USING A MATERIAL WITH LOW SHRINKAGE COEFFICIENT</strong></p> <p>This translates in smaller tensions and thus less force "pulling up" the corners of your print. Historically, 3D printing started with ABS because this material was one of the very few, relatively safe ones to source. Nowadays there are materials like PETG which have similar mechanical properties to ABS but are much easier and forgiving to print with, so - unless you need ABS for some very specific reason (e.g.: acetone smoothing) consider never printing with it.</p> <p><strong>DECREASING THE THERMAL DIFFERENCE BETWEEN MOLTEN AND SOLID STATE</strong></p> <p>Concretely, this means lowering the "gap" between the ~200°C of the nozzle and the ~20°C of room temperature by using a heated bed and - possibly - an enclosure.</p> <p>The heated bed not only drastically diminish the shrinkage of the first layer, but because heat radiates, and hot air goes upwards, the entire bottom of the print has shrinkage mitigated.</p> <p>An enclosure just increase the benefit of the heating bed, by reflecting IR radiation back towards the print and preventing hot air to escape. A heated enclosure just improve things even further.</p> <p>Some slicers offer a "shroud" option, that encloses the entire print in an enclosed, sacrificial structure, that tries to emulate the benefits of a proper printer enclosure.</p> <p><strong>INCREASING ADHESION WITH THE PRINTING BED</strong></p> <p>That is the "brutal force" approach: if you face a strong "curl up" force, oppose it with a strong "anchor down" one.</p> <p>The increase in adhesion can be achieved in a number of ways:</p> <ul> <li>Lower print speed (more time for the molten plastic to "bond")</li> <li>Overextrusion (more pressure, more material)</li> <li>Disabling cooling fan (more progressive cooling, more time to "bond")</li> <li>Using a brim (more contact surface between print and bed)</li> <li>Using "ad hoc" material on the bed (PVA glue for PLA, ABS sludge for ABS, kapton tape, hair spray, blue tape, etc...)</li> </ul> <p><strong>REDUCING THE CURL-UP FORCE</strong></p> <p>This is typically achieved during design. Designing is a vast field and it would be impossible to cover all the possible mitigating strategies one could use, but here are some of the most common ones:</p> <ul> <li><p>Prefer assembling smaller parts over printing huge ones. This is self explanatory really, as the curling force increases with the amount of material "pulling", the least material one has, the less force one gets.</p></li> <li><p>Make relief holes above the first layers in long structures. This will essentially "break" the build-up of tension in the layer, creating many points with a little "curling up force" rather than two with a huge one. Something along the lines of this, for example:</p></li> </ul> <p><a href="https://i.stack.imgur.com/nKSuL.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/nKSuL.jpg" alt="I beam with relief holes"></a></p> <ul> <li>Avoid extensive overhangs close to the bottom of the print (this is because otherwise you will have considerably more material "pulling up" than you will have "anchoring down". Here is an example of what <em>not</em> to do (to be fair: this was specifically taken from a <a href="https://www.thingiverse.com/thing:1504207" rel="noreferrer">bed adhesion/warping test</a>).</li> </ul> <p><a href="https://i.stack.imgur.com/t7IDh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/t7IDh.png" alt="warping test"></a></p> <p>Of course all of the above strategies can/should be combined, when possible. Even if not warped, a part with a lot of internal tension will perform less predictably and possibly worse than a part where such tensions are lower.</p>
<p>If you have a heat bed, heat it up accordingly (for example for PLA 50 °C first layers, 40 °C then can be a good starting point).</p> <p>If the first layer isn't close enough, then warping can happen (Happened to me when moving from 0.3 mm layers to 0.1 mm).</p> <p>If you are under extruding / have dirt in the system (the heat chamber) so that extrusion is uneven it can make warps.</p> <p>And as always, you can try to print slower, it helps not always but often.</p> <p>Please also do tell what temperatures (heat bed &amp; nozzle) you are using and what material.</p>
781
<p>Could you recommend a lightweight SQL database which doesn't require installation on a client computer to work and could be accessed easily from .NET application? Only basic SQL capabilities are needed.</p> <p>Now I am using Access database in simple projects and distribute .MDB and .EXE files together. Looking for any alternatives.</p>
<p>Depends on what you mean by lightweight. Easy on Ram? Or lighter db file? Or lighter connector to connect to db? Or fewer files over all? I'll give a comparison of what I know:</p> <pre><code> no of files cumulative size of files db size Firebird 2.5 5 6.82 MB 250 KB SqlServerCe 4 7 2.08 MB 64 KB Sqlite 3.7.11.0 1 0.83 MB 15 KB VistaDb 4.3.3.34 1 1.04 MB 48 KB no of files - includes the .net connector and excludes the db file </code></pre> <p>The dbs are of 1 table with 2 columns and 2 rows. Take the db size with a pinch of salt as dbs could grow differently with further use. For instance <code>SqlServerCe</code> though initially was at 64 KB, it didn't grow at all after adding a few hundred records, while <code>VistaDb</code> grew easily from 48 to 72 to 140 KB. SQLite was the best in that regard which started from the lowest and grew linearly.</p> <p>Few anecdotes: I had better performance using SqlServerCe with the factory settings which means its the easiest to get kick started without any configuration, while I found Firebird little bit harder to get it started due to lack of online materials. Firebird as I could read had widest standard sql compliance. While VistaDb is written in fully managed C# which means it can be merged with your application's assembly to have one single file, it seemed slowest to me. Of all, considering performance, ease and size I chose SQLite. SqlServerCe would be my second choice.</p> <p>In short each has its pluses and minuses. Again, take my rant with a pinch of salt, its just my personal experience.</p>
<p><a href="http://www.sqlite.org/" rel="nofollow noreferrer">SQLite</a> will be what you're after</p>
34,118
<p>I have the following code</p> <pre><code>Try 'Some code that causes exception Catch ex as ExceptionType1 'Handle Section - 1 Catch ex as ExceptionType2 'Handle section - 2 Catch ex as ExceptionType3 'Handle section - 3 Finally ' Clean up End Try </code></pre> <p>Suppose ExceptionType1 is thrown by the code which is handled by section - 1. After handling that in section-1, can I have control passed to section-2/section-3? Is that possible?</p>
<p>Change the code to catch all the exceptions in one block and determine the type and execution path from there. </p>
<p>I think you could get the behavior you want if you do nested try blocks. Once an exception is thrown, execution goes to the catch block. If nothing is rethrown, it moves on to finally. </p>
47,512
<p>I'm just starting out with F# and I can't find the syntax to do object initialization like in C# 3. </p> <p>I.e. given this:</p> <pre><code>public class Person { public DateTime BirthDate { get; set; } public string Name { get; set; } } </code></pre> <p>how do I write the following in F#:</p> <pre><code>var p = new Person { Name = "John", BirthDate = DateTime.Now }; </code></pre>
<p>You can do it like this:</p> <pre><code>let p = new Person (Name = "John", BirthDate = DateTime.Now) </code></pre>
<p>You can also omit the <code>new</code> keyword and use less verbose syntax: </p> <pre><code>let p = Person(BirthDate = DateTime.Now, Name = "John") </code></pre> <p><a href="https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/members/constructors" rel="nofollow noreferrer">https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/members/constructors</a></p>
48,609
<p>I want to write a simple utility to upload images to various free image hosting websites like TinyPic or Imageshack via a right-click context menu for the file.</p> <p>How can I do this using .NET? I've seen some linux scripts that use cURL to post images to these website but I'm not sure how I could create the post request, complete with an image in C#?</p> <p>Can someone point me in the right direction?</p> <hr> <p>EDIT:</p> <p>I've found a pretty good resource. Cropper, a free screenshot tool written in .net, has a lot of open-source plugins. One of them is a SendToTinyPic.. complete with source. Link here:<br> <a href="http://www.codeplex.com/cropperplugins" rel="nofollow noreferrer">http://www.codeplex.com/cropperplugins</a></p>
<p>Use HttpWebRequest.</p> <p>Using this class, you can POST data to a remote HTTP address, just set the mime/type to multi-part/form encoded, and post the binary data from the image with the request.</p> <p><a href="http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(VS.71).aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest(VS.71).aspx</a></p>
<p><a href="http://tinypic.com" rel="nofollow noreferrer">TinyPic.com</a> doesn't have an API as far as I know, but the Cropper SendToTinyPic Plugin tries to upload using "Screen scraping". The official version of the plugin doesn't work right now, but I put together a patch using the same approach, and submitted it to the <a href="http://cropperplugins.codeplex.com" rel="nofollow noreferrer">cropperplugins project</a>. It's just one source module that changed. Anyone can download the plugins project, and then drop in my patch and it should work. </p> <p>With the patch, it's PritScrn or Alt-PrntScrn will save the image and upload to tinypic, and stuff the URL of the raw image on your clipboard. All in 2 seconds. easy. </p> <p>If you don't want the actual tool, you can still look at the source code of my patch to see how to POST a page with form-data and a file upload. No direct link. See <a href="http://cropperplugins.codeplex.com/SourceControl/PatchList.aspx" rel="nofollow noreferrer">http://cropperplugins.codeplex.com/SourceControl/PatchList.aspx</a> and look for #3239. </p> <hr> <p>This example image was produced and then auto-uploaded to tinypic.com with the Alt-PrtScrn key-combo. <a href="https://i.stack.imgur.com/WfEhw.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/WfEhw.png" alt="Example image"></a> </p> <p>To embed it here, I just had to ctrl-V because the URL is stored on the clipboard. </p>
34,740
<p>Is there a reason why zero is used as a "default" function return value? I noticed that several functions from the stdlib and almost everywhere else, when not returning a proper number (e.g pow(), strcpy()) or an error (negative numbers), simply return zero.</p> <p>I just became curious after seeing several tests performed with negated logic. Very confusing.</p> <p>Why not return 1, or 0xff, or any positive number for that matter?</p>
<p>The rationale is that you want to distinguish the set of all the possible (negative) return values corresponding to different errors <em>from</em> the only situation in which all went OK. The simplest, most concise and most C-ish way to pursue such distinction is a logical test, and since in C all integers are "true" except for zero, you want to return zero to mean "the only situation", i.e. you want zero as the "good" value.</p> <p>The same line of reasoning applies to the return values of Unix programs, but indeed in the tests within Unix shell scripts the logic is inverted: a return value of 0 means "true" (for example, look at the return value of /bin/true).</p>
<p>Because 0 is false and null in C/C++ and you can make handy short cuts when that happens.</p>
42,743