Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm looking for the best JavaScript editor available as an Eclipse plugin. I've been using Spket which is good. But, is there more better one?
Disclaimer, I work at Aptana. I would point out there are some nice features for JS that you might not get so easily elsewhere. One is plugin-level integration of JS libraries that provide CodeAssist, samples, snippets and easy inclusion of the libraries files into your project; we provide the plugins for many of the m...
[Eclipse HTML Editor Plugin](http://amateras.sourceforge.jp/cgi-bin/fswiki_en/wiki.cgi?page=EclipseHTMLEditor) I too have struggled with this totally obvious question. It seemed crazy that this wasn't an extremely easy-to-find feature with all the web development happening in Eclipse these days. I was very turned off...
JavaScript editor within Eclipse
[ "", "javascript", "eclipse", "plugins", "editor", "" ]
On the other end of the spectrum, I would be happy if I could install a wiki and share the login credentials between [WordPress](http://en.wikipedia.org/wiki/WordPress) and the wiki. I hacked [MediaWiki](http://en.wikipedia.org/wiki/MediaWiki) a while ago to share logins with another site (in [ASP Classic](http://en.wi...
The tutorial *[WordPress, bbPress & MediaWiki](https://bbpress.org/forums/topic/mediawiki-bbpress-and-wordpress-integration/)* should get you on the right track to integrating MediaWiki into your WordPress install. It's certainly going to be a *lot* easier than hacking WordPress to have wiki features, especially with t...
[WPMW](http://ciarang.com/wiki/page/WPMW), a solution for integrating a MediaWiki within a WordPress installation, might help.
WordPress MediaWiki integration
[ "", "php", "mysql", "wordpress", "lamp", "mediawiki", "" ]
I'm currently writing an ASP.Net app from the UI down. I'm implementing an MVP architecture because I'm sick of Winforms and wanted something that had a better separation of concerns. So with MVP, the Presenter handles events raised by the View. Here's some code that I have in place to deal with the creation of users:...
That sounds just right to me. Exceptions are preferable as they can be thrown up to the top of the service layer from anywhere inside the service layer, no matter how deeply nested inside the service method implementation it is. This keeps the service code clean as you know the calling presenter will always get notific...
As Cheekysoft suggests, I would tend to move all major exceptions into an ExceptionHandler and let those exceptions bubble up. The ExceptionHandler would render the appropriate view for the type of exception. Any validation exceptions however should be handled in the view but typically this logic is common to many par...
How Do You Communicate Service Layer Messages/Errors to Higher Layers Using MVP?
[ "", "c#", "asp.net", "exception", "mvp", "n-tier-architecture", "" ]
Prior to C# generics, everyone would code collections for their business objects by creating a collection base that implemented IEnumerable IE: ``` public class CollectionBase : IEnumerable ``` and then would derive their Business Object collections from that. ``` public class BusinessObjectCollection : CollectionB...
I am generally in the camp of just using a List directly, unless for some reason I need to encapsulate the data structure and provide a limited subset of its functionality. This is mainly because if I don't have a specific need for encapsulation then doing it is just a waste of time. However, with the aggregate initia...
It's [recommended](http://blogs.msdn.com/fxcop/archive/2006/04/27/faq-why-does-donotexposegenericlists-recommend-that-i-expose-collection-lt-t-gt-instead-of-list-lt-t-gt-david-kean.aspx) that in public API's not to use List<T>, but to use Collection<T> If you are inheriting from it though, you should be fine, afaik.
List<BusinessObject> or BusinessObjectCollection?
[ "", "c#", ".net", "generics", "collections", "class-design", "" ]
What is the best way to iterate through a strongly-typed generic List in C#.NET and VB.NET?
For C#: ``` foreach(ObjectType objectItem in objectTypeList) { // ...do some stuff } ``` Answer for VB.NET from **Purple Ant**: ``` For Each objectItem as ObjectType in objectTypeList 'Do some stuff ' Next ```
With any generic implementation of IEnumerable the best way is: ``` //C# foreach( var item in listVariable) { //do stuff } ``` There is an important exception however. IEnumerable involves an overhead of Current() and MoveNext() that is what the foreach loop is actually compiled into. When you have a simple arra...
What is the best way to iterate through a strongly-typed generic List<T>?
[ "", "c#", ".net", "vb.net", "generics", "collections", "" ]
I am writing a webapp using CodeIgniter that requires authentication. I created a model which handles all my authentication. However, I can't find a way to access this authentication model from inside another model. Is there a way to access a model from inside another mode, or a better way to handle authentication insi...
In general, you don't want to create objects inside an object. That's a bad habit, instead, write a clear API and inject a model into your model. ``` <?php // in your controller $model1 = new Model1(); $model2 = new Model2(); $model2->setWhatever($model1); ?> ```
It seems you can load models inside models, although you probably should solve this another way. See [CodeIgniter forums](http://codeigniter.com/forums/viewthread/49625) for a discussion. ``` class SomeModel extends Model { function doSomething($foo) { $CI =& get_instance(); $CI->load->model('SomeOtherMode...
Can you access a model from inside another model in CodeIgniter?
[ "", "php", "codeigniter", "authentication", "model", "" ]
One of the fun parts of multi-cultural programming is number formats. * Americans use 10,000.50 * Germans use 10.000,50 * French use 10 000,50 My first approach would be to take the string, parse it backwards until I encounter a separator and use this as my decimal separator. There is an obvious flaw with that: 10.00...
I think the best you can do in this case is to take their input and then show them what you think they meant. If they disagree, show them the format you're expecting and get them to enter it again.
I don't know the ASP.NET side of the problem but .NET has a pretty powerful class: [System.Globalization.CultureInfo](https://learn.microsoft.com/dotnet/api/system.globalization.cultureinfo). You can use the following code to parse a string containing a double value: ``` double d = double.Parse("100.20", CultureInfo.C...
Floating Point Number parsing: Is there a Catch All algorithm?
[ "", "c#", ".net", "asp.net", "internationalization", "globalization", "" ]
Reading through [this question](https://stackoverflow.com/questions/39879/why-doesnt-javascript-support-multithreading) on multi-threaded javascript, I was wondering if there would be any security implications in allowing javascript to spawn mutliple threads. For example, would there be a risk of a malicious script rep...
No, multiple threads would not add extra security problems in a perfect implementation. Threaded javascript would add complexity to the javascript interpreter which makes it more likely to have an exploitable bug. But threads alone are not going to add any security issues. Threads are not present in javascript because...
Well, you can already lock up a browser and *seriously* slow down a system with badly-behaved JS. Enlightened browsers have implemented checks for this sort of thing, and will stop it before it gets out of hand. I would tend to assume that threads would be dealt with in a similar manner. --- Perhaps you could explai...
Security implications of multi-threaded javascript
[ "", "javascript", "multithreading", "" ]
Using C# and System.Data.SqlClient, is there a way to retrieve a list of parameters that belong to a stored procedure on a SQL Server before I actually execute it? I have an a "multi-environment" scenario where there are multiple versions of the same database schema. Examples of environments might be "Development", "S...
You can use SqlCommandBuilder.DeriveParameters() (see [SqlCommandBuilder.DeriveParameters - Get Parameter Information for a Stored Procedure - ADO.NET Tutorials](https://web.archive.org/web/20110304121600/http://www.davidhayden.com/blog/dave/archive/2006/11/01/SqlCommandBuilderDeriveParameters.aspx)) or there's [this w...
You want the [SqlCommandBuilder.DeriveParameters(SqlCommand)](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommandbuilder.deriveparameters.aspx) method. Note that it requires an additional round trip to the database, so it is a somewhat significant performance hit. You should consider caching the re...
How can I retrieve a list of parameters from a stored procedure in SQL Server
[ "", "c#", "sql-server", "ado.net", "" ]
We're working on a Log Viewer. The use will have the option to filter by user, severity, etc. In the Sql days I'd add to the query string, but I want to do it with Linq. How can I conditionally add where-clauses?
if you want to only filter if certain criteria is passed, do something like this ``` var logs = from log in context.Logs select log; if (filterBySeverity) logs = logs.Where(p => p.Severity == severity); if (filterByUser) logs = logs.Where(p => p.User == user); ``` Doing so this way will allow you...
If you need to filter base on a List / Array use the following: ``` public List<Data> GetData(List<string> Numbers, List<string> Letters) { if (Numbers == null) Numbers = new List<string>(); if (Letters == null) Letters = new List<string>(); var q = from d in d...
How can I conditionally apply a Linq operator?
[ "", "c#", "linq", "linq-to-sql", "" ]
I'm using the Infragistics grid and I'm having a difficult time using a drop-down list as the value selector for one of my columns. I tried reading the documentation but Infragistics' documentation is not so good. I've also taken a look at this [discussion](http://news.infragistics.com/forums/p/9063/45792.aspx) with n...
I've found what was wrong. The column must allow updates. ``` uwgMyGrid.Columns.FromKey("colTest").AllowUpdate = AllowUpdate.Yes; ```
Here's an example from one of my pages: ``` UltraWebGrid uwgMyGrid = new UltraWebGrid(); uwgMyGrid.Columns.Add("colTest", "Test Dropdown"); uwgMyGrid.Columns.FromKey("colTest").Type = ColumnType.DropDownList; uwgMyGrid.Columns.FromKey("colTest").ValueList.ValueListItems.Insert(0, "ONE", "Choice 1"); uwgMyGrid.Columns....
UltraWebGrid: How to use a drop-down list in a column
[ "", "c#", "asp.net", "grid", "infragistics", "ultrawebgrid", "" ]
We have an application with a good amount of jQuery JSON calls to server side code. Because of this, we have a large amount of binding code to parse responses and bind the appropriate values to the form. This is a two part question. 1. What is the reccomended approach for dealing with a large number of forms that all ...
Not 100% sure example what you are asking, but personally, and I use MochiKit, I create JavaScript "classes" (or widgets, if you prefer) for every significant client-side UI structure. These know, of course, how to populate themselves with data. I don't know what more there is to say - writing UI code for the browser ...
You should probably look into a framework like [knockout.js](http://www.knockoutjs.com) This way you can just update your models and the forms will update automatically.
Best practices with jQuery form binding code in an application
[ "", "javascript", "jquery", "ooad", "" ]
A question related to [Regular cast vs. static\_cast vs. dynamic\_cast](https://stackoverflow.com/questions/28002): What cast syntax style do you prefer in C++? * C-style cast syntax: `(int)foo` * C++-style cast syntax: `static_cast<int>(foo)` * constructor syntax: `int(foo)` They may not translate to exactly the sa...
It's best practice *never* to use C-style casts for three main reasons: * as already mentioned, no checking is performed here. The programmer simply cannot know which of the various casts is used which weakens strong typing * the new casts are intentionally visually striking. Since casts often reveal a weakness in the...
According to [Stroustrup](http://www.research.att.com/~bs/bs_faq2.html#static-cast): > The "new-style casts" were introduced > to give programmers a chance to state > their intentions more clearly and for > the compiler to catch more errors. So really, its for safety as it does extra compile-time checking.
C++ cast syntax styles
[ "", "c++", "coding-style", "casting", "" ]
Can anyone tell me how I can display a status message like "12 seconds ago" or "5 minutes ago" etc in a web page?
Here is the php code for the same: ``` function time_since($since) { $chunks = array( array(60 * 60 * 24 * 365 , 'year'), array(60 * 60 * 24 * 30 , 'month'), array(60 * 60 * 24 * 7, 'week'), array(60 * 60 * 24 , 'day'), array(60 * 60 , 'hour'), array(60 , 'minute'), ...
``` function timeAgo($timestamp){ $datetime1=new DateTime("now"); $datetime2=date_create($timestamp); $diff=date_diff($datetime1, $datetime2); $timemsg=''; if($diff->y > 0){ $timemsg = $diff->y .' year'. ($diff->y > 1?"'s":''); } else if($diff->m > 0){ $timemsg = $diff->m . ' m...
How to display "12 minutes ago" etc in a PHP webpage?
[ "", "php", "" ]
Whats the best/easiest way to obtain a count of items within an IEnumerable collection without enumerating over all of the items in the collection? Possible with LINQ or Lambda?
You will have to enumerate to get a count. Other constructs like the List keep a running count.
In any case, you have to loop through it. Linq offers the `Count` method: ``` var result = myenum.Count(); ```
The best way to get a count of IEnumerable<T>
[ "", "c#", "linq", "" ]
For a given class I would like to have tracing functionality i.e. I would like to log every method call (method signature and actual parameter values) and every method exit (just the method signature). How do I accomplish this assuming that: * I don't want to use any 3rd party AOP libraries for C#, * I don't want t...
C# is not an AOP oriented language. It has some AOP features and you can emulate some others but making AOP with C# is painful. I looked up for ways to do exactly what you wanted to do and I found no easy way to do it. As I understand it, this is what you want to do: ``` [Log()] public void Method1(String name, Int3...
The simplest way to achieve that is probably to use [PostSharp](http://www.postsharp.net). It injects code inside your methods based on the attributes that you apply to it. It allows you to do exactly what you want. Another option is to use the [profiling API](http://msdotnetsupport.blogspot.com/2006/08/net-profiling-...
How do I intercept a method call in C#?
[ "", "c#", "reflection", "aop", "" ]
I've been taking a look at some different products for .NET which propose to speed up development time by providing a way for business objects to map seamlessly to an automatically generated database. I've never had a problem writing a data access layer, but I'm wondering if this type of product will really save the ti...
I have used SubSonic and EntitySpaces. Once you get the hang of them, I beleive they can save you time, but as complexity of your app and volume of data grow, you may outgrow these tools. You start to lose time trying to figure out if something like a performance issue is related to the ORM or to your code. So, to answ...
I've found [iBatis](http://ibatis.apache.org/) from the Apache group to be an excellent solution to this problem. My team is currently using iBatis to map all of our calls from Java to our MySQL backend. It's been a huge benefit as it's easy to manage all of our SQL queries and procedures because they're all located in...
Simple Object to Database Product
[ "", "c#", ".net", "database", "orm", "" ]
If I have Python code ``` class A(): pass class B(): pass class C(A, B): pass ``` and I have class `C`, is there a way to iterate through it's super classed (`A` and `B`)? Something like pseudocode: ``` >>> magicGetSuperClasses(C) (<type 'A'>, <type 'B'>) ``` One solution seems to be [inspect module](ht...
`C.__bases__` is an array of the super classes, so you could implement your hypothetical function like so: ``` def magicGetSuperClasses(cls): return cls.__bases__ ``` But I imagine it would be easier to just reference `cls.__bases__` directly in most cases.
@John: Your snippet doesn't work -- you are returning the *class* of the base classes (which are also known as metaclasses). You really just want `cls.__bases__`: ``` class A: pass class B: pass class C(A, B): pass c = C() # Instance assert C.__bases__ == (A, B) # Works assert c.__class__.__bases__ == (A, B) # Works...
Python super class reflection
[ "", "python", "reflection", "" ]
I know that you can insert multiple rows at once, is there a way to update multiple rows at once (as in, in one query) in MySQL? Edit: For example I have the following ``` Name id Col1 Col2 Row1 1 6 1 Row2 2 2 3 Row3 3 9 5 Row4 4 16 8 ``` I want to combine all the following Upd...
Yes, that's possible - you can use INSERT ... ON DUPLICATE KEY UPDATE. Using your example: ``` INSERT INTO table (id,Col1,Col2) VALUES (1,1,1),(2,2,3),(3,9,3),(4,10,12) ON DUPLICATE KEY UPDATE Col1=VALUES(Col1),Col2=VALUES(Col2); ```
Since you have dynamic values, you need to use an IF or CASE for the columns to be updated. It gets kinda ugly, but it should work. Using your example, you could do it like: ``` UPDATE table SET Col1 = CASE id WHEN 1 THEN 1 WHEN 2 THEN 2 ...
Multiple Updates in MySQL
[ "", "mysql", "sql", "sql-update", "" ]
Since both a `Table Scan` and a `Clustered Index Scan` essentially scan all records in the table, why is a Clustered Index Scan supposedly better? As an example - what's the performance difference between the following when there are many records?: ``` declare @temp table( SomeColumn varchar(50) ) insert into @t...
In a table without a clustered index (a heap table), data pages are not linked together - so traversing pages requires a [lookup into the Index Allocation Map](http://msdn.microsoft.com/en-us/library/ms188270.aspx). A clustered table, however, has it's [data pages linked in a doubly linked list](http://msdn.microsoft....
<http://msdn.microsoft.com/en-us/library/aa216840(SQL.80).aspx> The Clustered Index Scan logical and physical operator scans the clustered index specified in the Argument column. When an optional WHERE:() predicate is present, only those rows that satisfy the predicate are returned. If the Argument column contains the...
What's the difference between a Table Scan and a Clustered Index Scan?
[ "", "sql", "sql-server", "indexing", "" ]
In Maven, dependencies are usually set up like this: ``` <dependency> <groupId>wonderful-inc</groupId> <artifactId>dream-library</artifactId> <version>1.2.3</version> </dependency> ``` Now, if you are working with libraries that have frequent releases, constantly updating the <version> tag can be somewhat annoy...
***NOTE:*** *The mentioned `LATEST` and `RELEASE` metaversions [have been dropped **for plugin dependencies** in Maven 3 "for the sake of reproducible builds"](https://cwiki.apache.org/confluence/display/MAVEN/Maven+3.x+Compatibility+Notes#Maven3.xCompatibilityNotes-PluginMetaversionResolution), over 6 years ago. (The...
Now I know this topic is old, but reading the question and the OP supplied answer it seems the [Maven Versions Plugin](http://www.mojohaus.org/versions-maven-plugin/) might have actually been a better answer to his question: In particular the following goals could be of use: * **versions:use-latest-versions** searche...
How do I tell Maven to use the latest version of a dependency?
[ "", "java", "maven", "dependencies", "maven-2", "maven-metadata", "" ]
Is anyone else having trouble running Swing applications from IntelliJ IDEA 8 Milestone 1? Even the simplest application of showing an empty JFrame seems to crash the JVM. I don't get a stack trace or anything, it looks like the JVM itself crashes and Windows shows me a pop-up that says the usual "This process is no lo...
I have actually experienced problems from using the JDK 6u10 beta myself and had to downgrade to JDK 6u7 for the time being. This solved some of my problems with among other things swing. Also, i have been running IJ8M1 since the 'release' and I am very satisfied with it, especially if you regard the "beta" tag. It fe...
Ask your question directly on the IDEA website. They always react fast and the problem you have is probably either fixed or documented.
Problems running Swing application with IDEA 8M1
[ "", "java", "swing", "ide", "jvm", "intellij-idea", "" ]
I'm using LINQ to SQL classes in a project where the database design is still in a bit of flux. Is there an easy way of synchronising the classes with the schema, or do I need to manually update the classes if a table design changes?
You can use SQLMetal.exe to generate your dbml and or cs/vb file. Use a pre-build script to start it and target the directory where your datacontext project belongs. ``` C:\Program Files\Microsoft SDKs\Windows\v6.0A\Bin\x64\sqlmetal.exe /server:<SERVER> /database:<database> /code:"path\Solution\DataContextPro...
I haven't tried it myself, but [Huagati DBML/EDMX Tools](http://www.huagati.com/dbmltools/) is recommended by other people. > Huagati DBML/EDMX Tools is an add-in > for Visual Studio that adds > functionality to the Linq2SQL/DBML > diagram designer in Visual Studio > 2008, and to the ADO.NET Entity > Framework designe...
Best way to update LINQ to SQL classes after database schema change
[ "", "c#", ".net", "linq-to-sql", "" ]
I'm trying to create a webapplication where I want to be able to plug-in separate assemblies. I'm using MVC preview 4 combined with Unity for dependency injection, which I use to create the controllers from my plugin assemblies. I'm using WebForms (default aspx) as my view engine. If I want to use a view, I'm stuck on...
Essentially this is the same issue as people had with WebForms and trying to compile their UserControl ASCX files into a DLL. I found this <http://www.codeproject.com/KB/aspnet/ASP2UserControlLibrary.aspx> that might work for you too.
It took me way too long to get this working properly from the various partial samples, so here's the full code needed to get views from a Views folder in a shared library structured the same as a regular Views folder but with everything set to build as embedded resources. It will only use the embedded file if the usual...
Views in separate assemblies in ASP.NET MVC
[ "", "c#", "asp.net-mvc", "plugins", "" ]
I'm going to start a new project - rewriting an existing system (PHP + SQL Server) from scratch because of some very serious limitations by design. We have some quite good knowledge of SQL Server (currently we're using SQL Server 2000 in existing system) and we would like to employ its newer version (2008 I guess) in ...
I've worked on a project using MSQL Server in conjunction with a Java Stack. It works very well and as long, since JDBC shouldn't really care about your database. We used ehcache together with Hibernate and had problems with the MS JDBC Driver, so we switched to jtds and it works really good. It's quite a while ago, s...
I don't know about Java and 2008... but you shouldn't have too much trouble with Java and SQL2000. As lubos suggested, you'd be doing yourself a favour to look at c# but if you're much more comfortable with Java then there shouldn't be any real limitations as the JDBC connector [is supported by Microsoft](http://msdn.m...
Java + SQL Server - a viable solution?
[ "", "java", "sql-server", "" ]
What would be the best way to have a list of items with a checkbox each in Java Swing? I.e. a JList with items that have some text and a checkbox each?
Create a custom `ListCellRenderer` and asign it to the `JList`. This custom `ListCellRenderer` must return a `JCheckbox` in the implementantion of `getListCellRendererComponent(...)` method. But this `JCheckbox` will not be editable, is a simple paint in the screen is up to you to choose when this `JCheckbox` must be...
A wonderful answer is this [`CheckBoxList`](http://www.devx.com/tips/Tip/5342). It implements Telcontar's answer (though 3 years before :)... I'm using it in Java 1.6 with no problems. I've also added an `addCheckbox` method like this (surely could be shorter, haven't used Java in a while): ``` public void addCheckbox...
How do I make a list with checkboxes in Java Swing?
[ "", "java", "swing", "jcheckbox", "" ]
I'm able to connect to and read an excel file no problem. But when importing data such as zipcodes that have leading zeros, how do you prevent excel from guessing the datatype and in the process stripping out leading zeros?
I believe you have to set the option in your connect string to force textual import rather than auto-detecting it. ``` Provider=Microsoft.ACE.OLEDB.12.0; Data Source=c:\path\to\myfile.xlsx; Extended Properties=\"Excel 12.0 Xml;IMEX=1\"; ``` Your milage may vary depending on the version you have installed. The...
Prefix with '
How do you prevent leading zeros from being stripped when importing an excel doc using c#
[ "", "c#", "asp.net", "excel", "ado.net", "" ]
I am building a public website using ASP.NET, as part of the deliverable I need to do an Admin Site for data entry of the stuff shown in the public site, I was wondering what techniques or procedures are people using to validate entries using ASP.NET MVC.
Take a look at the [JQuery Validation plugin](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) this plugin is amazing,it's clean to implement and has all the features you could ever need, including remote validation via AJAX. Also a sample MVC controller method can be found [here](http://httpcode.com/bl...
IMO using xVal with jQuery and DataAnnotationsModelBinder is the best combination. Sometimes however, there are validation rules which cannot be checked entirely on the client side, so you need to use remote client-side validation. I figured out way to generically implement remote client-side validation with xVal / j...
What's the best way to implement field validation using ASP.NET MVC?
[ "", "c#", "asp.net-mvc", "validation", "" ]
The following PHP code snippet uses GD to resize a browser-uploaded PNG to 128x128. It works great, except that the transparent areas in the original image are being replaced with a solid color- black in my case. Even though `imagesavealpha` is set, something isn't quite right. What's the best way to preserve the tra...
``` imagealphablending( $targetImage, false ); imagesavealpha( $targetImage, true ); ``` did it for me. Thanks ceejayoz. note, the target image needs the alpha settings, not the source image. Edit: full replacement code. See also answers below and their comments. This is not guaranteed to be be perfect in any way, b...
Why do you make things so complicated? the following is what I use and so far it has done the job for me. ``` $im = ImageCreateFromPNG($source); $new_im = imagecreatetruecolor($new_size[0],$new_size[1]); imagecolortransparent($new_im, imagecolorallocate($new_im, 0, 0, 0)); imagecopyresampled($new_im,$im,0,0,0,0,$new_s...
Can PNG image transparency be preserved when using PHP's GDlib imagecopyresampled?
[ "", "php", "png", "transparency", "gd", "alpha", "" ]
Instead of relying on my host to send an email, I was thinking of sending the email messages using my **Gmail** account. The emails are personalized emails to the bands I play on my show. Is it possible to do it?
Be sure to use `System.Net.Mail`, not the deprecated `System.Web.Mail`. Doing SSL with `System.Web.Mail` is a gross mess of hacky extensions. ``` using System.Net; using System.Net.Mail; var fromAddress = new MailAddress("from@gmail.com", "From Name"); var toAddress = new MailAddress("to@example.com", "To Name"); con...
The above answer doesn't work. You have to set `DeliveryMethod = SmtpDeliveryMethod.Network` or it will come back with a "**client was not authenticated**" error. Also it's always a good idea to put a timeout. Revised code: ``` using System.Net.Mail; using System.Net; var fromAddress = new MailAddress("from@gmail.co...
Sending email in .NET through Gmail
[ "", "c#", ".net", "email", "smtp", "gmail", "" ]
When developing whether its Web or Desktop at which point should a developer switch from SQLite, MySQL, MS SQL, etc
It depends on what you are doing. You might switch if: * You need more scalability or better performance - say from SQLite to SQL Server or Oracle. * You need access to more specific datatypes. * You need to support a customer that only runs a particular database. * You need better DBA tools. * Your application is usi...
You should switch databases at milestone 2.3433, 3ps prior to the left branch of dendrite 8,151,215. You should switch databases when you have a reason to do so, would be my advice. If your existing database is performing to your expectations, supports the load that is being placed on it by your production systems, ha...
What point should someone decide to switch Database Systems
[ "", "sql", "database", "" ]
I have a table of tags and want to get the highest count tags from the list. Sample data looks like this ``` id (1) tag ('night') id (2) tag ('awesome') id (3) tag ('night') ``` using ``` SELECT COUNT(*), `Tag` from `images-tags` GROUP BY `Tag` ``` gets me back the data I'm looking for perfectly. However, I would ...
In all versions of MySQL, simply alias the aggregate in the SELECT list, and order by the alias: ``` SELECT COUNT(id) AS theCount, `Tag` from `images-tags` GROUP BY `Tag` ORDER BY theCount DESC LIMIT 20 ```
MySQL prior to version 5 did not allow aggregate functions in ORDER BY clauses. You can get around this limit with the deprecated syntax: ``` SELECT COUNT(id), `Tag` from `images-tags` GROUP BY `Tag` ORDER BY 1 DESC LIMIT 20 ``` 1, since it's the first column you want to group on.
SQL Group By with an Order By
[ "", "mysql", "sql", "mysql-error-1111", "" ]
I am in the middle of reading the excellent [Clean Code](https://rads.stackoverflow.com/amzn/click/com/0132350882) One discussion is regarding passing nulls into a method. ``` public class MetricsCalculator { public double xProjection(Point p1, Point p2) { return (p2.x - p1.x) * 1.5; } } ... calculato...
Both the use of assertions and the throwing of exceptions are valid approaches here. Either mechanism can be used to indicate a programming error, not a runtime error, as is the case here. * Assertions have the advantage of performance as they are typically disabled on production systems. * Exceptions have the advanta...
General rule is if your method doesn't expect `null` arguments then you should throw [System.ArgumentNullException](http://msdn.microsoft.com/en-us/library/system.argumentnullexception.aspx). Throwing proper `Exception` not only protects you from resource corruption and other bad things but serves as a guide for users ...
Passing null to a method
[ "", "java", "null", "assert", "" ]
Most of my C/C++ development involves monolithic module files and absolutely no classes whatsoever, so usually when I need to make a **DLL** with accessible functions I just export them using the standard `__declspec(dllexport)` directive. Then access them either dynamically via `LoadLibrary()` or at compile time with ...
> What about late-binding? As in loading > it with LoadLibrary() and > GetProcAddress() ? I'm used being able > to load the library at run time and it > would be great if you could do that > here. So there are two ways to load the DLL. The first is to reference one or more symbols from the DLL (your classname, for exa...
When you build the DLL and the module that will use the DLL, have some kind of #define that you can use to distinguish between one and the other, then you can do something like this in your class header file: ``` #if defined( BUILD_DLL ) #define IMPORT_EXPORT __declspec(dllexport) #else #define IMPORT_EXPORT _...
Exporting a C++ class from a DLL
[ "", "c++", "windows", "dll", "" ]
I've been writing C and C++ code for almost twenty years, but there's one aspect of these languages that I've never really understood. I've obviously used regular casts i.e. ``` MyClass *m = (MyClass *)ptr; ``` all over the place, but there seem to be two other types of casts, and I don't know the difference. What's ...
## static\_cast `static_cast` is used for cases where you basically want to reverse an implicit conversion, with a few restrictions and additions. `static_cast` performs no runtime checks. This should be used if you know that you refer to an object of a specific type, and thus a check would be unnecessary. Example: `...
## Static cast The static cast performs conversions between compatible types. It is similar to the C-style cast, but is more restrictive. For example, the C-style cast would allow an integer pointer to point to a char. ``` char c = 10; // 1 byte int *p = (int*)&c; // 4 bytes ``` Since this results in a 4-byte ...
Regular cast vs. static_cast vs. dynamic_cast
[ "", "c++", "pointers", "casting", "" ]
I'm looking for the best method to parse various XML documents using a Java application. I'm currently doing this with SAX and a custom content handler and it works great - zippy and stable. I've decided to explore the option having the same program, that currently recieves a single format XML document, receive two ad...
As I understand it, the problem is that you don't know what format the document is prior to parsing. You could use a delegate pattern. I'm assuming you're not validating against a DTD/XSD/etcetera and that it is OK for the DefaultHandler to have state. ``` public class DelegatingHandler extends DefaultHandler { p...
You've done a good job of explaining what you want to do but not why. There are several XML frameworks that simplify marshalling and unmarshalling Java objects to/from XML. The simplest is [Commons Digester](http://commons.apache.org/digester/) which I typically use to parse configuration files. But if you are want to...
How would you use Java to handle various XML documents?
[ "", "java", "xml", "sax", "stax", "" ]
I noticed that many people here use [TextMate](http://macromates.com/) for coding on OS X. I've recently started using it, and although I like its minimalistic interface, it makes it harder to stumble upon cool features if you don't know what you're looking for. So, what feature have you found most helpful for coding ...
Don't neglect the 'mate' command line tool. You can use it to pipe output into TextMate, so if you do the following... ``` diff file1.py file2.py | mate ``` ...it will not only open in TextMate, but it is smart enough to know that you're looking at a diff and highlight lines on screen. TextMate's SVN integration is ...
Holding down option while dragging allows you to highlight a block of text. If you type while the highlight is active, your keystrokes appear on multiple lines.
What are some useful TextMate features?
[ "", "python", "macos", "text-editor", "textmate", "" ]
I'm writing a PHP script that involves scraping web pages. Currently, the script analyzes the page line by line, but it breaks if there is a tag that spans multiple lines, like ``` <img src="example.jpg" alt="example"> ``` If worse comes to worst, I could possibly preprocess the page by removing all line breaks, then...
Perhaps for future projects I'll use a parsing library, but that's kind of aside from the question at hand. This is my current solution. `rstrpos` is strpos, but from the reverse direction. Example use: ``` for($i=0; $i<count($lines); $i++) { $line = handle_mulitline_tags(&$i, $line, $lines); } ``` And here's tha...
This is one of my pet peeves: *never* parse HTML by hand. *Never* parse HTML with regexps. *Never* parse HTML with string comparisons. *Always* use an HTML parser to parse HTML – that's what they're there for. It's been a long time since I've done any PHP, but a quick search turned up [this PHP5 HTML parser](http://Si...
How to determine if an html tag splits across multiple lines
[ "", "php", "html", "scripting", "" ]
Using VS2008, C#, .Net 2 and Winforms how can I make a regular Button look "pressed"? Imagine this button is an on/off switch. `ToolStripButton` has the Checked property, but the regular Button does not.
One method you can used to obtain this option is by placing a "CheckBox" object and changing its "Appearance" from "Normal" to "Button" this will give you the same functionality that I believe you are looking for.
You could probably also use the ControlPaint class for this.
How to make a button appear as if it is pressed?
[ "", "c#", ".net", "winforms", "user-interface", "button", "" ]
I saw this in [an answer to another question](https://stackoverflow.com/a/4384/697449), in reference to shortcomings of the Java spec: > There are more shortcomings and this is a subtle topic. Check [this](http://kiranthakkar.blogspot.com/2007/05/method-overloading-with-new-features-of.html) out: > > ``` > public clas...
In the first case, you have a widening conversion happening. This can be see when runinng the "javap" utility program (included w/ the JDK), on the compiled class: ``` public static void main(java.lang.String[]); Code: 0: iconst_ 5 1: istore_ 1 2: iload_ 1 3: i2l 4: invokestatic #6; //Met...
Yes it is, try it out in a test. You will see "long" printed. It is widening because Java will choose to widen the int into a long before it chooses to autobox it to an Integer, so the hello(long) method is chosen to be called. Edit: [the original post being referenced](https://stackoverflow.com/questions/4242/why-can...
Is this really widening vs autoboxing?
[ "", "java", "primitive", "autoboxing", "" ]
As the title says, is there a way to run the same Adobe AIR app more than once? I have a little widget I wrote that shows thumbnails from a couple of photo streams, and I'd like to fix it so I can look at more than one stream at a time. Thanks!
It seems that this is not possible. From the [documentation](http://livedocs.adobe.com/flex/3/html/help.html?content=app_launch_1.html): > Only one instance of an AIR application is started. When an already running application is invoked again, AIR dispatches a new invoke event to the running instance. It also gives ...
No, it can't. AIR only allows one running instance of any app with the same ID defined in the app.xml file. ``` <application xmlns="http://ns.adobe.com/air/application/1.0"> <id>ApplicationID</id> ``` To work around this you'll either have to create individually ID'd apps for each stream, or create a master app with...
Can the same Adobe AIR app run more than once?
[ "", "javascript", "air", "adobe", "" ]
I've been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could find this online?
Checkout the [TimeComplexity](http://wiki.python.org/moin/TimeComplexity) page on the py dot org wiki. It covers set/dicts/lists/etc at least as far as time complexity goes.
Raymond D. Hettinger does [an excellent talk](http://www.youtube.com/watch?v=hYUsssClE94) ([slides](http://wenku.baidu.com/view/9c6fb20dcc1755270722089d.html)) about Python's built-in collections called 'Core Python Containers - Under the Hood'. The version I saw focussed mainly on `set` and `dict`, but `list` was cove...
Where can I find the time and space complexity of the built-in sequence types in Python
[ "", "python", "performance", "complexity-theory", "big-o", "sequences", "" ]
I have an application which *really* should be installed, but does work fine when deployed using JNLP. However, it would seem that some Java functions such as `Runtime.exec` don't work using the default security options. I would like to therefore [disable](http://www.joelonsoftware.com/items/2008/07/01.html) UI funct...
You want to ask to the [SecurityManager](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/SecurityManager.html) if you have Exec right with the checkExec method.
I have also found that adding the following to the JNLP file: ``` <security> <all-permissions/> </security> ``` And signing the JAR file allows the app to run with all the permissions needed for `Runtime.exec`.
How do I detect if a function is available during JNLP execution?
[ "", "java", "security", "deployment", "permissions", "jnlp", "" ]
What would be the easiest way to be able to send and receive raw network packets. Do I have to write my own JNI wrapping of some c API, and in that case what API am I looking for? EDIT: I want to be able to do what wireshark does, i.e. record all incomming packets on an interface, and in addition be able to send back ...
If you start with the idea that you need something *like* a packet sniffer, you'll want to look at <http://netresearch.ics.uci.edu/kfujii/jpcap/doc/>.
Raw Socket for Java is a request for JDK for a looong long time. See the request [here](https://bugs.java.com/bugdatabase/view_bug.do?bug_id=4727550). There's a long discussion there where you can look for workarounds and solutions. I once needed this for a simple PING operation, but I can't remember how I resolved thi...
How do I read and write raw ip packets from java on a mac?
[ "", "java", "macos", "networking", "" ]
I'm implementing a tagging system for a website. There are multiple tags per object and multiple objects per tag. This is accomplished by maintaining a table with two values per record, one for the ids of the object and the tag. I'm looking to write a query to find the objects that match a given set of tags. Suppose I...
Given: * object table (primary key id) * objecttags table (foreign keys objectId, tagid) * tags table (primary key id) ``` SELECT distinct o.* from object o join objecttags ot on o.Id = ot.objectid join tags t on ot.tagid = t.id where t.Name = 'fruit' or t.name = 'food'; ``` This seems...
Oh gosh I may have mis-interpreted your original comment. The easiest way to do this in SQL would be to have three tables: ``` 1) Tags ( tag_id, name ) 2) Objects (whatever that is) 3) Object_Tag( tag_id, object_id ) ``` Then you can ask virtually any question you want of the data quickly, easily, and efficiently (p...
SQL many-to-many matching
[ "", "sql", "many-to-many", "tagging", "" ]
Jeff actually posted about this in [Sanitize HTML](http://refactormycode.com/codes/333-sanitize-html). But his example is in C# and I'm actually more interested in a Java version. Does anyone have a better version for Java? Is his example good enough to just convert directly from C# to Java? [Update] I have put a boun...
Don't do this with regular expressions. Remember, you're not protecting just against valid HTML; you're protecting against the DOM that web browsers create. Browsers can be tricked into producing valid DOM from invalid HTML quite easily. For example, see this list of [obfuscated XSS attacks](http://ha.ckers.org/xss.ht...
I extracted from NoScript best Anti-XSS addon, here is its Regex: Work flawless: ``` <[^\w<>]*(?:[^<>"'\s]*:)?[^\w<>]*(?:\W*s\W*c\W*r\W*i\W*p\W*t|\W*f\W*o\W*r\W*m|\W*s\W*t\W*y\W*l\W*e|\W*s\W*v\W*g|\W*m\W*a\W*r\W*q\W*u\W*e\W*e|(?:\W*l\W*i\W*n\W*k|\W*o\W*b\W*j\W*e\W*c\W*t|\W*e\W*m\W*b\W*e\W*d|\W*a\W*p\W*p\W*l\W*e\W*t|\W...
Best regex to catch XSS (Cross-site Scripting) attack (in Java)?
[ "", "java", "html", "regex", "xss", "" ]
I'm using `ColdFusion` to populate a template that includes HTML unordered lists (`<ul>`s). Most of these aren't that long, but a few have ridiculously long lengths and could really stand to be in 2-3 columns. Is there an HTML, ColdFusion or perhaps JavaScript (I'm accepting jQuery solutions) way to do this easily? I...
So I dug up this article from A List Apart [CSS Swag: Multi-Column Lists](http://www.alistapart.com/articles/multicolumnlists). I ended up using the first solution, it's not the best but the others require either using complex HTML that can't be generated dynamically, or creating a lot of custom classes, which could be...
If Safari and Firefox support is good enough for you, there is a CSS solution: ``` ul { -webkit-column-count: 3; -moz-column-count: 3; column-count: 3; -webkit-column-gap: 2em; -moz-column-gap: 2em; column-gap: 2em; } ``` I'm not sure about Opera.
Wrapping lists into columns
[ "", "javascript", "jquery", "html", "css", "cfml", "" ]
Most of time we represent concepts which can never be less than 0. For example to declare length, we write: ``` int length; ``` The name expresses its purpose well but you can assign negative values to it. It seems that for some situations, you can represent your intent more clearly by writing it this way instead: `...
“When in Rome, do as the Romans do.” While there is theoretically an advantage in using unsigned values where applicable because it makes the code more expressive, this is simply not done in C#. I'm not sure why the developers initially didn't design the interfaces to handle `uints` and make the type CLS compliant but...
If you decrement a signed number with a value of 0, it becomes negative and you can easily test for this. If you decrement an unsigned number with a value of 0, it underflows and becomes the maximum value for the type - somewhat more difficult to check for.
Using Unsigned Primitive Types
[ "", "c#", "primitive-types", "" ]
I'm trying to add support for stackoverflow feeds in my rss reader but **SelectNodes** and **SelectSingleNode** have no effect. This is probably something to do with ATOM and xml namespaces that I just don't understand yet. I have gotten it to work by removing all attributes from the **feed** tag, but that's a hack an...
Don't confuse the namespace names in the XML file with the namespace names for your namespace manager. They're both shortcuts, and they don't necessarily have to match. So you can register "<http://www.w3.org/2005/Atom>" as "atom", and then do a SelectNodes for "atom:entry".
You might need to add a XmlNamespaceManager. ``` XmlDocument document = new XmlDocument(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable); nsmgr.AddNamespace("creativeCommons", "http://backend.userland.com/creativeCommonsRssModule"); // AddNamespace for other namespaces too. document.Load(feed...
SelectNodes not working on stackoverflow feed
[ "", "c#", ".net", "rss", "atom-feed", "" ]
In Ruby on Rails, I'm attempting to update the `innerHTML` of a div tag using the `form_remote_tag` helper. This update happens whenever an associated select tag receives an onchange event. The problem is, `<select onchange="this.form.submit();">`; doesn't work. Nor does `document.forms[0].submit()`. The only way to ge...
If you didn't actually want to submit the form, but just invoke whatever code happened to be in the onsubmit, you could possibly do this: (untested) ``` var code = document.getElementById('formId').getAttribute('onsubmit'); eval(code); ```
I realize this question is kind of old, but what the heck are you doing eval for? ``` document.getElementById('formId').onsubmit(); document.getElementById('formId').submit(); ``` or ``` document.formName.onsubmit(); document.formName.submit(); ``` When the DOM of a document is loaded, the events are not strings an...
Is it possible to call Javascript's onsubmit event programmatically on a form?
[ "", "javascript", "ruby-on-rails", "ruby", "" ]
Currently we have a hybrid ASP/PHP setup connecting to a SQL Server 2005 database. But all the query work is done on the client side, I'd like to move some of this to PHP. What driver and/or connection string is needed to connect to Sql Svr and what is the syntax to use in PHP? --- Update: OK so I was definitely try...
You have two options: 1) **php\_mssql extension** : If you'd like something that has the same API mysql and mysqli has, then use the php\_mssql extension. But there is a catch, the bundled ntwdblib.dll file with PHP is not working. You have to find this file from a SQL Server 2000 installation or you can find it on th...
Just use the mssql\_connect() function like this: ``` $conn = mssql_connect('localhost', 'sa' , '123456') or die('Can\'t connect.'); mssql_select_db('database', $conn) or die('Can\'t select the database'); ``` Functions relating to SQL Server are defined in the [PHP manual for the MSSQL driver](http://www.php...
PHP with SQL Server 2005+
[ "", "php", "sql-server", "" ]
I have a ListBox that has a style defined for ListBoxItems. Inside this style, I have some labels and a button. One that button, I want to define a click event that can be handled on my page (or any page that uses that style). How do I create an event handler on my WPF page to handle the event from my ListBoxItems styl...
Take a look at [RoutedCommand](http://msdn.microsoft.com/en-us/library/system.windows.input.routedcommand.aspx)s. Define your command in myclass somewhere as follows: ``` public static readonly RoutedCommand Login = new RoutedCommand(); ``` Now define your button with this command: ``` <Button Command="{x:S...
As Arcturus posted, RoutedCommands are a great way to achieve this. However, if there's only the one button in your DataTemplate then this might be a bit simpler: You can actually handle any button's Click event from the host ListBox, like this: ``` <ListBox Button.Click="removeButtonClick" ... /> ``` Any buttons co...
WPF Listbox style with a button
[ "", "c#", "wpf", "" ]
How do I convert the value of a PHP variable to string? I was looking for something better than concatenating with an empty string: ``` $myText = $myVar . ''; ``` Like the `ToString()` method in Java or .NET.
You can use the [casting operators](https://www.php.net/manual/en/language.types.type-juggling.php): ``` $myText = (string)$myVar; ``` There are more details for string casting and conversion in the [Strings section](https://www.php.net/manual/en/language.types.string.php#language.types.string.casting) of the PHP man...
This is done with typecasting: ``` $strvar = (string) $var; // Casts to string echo $var; // Will cast to string implicitly var_dump($var); // Will show the true type of the variable ``` In a class you can define what is output by using the magical method [`__toString`](http://www.php.net/manual/en/language.oop5.magi...
PHP equivalent of .NET/Java's toString()
[ "", "php", "string", "" ]
We have a PHP project that we would like to version control. Right now there are three of us working on a development version of the project which resides in an external folder to which all of our Eclipse IDEs are linked, and thus no version control. What is the right way and the best way to version control this? We ...
We were in a similar situation, and here's what we ended up doing: * Set up two branches -- the release and development branch. * For the development branch, include a post-commit hook that deploys the repository to the dev server, so you can test. * Once you're ready, you merge your changes into the release branch. I...
Here is what we do: * Each dev has a VM that is configured like our integration server * The integration server has space for Trunk, each user, and a few slots for branches * The production server * Hooks are in Subversion to e-mail when commits are made At the beginning of a project, the user makes a branch and chec...
Version control PHP Web Project
[ "", "php", "svn", "version-control", "cvs", "" ]
We would like to have user defined formulas in our c++ program. e.g. The value *v = x + ( y - (z - 2)) / 2*. Later in the program the user would define x,y and z -> the program should return the result of the calculation. Somewhen later the formula may get changed, so the next time the program should parse the formu...
If it will be used frequently and if it will be extended in the future, I would almost recommend adding either Python or Lua into your code. [Lua](http://www.lua.org/) is a very lightweight scripting language which you can hook into and provide new functions, operators etc. If you want to do more robust and complicated...
You can represent your formula as a tree of operations and sub-expressions. You may want to define types or constants for Operation types and Variables. You can then easily enough write a method that recurses through the tree, applying the appropriate operations to whatever values you pass in.
calculating user defined formulas (with c++)
[ "", "c++", "" ]
For whatever reason, our company has a coding guideline that states: `Each class shall have it's own header and implementation file.` So if we wrote a class called `MyString` we would need an associated **MyStringh.h** and **MyString.cxx**. Does anyone else do this? Has anyone seen any compiling performance repercus...
The term here is **translation unit** and you really want to (if possible) have one class per translation unit ie, one class implementation per .cpp file, with a corresponding .h file of the same name. It's usually more efficient (from a compile/link) standpoint to do things this way, especially if you're doing things...
## Overwhelmed by thousands lines of code? Having one set of header/source files per class in a directory can seem overkill. And if the number of classes goes toward 100 or 1000, it can even be frightening. But having played with sources following the philosophy "let's put together everything", the conclusion is that...
Multiple classes in a header file vs. a single header file per class
[ "", "c++", "performance", "file-organization", "" ]
I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use `import os` and then use a command line speech program to say "Process complete". I much rather it be a simple "bell." I know that there's a function that can be used in *Cocoa* apps, `NSBeep`, but I don'...
Have you tried : ``` import sys sys.stdout.write('\a') sys.stdout.flush() ``` That works for me here on Mac OS 10.5 Actually, I think your original attempt works also with a little modification: ``` print('\a') ``` (You just need the single quotes around the character sequence).
If you have PyObjC (the Python - Objective-C bridge) installed or are running on OS X 10.5's system python (which ships with PyObjC), you can do ``` from AppKit import NSBeep NSBeep() ``` to play the system alert.
Python Sound ("Bell")
[ "", "python", "macos", "audio", "terminal", "" ]
I want to parse a config file sorta thing, like so: ``` [KEY:Value] [SUBKEY:SubValue] ``` Now I started with a `StreamReader`, converting lines into character arrays, when I figured there's gotta be a better way. So I ask you, humble reader, to help me. One restriction is that it has to work in a Linux/Mono...
> I considered it, but I'm not going to use XML. I am going to be writing this stuff by hand, and hand editing XML makes my brain hurt. :') Have you looked at [YAML](http://www.yaml.org/)? You get the benefits of XML without all the pain and suffering. It's used extensively in the ruby community for things like confi...
I was looking at almost this exact problem the other day: [this article](http://trackerrealm.com/blogs/2007/04/tokenize-string-with-c-regular.html) on string tokenizing is exactly what you need. You'll want to define your tokens as something like: ``` @"(?&ltlevel>\s) | " + @"(?&ltterm>[^:\s]) | " + @"(?&ltseparator>:...
Best method of Textfile Parsing in C#?
[ "", "c#", "fileparse", "" ]
I've been looking for some good genetic programming examples for C#. Anyone knows of good online/book resources? Wonder if there is a C# library out there for Evolutionary/Genetic programming?
After developing [my own Genetic Programming didactic application](http://code.google.com/p/evo-lisa-clone/), I found a complete Genetic Programming Framework called [AForge.NET Genetics](http://code.google.com/p/aforge/source/browse/#svn/trunk/Sources/Genetic). It's a part of the [Aforge.NET library](http://code.googl...
MSDN had an article last year about genetic programming: [Genetic Algorithms: Survival of the Fittest with Windows Forms](http://msdn.microsoft.com/en-us/magazine/cc163934.aspx)
Genetic Programming in C#
[ "", "c#", "genetic-algorithm", "genetic-programming", "evolutionary-algorithm", "" ]
I have a ListView control, and I'm trying to figure out the easiest/best way to disallow changing the selected row(s), without *hiding* the selected row(s). I know there's a `HideSelection` property, but that only works when the `ListView` is still enabled (but not focused). I need the selection to be viewable even wh...
You could also make the ListView ownerdraw. You then have complete control over how the items look whether they are selected or not or whether the ListView itself is enabled or not. The DrawListViewItemEventArgs provides a way to ask the ListView to draw individual parts of the item so you only have to draw the bits yo...
There are two options, change the selected rows disabled colors. Or change all the other rows to simulate they are disabled except for the selected one. The first option is obviously the easiest, and the second option obviously is going to need some extra protections. I have actually done the first option before and i...
Disabling a ListView in C#, but still showing the current selection
[ "", "c#", ".net", "winforms", "listview", "" ]
Every time I create a new project I copy the last project's ant file to the new one and make the appropriate changes (trying at the same time to make it more flexible for the next project). But since I didn't really thought about it at the beginning, the file started to look really ugly. Do you have an Ant template th...
An alternative to making a template is to evolve one by gradually generalising your current project's Ant script so that there are fewer changes to make the next time you copy it for use on a new project. There are several things you can do. Use ${ant.project.name} in file names, so you only have to mention your appli...
You can give <http://import-ant.sourceforge.net/> a try. It is a set of build file snippets that can be used to create simple custom build files.
Best Apache Ant Template
[ "", "java", "ant", "" ]
Suppose I have a stringbuilder in C# that does this: ``` StringBuilder sb = new StringBuilder(); string cat = "cat"; sb.Append("the ").Append(cat).(" in the hat"); string s = sb.ToString(); ``` would that be as efficient or any more efficient as having: ``` string cat = "cat"; string s = String.Format("The {0} in th...
**NOTE:** This answer was written when .NET 2.0 was the current version. This may no longer apply to later versions. `String.Format` uses a `StringBuilder` internally: ``` public static string Format(IFormatProvider provider, string format, params object[] args) { if ((format == null) || (args == null)) { ...
From the [MSDN documentation](http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx): > The performance of a concatenation operation for a String or StringBuilder object depends on how often a memory allocation occurs. A String concatenation operation always allocates memory, whereas a StringBuilder c...
Is String.Format as efficient as StringBuilder
[ "", "c#", "vb.net", "performance", "stringbuilder", "string.format", "" ]
I've been trying to understand how Ruby blocks work, and to do that I've been trying to implement them in C. One easy way to implement closures is to pass a `void*` to the enclosing stack to the closure/function but Ruby blocks also seem to handle returns and break statements from the scope that uses the block. ``` l...
The concept of closures requires the concept of contexts. C's context is based on the stack and the registers of the CPU, so to create a block/closure, you need to be able to manipulate the stack pointer in a correct (and reentrant) way, and store/restore registers as needed. The way this is done by interpreters or vi...
I haven't actually implemented any of this, so take it with a sack of salt. There are two parts to a closure: the data environment and the code environment. Like you said, you can probably pass a void\* to handle references to data. You could probably use setjmp and longjmp to implement the non-linear control flow jum...
Ruby blocks/Java closures in C
[ "", "java", "c", "ruby", "" ]
My question concerns c# and how to access Static members ... Well I don't really know how to explain it (which kind of is bad for a question isn't it?) I will just give you some sample code: ``` Class test<T>{ int method1(Obj Parameter1){ //in here I want to do something which I would explain as ...
One more way to do it, this time some reflection in the mix: ``` static class Parser { public static bool TryParse<TType>( string str, out TType x ) { // Get the type on that TryParse shall be called Type objType = typeof( TType ); // Enumerate the methods of TType foreach( Met...
The problem is that TryParse isn't defined on an interface or base class anywhere, so you can't make an assumption that the type passed into your class will have that function. Unless you can contrain T in some way, you'll run into this a lot. [Constraints on Type Parameters](http://msdn.microsoft.com/en-us/library/d5...
Generics in c# & accessing the static members of T
[ "", "c#", "generics", "static", "methods", "data-access", "" ]
I'm using two different libraries in my project, and both of them supply a basic rectangle `struct`. The problem with this is that there seems to be no way to insert a conversion between the types, so I can't call a function in one library with the result from a function in the other. If I was the author of either of t...
If you can't modify the structures then you have no alternative to writing a manual conversion function because overloading conversion operators only works within the class body. There's no other way.
Create an intermediate shim type "`RectangleEx`", and define custom conversions to/from the 3rd-party string types. Whenever you speak to either API, do so through the shim class. Another way would be to derive a `class` from either `rect` or `Rectangle`, and insert conversions/constructors there.
How can I convert types in C++?
[ "", "c++", "oop", "types", "" ]
I am trying to implement an "out of proc" COM server written in C#. How do I do this? I need the C# code to be "out of proc" from my main C++ application, because I cannot load the .NET runtime into my main process space *WHY?:* My C++ code is in a DLL that is loaded into many different customer EXE's, some of whic...
You can create COM+ components using System.EnterpriseServices.ServicedComponent. Consequently, you'll be able to create out-of-proc and in-proc (client) component activation as well as all COM+ benefits of pooling, remoting, run as a windows service etc.
[Here](http://www.codeproject.com/KB/COM/BuildCOMServersInDotNet.aspx) we can read that it is possible, but the exe will be loaded as an library and not started in it's own process like an exe. I don't know if that is a problem for you? It also contains some possible solutions if you do want to make it act like a real ...
What do I need to do to implement an "out of proc" COM server in C#?
[ "", "c#", "com", "interop", "" ]
I am merging a CVS branch and one of the larger changes is the replacement wherever it occurs of a Singleton pattern with abstract classes that have a static initialisation block and all static methods. Is this something that's worth keeping since it will require merging a lot of conflicts, what sort of situation woul...
From a strict runtime performance point of view, the difference is really negligible. The main difference between the two lies down in the fact that the "static" lifecycle is linked to the classloader, whereas for the singleton it's a regular instance lifecycle. Usually it's better to stay away from the ClassLoader bus...
I would use a singleton if it needed to store any state, and static classes otherwise. There's no point in instantiating something, even a single instance, unless it needs to store something.
Java Singleton vs static - is there a real performance benefit?
[ "", "java", "design-patterns", "singleton", "" ]
I'm seeing strange errors when my C++ code has min() or max() calls. I'm using Visual C++ compilers.
Check if your code is including the **windows.h** header file and either your code or other third-party headers have their own **min()**/**max()** definitions. If yes, then prepend your **windows.h** inclusion with a definition of **NOMINMAX** like this: ``` #define NOMINMAX #include <windows.h> ```
Another possibility could be from side effects. Most min/max macros will include the parameters multiple times and may not do what you expect. Errors and warnings could also be generated. ``` max(a,i++) expands as ((a) > (i++) ? (a) : (i++)) ``` afterwards i is either plus 1 or plus 2 The () in the expansion are to a...
Strange C++ errors with code that has min()/max() calls
[ "", "c++", "c", "" ]
I have a SQL script that inserts data (via INSERT statements currently numbering in the thousands) One of the columns contains a unique identifier (though not an IDENTITY type, just a plain ol' int) that's actually unique across a few different tables. I'd like to add a scalar function to my script that gets the next ...
> I'm starting to think it can't be done that way since there doesn't seem to be a way to maintain the offset counter between calls. Is that right, or is there something I'm missing. You aren't missing anything; SQL Server does not support global variables, and it doesn't support data modification within UDFs. And eve...
If you have 2 users hitting it at the same time they will get the same id. Why didn't you use an id table with an identity instead, insert into that and use that as the unique (which is guaranteed) id, this will also perform much faster > > sp\_getNextID never ever prefix procs with sp\_, this has performance implica...
Can I maintain state between calls to a SQL Server UDF?
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I'm unsure whether the following code would ensure all conditions given in Comparator's Javadoc. ``` class TotalOrder<T> implements Comparator<T> { public boolean compare(T o1, T o2) { if (o1 == o2 || equal(o1, o2)) return 0; int h1 = System.identityHashCode(o1); int h2 = System.identityH...
> Hey, look at what I found! > > <http://gafter.blogspot.com/2007/03/compact-object-comparator.html> Oh yes, I forgot about the IdentityHashMap (Java 6 and above only). Just have to pay attention at releasing your comparator.
Hey, look at what I found! <http://gafter.blogspot.com/2007/03/compact-object-comparator.html> This is exactly what I was looking for.
Impose a total ordering on all instances of *any* class in Java
[ "", "java", "algorithm", "" ]
I have read about partial methods in the latest [C# language specification](http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx), so I understand the principles, but I'm wondering how people are actually using them. Is there a particular design pattern that benefits from partial methods?
Partial methods have been introduced for similar reasons to why partial classes were in .Net 2. A partial class is one that can be split across multiple files - the compiler builds them all into one file as it runs. The advantage for this is that Visual Studio can provide a graphical designer for part of the class wh...
Partial methods are very similar in concept to the GoF [Template Method](http://www.dofactory.com/Patterns/PatternTemplate.aspx) behavioural pattern ([Design Patterns](http://books.google.com/books?id=aQ1RAAAAMAAJ&q=design+patterns&dq=design+patterns&ei=pNO-SJqWEY_-jgH1pvHpDA&pgis=1), p325). They allow the behaviour o...
How are partial methods used in C# 3.0?
[ "", "c#", "design-patterns", ".net-3.5", "partial-methods", "" ]
I am trying to code TDD style in PHP and one of my biggest stumbling blocks (other than lack of a decent IDE) is that I have to make my own hacked together IoC container just to inject all my mock objects properly. Has anyone used an Ioc container in PHP? All I've been able to find is [PHP IOC on the ever-annoying php...
I played with some DI Frameworks for PHP, but I haven't used one in production. Have some links: 1. [http://www.stubbles.net/](http://www.stubbles.net) which I think is the oldest I tried 2. <http://php.xjconf.net/> 3. [FLOW3](http://flow3.typo3.org/) - I belive this one will become a very nice framework (its ...
[Phemto](http://phemto.sourceforge.net/) is being developed again, and looks quite promising IMHO. A few other similar projects, that you might want to look at: [bucket](http://github.com/troelskn/bucket) (Disclaimer: I'm the principal author of this one) The [php-port of picocontainer](http://fisheye.codehaus.org/b...
Inversion of Control Container for PHP?
[ "", "php", "frameworks", "" ]
How can I build a loop in JavaScript?
**For loops** ``` for (i = startValue; i <= endValue; i++) { // Before the loop: i is set to startValue // After each iteration of the loop: i++ is executed // The loop continues as long as i <= endValue is true } ``` **For...in loops** ``` for (i in things) { // If things is an array, i will usually...
Here is an example of a for loop: We have an array of items **nodes**. ``` for(var i = 0; i< nodes.length; i++){ var node = nodes[i]; alert(node); } ```
How do I build a loop in JavaScript?
[ "", "javascript", "loops", "" ]
Assuming you can't use LINQ for whatever reason, is it a better practice to place your queries in stored procedures, or is it just as good a practice to execute *ad hoc* queries against the database (say, SQL Server for argument's sake)?
In my experience writing mostly WinForms Client/Server apps these are the simple conclusions I've come to: **Use Stored Procedures:** 1. For any complex data work. If you're going to be doing something truly requiring a cursor or temp tables it's usually fastest to do it within SQL Server. 2. When you need to lock do...
I can't speak to anything other than SQL Server, but the performance argument is **not** significantly valid there unless you're on 6.5 or earlier. SQL Server has been caching ad-hoc execution plans for roughly a decade now.
Which is better: Ad hoc queries or stored procedures?
[ "", "sql", "stored-procedures", "" ]
I want to show HTML content inside Flash. Is there some way to do this? I am talking about full blown HTML (with JavaScript if possible).
[Here is a decent article](http://www.wdvl.com/Reviews/Graphics/Flash5/external.html) on how to accomplish that. [@Flubba](https://stackoverflow.com/questions/22909/is-there-some-way-to-show-html-content-inside-flash#24396): I didn't say "*great*" article, I said "*decent*" - there is a big difference. Besides, no one...
flashQuery supports HTML tags and CSS rules for Flash. It transforms flash into a really browser. Here it is: <http://www.flashquery.org/>
Is there some way to show HTML content inside Flash?
[ "", "javascript", "html", "flash", "adobe", "" ]
I have a console app that needs to display the state of items, but rather than having text scroll by like mad I'd rather see the current status keep showing up on the same lines. For the sake of example: > `Running... nn% complete` > `Buffer size: bbbb bytes` should be the output, where 'nn' is the current percenta...
You can use [SetConsoleCursorPosition](http://msdn.microsoft.com/en-us/library/ms686025.aspx). You'll need to call [GetStdHandle](http://msdn.microsoft.com/en-us/library/ms683231.aspx) to get a handle to the output buffer.
Joseph, JP, and CodingTheWheel all provided valuable help. For my simple case, the most straight-forward approach seemed to be based on [CodingTheWheel's answer](https://stackoverflow.com/questions/45286/how-can-i-overwrite-the-same-portion-of-the-console-in-a-windows-native-c-conso#45316): ``` // before entering upd...
How can I overwrite the same portion of the console in a Windows native C++ console app, without using a 3rd Party library?
[ "", "c++", "windows", "console", "" ]
I have the following arrays: ``` $artist = ["the roots", "michael jackson", "billy idol", "more", "and more", "and_YET_MORE"]; $count = [5, 3, 9, 1, 1, 3]; ``` I want to generate a tag cloud that will have artists with a higher number in `$count` enclosed in `h6` tags and the lowest enclosed `h1` tags.
You will want to add a logarithmic function to it too. (taken from tagadelic, my Drupal module to create tag clouds <http://drupal.org/project/tagadelic>): ``` db_query('SELECT COUNT(*) AS count, id, name FROM ... ORDER BY count DESC'); $steps = 6; $tags = array(); $min = 1e9; $max = -1e9; while ($tag = db_fetch_obj...
Off the top of my head... ``` $artist = array("the roots","michael jackson","billy idol","more","and more","and_YET_MORE"); $count = array(5,3,9,1,1,3); $highest = max($count); for (int $x = 0; $x < count($artist); $x++) { $normalized = $count[$x] / $highest; $heading = ceil($normalized * 6); // 6 heading type...
Create a tag cloud by wrapping array values in h1 through h6 tags based on a mapping array of weights
[ "", "php", "arrays", "mapping", "tag-cloud", "" ]
I'm looking for a "safe" eval function, to implement spreadsheet-like calculations (using numpy/scipy). The functionality to do this (the [rexec module](http://docs.python.org/lib/module-rexec.html)) has been removed from Python since 2.3 due to apparently unfixable security problems. There are several third-party hac...
Depends on your definition of safe I suppose. A lot of the security depends on what you pass in and what you are allowed to pass in the context. For instance, if a file is passed in, I can open arbitrary files: ``` >>> names['f'] = open('foo', 'w+') >>> safe_eval.safe_eval("baz = type(f)('baz', 'w+')", names) >>> name...
If you simply need to write down and read some data structure in Python, and don't need the actual capacity of executing custom code, this one is a better fit: <http://code.activestate.com/recipes/364469-safe-eval/> It garantees that no code is executed, only static data structures are evaluated: strings, lists, tuple...
Is "safe_eval" really safe?
[ "", "python", "security", "" ]
How do I list the symbols being exported from a .so file? If possible, I'd also like to know their source (e.g. if they are pulled in from a static library). I'm using gcc 4.0.2, if that makes a difference.
The standard tool for listing symbols is `nm`, you can use it simply like this: ``` nm -gD yourLib.so ``` If you want to see symbols of a C++ library, add the "-C" option which demangle the symbols (it's far more readable demangled). ``` nm -gDC yourLib.so ``` If your .so file is in elf format, you have two options...
If your `.so` file is in elf format, you can use readelf program to extract symbol information from the binary. This command will give you the symbol table: ``` readelf -Ws /usr/lib/libexample.so ``` You only should extract those that are defined in this `.so` file, not in the libraries referenced by it. Seventh colu...
How do I list the symbols in a .so file
[ "", "c++", "c", "gcc", "symbols", "name-mangling", "" ]
How do you pass `$_POST` values to a page using `cURL`?
Should work fine. ``` $data = array('name' => 'Ross', 'php_master' => true); // You can POST a file by prefixing with an @ (for <input type="file"> fields) $data['file'] = '@/home/user/world.jpg'; $handle = curl_init($url); curl_setopt($handle, CURLOPT_POST, true); curl_setopt($handle, CURLOPT_POSTFIELDS, $data); cu...
[Ross has the right idea](https://stackoverflow.com/questions/28395/passing-post-values-with-curl#28411) for POSTing the usual parameter/value format to a url. I recently ran into a situation where I needed to POST some XML as Content-Type "text/xml" without any parameter pairs so here's how you do that: ``` $xml = '...
Passing $_POST values with cURL
[ "", "php", "post", "curl", "" ]
In my ASP.NET User Control I'm adding some JavaScript to the `window.onload` event: ``` if (!Page.ClientScript.IsStartupScriptRegistered(this.GetType(), onloadScriptName)) Page.ClientScript.RegisterStartupScript(this.GetType(), onloadScriptName, "window.onload = function() {myFunction();};", true); ``` My prob...
Most of the "solutions" suggested are Microsoft-specific, or require bloated libraries. Here's one good way. This works with W3C-compliant browsers and with Microsoft IE. ``` if (window.addEventListener) // W3C standard { window.addEventListener('load', myFunction, false); // NB **not** 'onload' } else if (window.a...
There still is an ugly solution (which is far inferior to using a framework or `addEventListener`/`attachEvent`) that is to save the current `onload` event: ``` function addOnLoad(fn) { var old = window.onload; window.onload = function() { old(); fn(); }; } addOnLoad(function() { // your...
Add multiple window.onload events
[ "", "javascript", "asp.net", "events", "listener", "" ]
I have two applications written in Java that communicate with each other using XML messages over the network. I'm using a SAX parser at the receiving end to get the data back out of the messages. One of the requirements is to embed binary data in an XML message, but SAX doesn't like this. Does anyone know how to do thi...
You could encode the binary data using base64 and put it into a Base64 element; the below article is a pretty good one on the subject. [Handling Binary Data in XML Documents](http://www.xml.com/pub/a/98/07/binary/binary.html)
XML is so versatile... ``` <DATA> <BINARY> <BIT index="0">0</BIT> <BIT index="1">0</BIT> <BIT index="2">1</BIT> ... <BIT index="n">1</BIT> </BINARY> </DATA> ``` XML is like violence - If it doesn't solve your problem, you're not using enough of it. EDIT: BTW: Base64 + CDATA is probably the b...
How do you embed binary data in XML?
[ "", "java", "xml", "binary", "binary-data", "" ]
In C#, `int` and `Int32` are the same thing, but I've read a number of times that `int` is preferred over `Int32` with no reason given. Is there a reason, and should I care?
[ECMA-334](https://www.ecma-international.org/publications/standards/Ecma-334.htm):2006 *C# Language Specification* (p18): > Each of the predefined types is shorthand for a system-provided type. For example, the keyword `int` refers to the struct `System.Int32`. As a matter of style, use of the keyword is favoured ove...
The two are indeed synonymous; `int` will be a little more familiar looking, `Int32` makes the 32-bitness more explicit to those reading your code. I would be inclined to use `int` where I just need 'an integer', `Int32` where the size is important (cryptographic code, structures) so future maintainers will know it's s...
Should I use int or Int32
[ "", "c#", "variable-types", "" ]
Does anyone have a technique for generating SQL table create (and data insert) commands pragmatically from a CSV (or sheet in a .xls) file? I've got a third party database system which I'd like to populate with data from a csv file (or sheet in a xls file) but the importer supplied can't create the table structure aut...
In SQL server it is as easy as ``` SELECT * INTO NewTablenNmeHere FROM OPENROWSET( 'Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=C:\testing.xls','SELECT * FROM [Sheet1$]') ```
``` BULK INSERT CSVTest FROM 'c:\csvtest.txt' WITH ( FIELDTERMINATOR = ',', ROWTERMINATOR = '\n' ) ```
CSV (or sheet in XLS) to SQL create (and insert) statements with .Net?
[ "", ".net", "sql", "csv", "xls", "" ]
I'd like to make a debug logging function with the same parameters as `printf`. But one that can be removed by the pre-processor during optimized builds. For example: ``` Debug_Print("Warning: value %d > 3!\n", value); ``` I've looked at variadic macros but those aren't available on all platforms. `gcc` supports the...
I still do it the old way, by defining a macro (XTRACE, below) which correlates to either a no-op or a function call with a variable argument list. Internally, call vsnprintf so you can keep the printf syntax: ``` #include <stdio.h> void XTrace0(LPCTSTR lpszText) { ::OutputDebugString(lpszText); } void XTrace(LPC...
This is how I do debug print outs in C++. Define 'dout' (debug out) like this: ``` #ifdef DEBUG #define dout cout #else #define dout 0 && cout #endif ``` In the code I use 'dout' just like 'cout'. ``` dout << "in foobar with x= " << x << " and y= " << y << '\n'; ``` If the preprocessor replaces 'dout' with '0 && co...
How do you create a debug only function that takes a variable argument list? Like printf()
[ "", "c++", "c", "c-preprocessor", "" ]
I would like to find out safe ways of implementing three dimensional arrays of integers in C++, using pointer arithmetic / dynamic memory allocation, or, alternatively using `STL` techniques such as vectors. Essentially I want my integer array dimensions to look like: ``` [ x ][ y ][ z ] ``` x and y are in the range...
Have a look at the Boost [multi-dimensional array](http://www.boost.org/doc/libs/release/libs/multi_array) library. Here's an example (adapted from the Boost documentation): ``` #include "boost/multi_array.hpp" int main() { // Create a 3D array that is 20 x 30 x 4 int x = 20; int y = 30; int z = 4; typedef...
Each pair of square brackets is a dereferencing operation (when applied to a pointer). As an example, the following pairs of lines of code are equivalent: ``` x = myArray[4]; x = *(myArray+4); ``` ``` x = myArray[2][7]; x = *((*(myArray+2))+7); ``` To use your suggested syntax you are simply dereferencing the value ...
Three dimensional arrays of integers in C++
[ "", "c++", "arrays", "multidimensional-array", "" ]
I've got a bunch of FoxPro (VFP9) DBF files on my Ubuntu system, is there a library to open these in Python? I only need to read them, and would preferably have access to the memo fields too. **Update**: Thanks @cnu, I used Yusdi Santoso's [`dbf.py`](http://www.physics.ox.ac.uk/users/santoso/dbf.py.src) and it works n...
You can try this [recipe on Active State](http://code.activestate.com/recipes/362715/). There is also a [DBFReader module](http://code.google.com/p/lino/source/browse/lino/utils/dbfreader.py) which you can try. For support for [memo fields](http://www.physics.ox.ac.uk/users/santoso/dbf.py.src).
I prefer [dbfpy](http://sourceforge.net/projects/dbfpy/). It supports both reading and writing of `.DBF` files and can cope with most variations of the format. It's the only implementation I have found that could both read and write the legacy DBF files of some older systems I have worked with.
What's the easiest way to read a FoxPro DBF file from Python?
[ "", "python", "foxpro", "dbf", "visual-foxpro", "" ]
Is it possible to actually make use of placement new in portable code when using it for arrays? It appears that the pointer you get back from new[] is not always the same as the address you pass in (5.3.4, note 12 in the standard seems to confirm that this is correct), but I don't see how you can allocate a buffer for...
Personally I'd go with the option of not using placement new on the array and instead use placement new on each item in the array individually. For example: ``` int main(int argc, char* argv[]) { const int NUMELEMENTS=20; char *pBuffer = new char[NUMELEMENTS*sizeof(A)]; A *pA = (A*)pBuffer; for(int i = 0; i ...
@Derek 5.3.4, section 12 talks about the array allocation overhead and, unless I'm misreading it, it seems to suggest to me that it is valid for the compiler to add it on placement new as well: > This overhead may be applied in all array new-expressions, including those referencing the library function operator new[]...
Can placement new for arrays be used in a portable way?
[ "", "c++", "arrays", "compiler-construction", "portability", "overhead", "" ]
What is the easiest way to compare strings in Python, ignoring case? Of course one can do (str1.lower() <= str2.lower()), etc., but this created two additional temporary strings (with the obvious alloc/g-c overheads). I guess I'm looking for an equivalent to C's stricmp(). [Some more context requested, so I'll demon...
In response to your clarification... You could use [ctypes](http://docs.python.org/lib/ctypes-ctypes-tutorial.html) to execute the c function "strcasecmp". Ctypes is included in Python 2.5. It provides the ability to call out to dll and shared libraries such as libc. Here is a quick example (Python on Linux; see link ...
Here is a benchmark showing that using [`str.lower`](http://docs.python.org/2/library/string.html?highlight=lower#string.lower) is faster than the accepted answer's proposed method (`libc.strcasecmp`): ``` #!/usr/bin/env python2.7 import random import timeit from ctypes import * libc = CDLL('libc.dylib') # change to ...
Ignore case in Python strings
[ "", "python", "string", "case-insensitive", "" ]
I've got a JavaScript "object", built this way: ``` function foo() { this.length = 0; } foo.prototype.getLength = function() { return this.length; } ... ``` I know how to emulate namespaces with singleton JavaScript objects, but what is the best way to "namepace" an object such as that above that will intan...
Simple: ``` if(!MyNamespace) MyNamespace = {}; MyNamespace.foo = function() { this.length = 0; }; MyNamespace.foo.prototype.getLength = function() { return this.length; }; ```
Javascript doesn't really have namespace or packages like other languages. Instead it has closures. If you have an application that consists of multiple functions, variables and objects, then you should put them inside a single global object. This will have the same effect as a namespace. For example: ``` var namespa...
How to provide namespaces in JavaScript with instanced objects
[ "", "javascript", "namespaces", "" ]
I'm looking for a way to poll different servers and check that SQL server is up and running. I'm writing my code in C#. I don't particularly care about individual databases, just that SQL server is running and responsive. Any ideas?
Well, the brute force solution is to attempt to initiate a connection with the database on each server. That will tell you whether it's running, though you could have timeout issues. The more elegant (but more difficult... isn't that always the way?) solution would be to use WMI to connect to the remote machine and fi...
`System.Data.Sql.SqlDataSourceEnumerator` will return all instances of SQL Server currently running. [MSDN Link](http://msdn.microsoft.com/en-us/library/system.data.sql.sqldatasourceenumerator.aspx)
Detecting if SQL server is running
[ "", "c#", "sql-server", "" ]
I'm using `int` as an example, but this applies to any value type in .Net In .Net 1 the following would throw a compiler exception: ``` int i = SomeFunctionThatReturnsInt(); if( i == null ) //compiler exception here ``` Now (in .Net 2 or 3.5) that exception has gone. I know why this is: ``` int? j = null; //nulla...
I don't think this is a compiler problem *per se*; an integer value is never null, but the idea of equating them isn't invalid; it's a valid function that always returns false. And the compiler knows; the code ``` bool oneIsNull = 1 == null; ``` compiles, but gives a compiler warning: `The result of the expression is...
Odd ... compiling this with VS2008, targetting .NET 3.5: ``` static int F() { return 42; } static void Main(string[] args) { int i = F(); if (i == null) { } } ``` I get a compiler warning ``` warning CS0472: The result of the expression is always 'false' since a value of type 'int' is never equ...
.Net 2+: why does if( 1 == null ) no longer throw a compiler exception?
[ "", "c#", ".net-3.5", "compiler-construction", ".net-2.0", "" ]
I'm considering dumping boost as a dependency... atm the only thing that I really need is `shared_ptr<>`, and I can get that from `std::tr1`, available in gcc suite 4.\*
AFAIK, all of the distros package V 4.+ nowadays.
These days, I believe most Linux distros do not ship with the development system by default. But I'm pretty sure g++ v4 is the 'standard' development C++ compiler if you install the C++ development environment at all. g++ v3 is usually just available as a special install. For openSUSE 11, gcc 4.3 is the current package...
Does every Linux distro ship with gcc/g++ 4.* these days?
[ "", "c++", "linux", "gcc", "distro", "" ]
Using C#, I need a class called `User` that has a username, password, active flag, first name, last name, full name, etc. There should be methods to *authenticate* and *save* a user. Do I just write a test for the methods? And do I even need to worry about testing the properties since they are .Net's getter and setter...
Many great responses to this are also on my question: "[Beginning TDD - Challenges? Solutions? Recommendations?](https://stackoverflow.com/questions/24965/beginning-tdd-challenges-solutions-recommendations)" May I also recommend taking a look at my [blog post](http://cantgrokwontgrok.blogspot.com/2008/09/tdd-getting-s...
Test your code, not the language. A unit test like: ``` Integer i = new Integer(7); assert (i.instanceOf(integer)); ``` is only useful if you are writing a compiler and there is a non-zero chance that your `instanceof` method is not working. Don't test stuff that you can rely on the language to enforce. In your cas...
How do you know what to test when writing unit tests?
[ "", "c#", "unit-testing", "tdd", "" ]
I am trying to `INSERT INTO` a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the `SQL` engine of the day ([MySQL](http://en.wikipedia.org/wiki/MySQL), [Oracle](http://en.wikipedia.org/wiki/Oracle_Datab...
Try: ``` INSERT INTO table1 ( column1 ) SELECT col1 FROM table2 ``` This is standard ANSI SQL and should work on any DBMS It definitely works for: * Oracle * MS SQL Server * MySQL * Postgres * SQLite v3 * Teradata * DB2 * Sybase * Vertica * HSQLDB * H2 * AWS RedShift * SAP HANA * Google Spanner
[Claude Houle's answer](https://stackoverflow.com/a/25971/282110): should work fine, and you can also have multiple columns and other data as well: ``` INSERT INTO table1 ( column1, column2, someInt, someVarChar ) SELECT table2.column1, table2.column2, 8, 'some string etc.' FROM table2 WHERE table2.ID = 7; ``` ...
Insert into ... values ( SELECT ... FROM ... )
[ "", "sql", "database", "syntax", "database-agnostic", "ansi-sql-92", "" ]
I want to copy a file from A to B in C#. How do I do that?
The `File.Copy(path, destination)` method: [MSDN Link](http://msdn.microsoft.com/en-us/library/system.io.file.copy.aspx)
Without any error handling code: ``` File.Copy(path, path2); ```
How to copy a file in C#
[ "", "c#", ".net", "file", "" ]
What's the simplest-to-use techonlogy available to save an arbitrary Java object graph as an XML file (and to be able to rehydrate the objects later)?
The easiest way here is to serialize the object graph. Java 1.4 has built in support for serialization as XML. A solution I have used successfully is XStream (<http://x-stream.github.io/)-> it's a small library that will easily allow you to serialize and deserialize to and from XML. The downside is you can only very ...
Apache digester is fairly easy: <http://commons.apache.org/digester/> JAXB is newer and comes with annotation goodness: <https://jaxb.dev.java.net>
Saving Java Object Graphs as XML file
[ "", "java", "xml", "" ]
The RFC for a Java class is set of all methods that can be invoked in response to a message to an object of the class or by some method in the class. RFC = M + R where M = Number of methods in the class. R = Total number of other methods directly invoked from the M. Thinking C is the .class and J is the .java file of ...
You could use the [Byte Code Engineering Library](http://jakarta.apache.org/bcel/index.html) with binaries. You can use a [DescendingVisitor](http://jakarta.apache.org/bcel/apidocs/org/apache/bcel/classfile/DescendingVisitor.html) to visit a class' members and references. I've used it to [find class dependencies](http:...
You should find your answer in the [Java language specification](http://java.sun.com/docs/books/jls/third_edition/html/j3TOC.html). You have forgot static method call, method call inside parameters...
Algorithm to perform RFC calculation in Java
[ "", "java", "regex", "algorithm", "reflection", "" ]
I'm trying to install [Laconica](http://laconi.ca/), an open-source Microblogging application on my Windows development server using XAMPP as per the [instructions provided](http://laconi.ca/trac/wiki/InstallationWindows). The website cannot find PEAR, and throws the below errors: > Warning: require\_once(PEAR.php) [...
You need to fix your `include_path` system variable to point to the correct location. To fix it edit the `php.ini` file. In that file you will find a line that says, "`include_path = ...`". (You can find out what the location of php.ini by running `phpinfo()` on a page.) Fix the part of the line that says, "`\xampplit...
If you are using the portable XAMPP installation and Windows 7, and, like me have the version after they removed the XAMPP shell from the control panel none of the suggested answers here will do you much good as the packages will not install. The problem is with the config file. I found the correct settings after a lo...
Getting PEAR to work on XAMPP (Apache/MySQL stack on Windows)
[ "", "php", "pear", "laconica", "" ]
What is the best way to manage a list of windows (keeping them in order) to be able to promote the next window to the top-level when the current top-level window is closed. This is for a web application, so we're using jQuery Javascript. We'd talked through a few simplistic solutions, such as using an array and just...
A stack if you want to just close the window on top. A queue if you also need to open windows at the end.
I don't really know javascript, but couldn't you create a stack of windows?
Best way to keep an ordered list of windows (from most-recently created to oldest)?
[ "", "javascript", "" ]