Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Is there a C# equivalent for the VB.NET `FormatNumber` function? I.e.: ``` JSArrayString += "^" + (String)FormatNumber(inv.RRP * oCountry.ExchangeRate, 2); ```
In both C# and VB.NET you can use either the [.ToString()](http://www.java2s.com/Code/CSharp/Development-Class/UseToStringtoformatvalues.htm) function or the [String.Format()](http://www.java2s.com/Code/CSharp/Development-Class/UseStringFormattoformatavalue.htm) method to format the text. Using the .ToString() method ...
Yes, the .ToString(string) methods. For instance, ``` int number = 32; string formatted = number.ToString("D4"); Console.WriteLine(formatted); // Shows 0032 ``` Note that in C# you don't use a number to specify a format, but you use a character or a sequence of characters. Formatting numbers and dates in C# takes som...
VB.NET FormatNumber equivalent in C#?
[ "", "c#", ".net", "vb.net", "" ]
What modes are the best? And any tips or tricks that make developing java in emacs a bit better.
For anything else than casual Java editing, many people recommend the [Java Development Environment for Emacs.](http://jdee.sourceforge.net/)
[Eclim](http://eclim.org/) is a project that uses eclipse running in headless mode to provide features to Emacs such as in-line error checking, auto import management, basic refactoring, etc. It's much easier than JDEE to set up and when paired with something like YASnippet I find myself more productive than I was in E...
What is the best way to do Java development in Emacs?
[ "", "java", "emacs", "" ]
I want to implement a two-pass cache system: * The first pass generates a PHP file, with all of the common stuff (e.g. news items), hardcoded. The database then has a cache table to link these with the pages (eg "index.php page=1 style=default"), the database also stores an uptodate field, which if false causes the fi...
I second Ken's rec of PEAR's [Cache\_Lite](http://pear.php.net/package/Cache_Lite) library, you can use it to easily cache either parts of pages or entire pages. If you're running your own server(s), I'd strongly recommend [memcached](http://www.danga.com/memcached/) instead. It's much faster since it runs entirely in...
I recommend to don't reinvent the wheel... there are some template engines that support caching, like [Smarty](http://www.smarty.net/)
Creating a two-pass PHP cache system with mutable items
[ "", "php", "caching", "" ]
Everyone I talk to who knows (knew) about it claims it was the greatest thing since sliced bread. Why did it fail? Or, if it didn't fail, who's using it now?
Check out [GigaSpaces](http://www.gigaspaces.com). It's a quite successful Jini/Javaspaces implementation. I think Jini has a great model, but it is stuck with Java. Web-services is more appealing because it works with standarized protocols, even though Jini service discovery is more natural.
Things have definitely quited down for the idea. Which is strange since you'd think its goals are even more relevant now. <http://www.jini.org/wiki/Category:News>
Is JINI at all active anymore?
[ "", "java", "jini", "" ]
I have a handful of projects that all use one project for the data model. Each of these projects has its own applicationContext.xml file with a bunch of repetitive data stuff within it. I'd like to have a modelContext.xml file and another for my ui.xml, etc. Can I do this?
From the [Spring Docs (v 2.5.5 Section 3.2.2.1.)](http://static.springframework.org/spring/docs/2.5.5/reference/beans.html#beans-definition): > It can often be useful to split up > container definitions into multiple > XML files. One way to then load an > application context which is > configured from all these XML > ...
We do this in our projects at work, using the classpath\* resource loader in Spring. For a certain app, all appcontext files containing the application id will be loaded: ``` classpath*:springconfig/spring-appname-*.xml ```
Can I compose a Spring Configuration File from smaller ones?
[ "", "java", "spring", "" ]
I'm just wondering if there can be a case where the hostname can be successfully resolved but the returned hostEntry.AddressList is empty. Currently I'm doing something like this: ``` IPHostEntry hostEntry = Dns.GetHostEntry("some.hostname.tld"); if (hostEntry.AddressList.Count() < 1) { // can that ever happen? t...
No, you'll not see an empty address list: even if you query a DNS label that does exist, but has no A or AAAA (IPv6) records, a SocketException ("No Such Host is Known") will be thrown. You can verify this by looking at the function `InternalGetHostByName(string hostName, bool includeIPv6)` in DNS.cs from the .NET Ref...
Just for the records. Thanks to mdb's [accepted answer](https://stackoverflow.com/questions/156585/can-dnsgethostentry-ever-return-an-iphostentry-with-an-empty-addresslist#156638) I took a look at the [description of the WSANO\_DATA error](http://msdn.microsoft.com/en-us/library/ms740668(VS.85).aspx): > The requested...
Can Dns.GetHostEntry ever return an IPHostEntry with an empty AddressList?
[ "", "c#", "dns", "" ]
We are using fmt:setBundle to load a resource bundle from a database (we extended the ResourceBundle class to do that). When we modify a value in database, we have to reload the web server to display the new value on the web app. Is there any simple way to use the new value without restarting the web server ? (We do ...
As others have pointed out in the comments, you might want to look into Spring - particularly the [ReloadableResourceBundleMessageSource](http://static.springframework.org/spring/docs/2.5.x/api/org/springframework/context/support/ReloadableResourceBundleMessageSource.html).
If you're using JDK 1.6 you can use the callback methods `getTimeToLive()` and `needsReload()` in [ResourceBundle.Control](http://java.sun.com/javase/6/docs/api/java/util/ResourceBundle.Control.html) to control if the bundle cache needs to be loaded with new values from the database.
In Java, how to reload dynamically resources bundles in a web application?
[ "", "java", "resources", "resourcebundle", "" ]
I received the following exception when I was using the Regex class with the regular expression: (?'named a'asdf) ``` System.ArgumentException: parsing \"(?'named a'asdf)\" - Invalid group name: Group names must begin with a word character. ``` What is the problem with my regular expression?
The problem is the space in the name of the capture. Remove the space and it works fine. From the MSDN documentation: "The string used for name must not contain any punctuation and cannot begin with a number. You can use single quotes instead of angle brackets; for example, (?'name')." It does not matter if you use a...
The reference for the MSDN documentation mentioned by vengafoo is here: [Regular Expression Grouping Constructs](http://msdn.microsoft.com/en-us/library/bs2twtah.aspx) > **`(?<name> subexpression)`** > Captures the matched subexpression into a group name or number name. The string used > for name must not contain an...
Invalid group name: Group names must begin with a word character
[ "", "c#", "regex", "exception", "" ]
I see `__all__` in `__init__.py` files. What does it do?
It's a list of public objects of that module, as interpreted by `import *`. It overrides the default of hiding everything that begins with an underscore.
Linked to, but not explicitly mentioned here, is exactly when `__all__` is used. It is a list of strings defining what symbols in a module will be exported when `from <module> import *` is used on the module. For example, the following code in a `foo.py` explicitly exports the symbols `bar` and `baz`: ``` __all__ = [...
What does __all__ mean in Python?
[ "", "python", "syntax", "namespaces", "" ]
I'm looking for a way to do query auto-completion/suggestions in Lucene. I've Googled around a bit and played around a bit, but all of the examples I've seen seem to be setting up filters in Solr. We don't use Solr and aren't planning to move to using Solr in the near future, and Solr is obviously just wrapping around ...
Based on @Alexandre Victoor's answer, I wrote a little class based on the Lucene Spellchecker in the contrib package (and using the LuceneDictionary included in it) that does exactly what I want. This allows re-indexing from a single source index with a single field, and provides suggestions for terms. Results are sor...
Here's a transliteration of Mat's implementation into C# for Lucene.NET, along with a snippet for wiring a text box using jQuery's autocomplete feature. ``` <input id="search-input" name="query" placeholder="Search database." type="text" /> ``` ... JQuery Autocomplete: ``` // don't navigate away from the field when ...
How to do query auto-completion/suggestions in Lucene?
[ "", "java", "autocomplete", "lucene", "" ]
As a temporary quick fix to mitigate the major risk while working on the permanent fix for XSS Vulnerability in a very large code base, I'm looking for a pre-existing XSS prevention blacklist that does a reasonable job of protecting against XSS. Preferably a set of Regular Expressions. I'm aware of plenty of cheat she...
I realise this may not be a direct answer to your question, but ASP.NET developers in a similar situation may find this useful: [Microsoft Anti-Cross Site Scripting Library V1.5](http://www.microsoft.com/downloads/details.aspx?FamilyId=EFB9C819-53FF-4F82-BFAF-E11625130C25&displaylang=en) > This library differs from m...
Here is one: <http://ha.ckers.org/xss.html> but i don't know if it's complete. CAL9000 is another list where you could find something like that.
XSS Blacklist - Is anyone aware of a reasonable one?
[ "", "javascript", "html", "security", "xss", "" ]
I am building a table using the DataGridView where a user can select items from a dropdown in each cell. To simplify the problem, lets say i have 1 column. I am using the DataGridViewComboBoxColumn in the designer. I am trying to support having each row in that column have a different list of items to choose from. Is ...
Yes. This can be done using the DataGridViewComboBoxCell. Here is an example method to add the items to just one cell, rather than the whole column. ``` private void setCellComboBoxItems(DataGridView dataGrid, int rowIndex, int colIndex, object[] itemsToAdd) { DataGridViewComboBoxCell dgvcbc = (DataGridViewComboB...
``` private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex == DataGridViewComboBoxColumnNumber) { setCellComboBoxItems(myDataGridView, e.RowIndex, e.ColumnIndex, someObj); } } ```
DataGridViewComboBoxColumn adding different items to each row .
[ "", "c#", "winforms", "datagridview", "" ]
How can I set the background color of a specific item in a *System.Windows.Forms.ListBox*? I would like to be able to set multiple ones if possible.
Probably the only way to accomplish that is to draw the items yourself. Set the `DrawMode` to `OwnerDrawFixed` and code something like this on the DrawItem event: ``` private void listBox_DrawItem(object sender, DrawItemEventArgs e) { e.DrawBackground(); Graphics g = e.Graphics; g.FillRectangle(new Solid...
Thanks for the [answer by Grad van Horck](https://stackoverflow.com/a/91758/447356). It guided me in the correct direction. To support text (not just background color), here is my fully working code: ``` //global brushes with ordinary/selected colors private SolidBrush reportsForegroundBrushSelected = new SolidBrush(...
Background color of a ListBox item (Windows Forms)
[ "", "c#", "winforms", "listbox", "colors", "" ]
I have inherited a project that uses LLBLGen Pro for the DB layer. The DB model requires that when a entry is deleted a flag (DeletedDate is set to the current time). The last programmer ignored this requirement and has used regular deletes throughout the entire application. Is there a way to set the code generator to...
I implemented this in SQL Server 2005 using INSTEAD OF triggers on delete for any soft delete table. The triggers set the delete flag and perform clean-up. The beauty of this solution is that it correctly handles deletes issued by any system that accesses the database. INSTEAD OF is relatively new in SQL Server, I know...
You could create custom task in LLBLGen that would override those for you when you are generating entities. Check out their template studio and template examples on the website.
LLBLGen: How can I softdelete a entry
[ "", "c#", "llblgenpro", "" ]
Say for instance I was writing a function that was designed to accept multiple argument types: ``` var overloaded = function (arg) { if (is_dom_element(arg)) { // Code for DOM Element argument... } }; ``` What's the best way to implement **`is_dom_element`** so that it works in a cross-browser, fairly...
jQuery checks the nodeType property. So you would have: ``` var overloaded = function (arg) { if (arg.nodeType) { // Code for DOM Element argument... } }; ``` Although this would detect all DOM objects, not just elements. If you want elements alone, that would be: ``` var overloaded = function (arg) ...
Probably this one here: ``` node instanceof HTMLElement ``` That should work in most browsers. Otherwise you have to duck-type it (eg. `typeof x.nodeType != 'undefined'`)
What's the best way to detect if a given Javascript object is a DOM Element?
[ "", "javascript", "dom", "cross-browser", "" ]
In other words, is it correct to use: ``` public class CustomerList : System.Collections.Generic.List<Customer> { /// supposed to be empty } ``` instead of: ``` using CustomerList = System.Collections.Generic.List<Customer> ``` I'd rather use the first approach because I'd just define CustomerList once, and eve...
Don't do it. When people read: ``` List<Customer> ``` they immediately understand it. When they read: ``` CustomerList ``` they have to go and figure out what a CustomerList is, and that makes your code harder to read. Unless you are the only one working on your codebase, writing readable code is a good idea.
well, unless you are adding some functionality to the base class there is no point in creating a wrapper object. I would go with number two if you really need to, but why not just create a variable? ``` List<Customer> customerList = new List<Customer>(); ```
Is it correct to use inheritance instead of name aliasing in c#?
[ "", "c#", "inheritance", "alias", "typedef", "" ]
I am wanting to find the distance between two different points. This I know can be accomplished with the great circle distance. <http://www.meridianworlddata.com/Distance-calculation.asp> Once done, with a point and distance I would like to find the point that distance north, and that distance east in order to create ...
We've had some success using [OpenMap](http://openmap-java.org/) to plot a lot of positional data. There's a [LatLonPoint](http://openmap-java.org/api/com/bbn/openmap/proj/coords/LatLonPoint.html) class that has some basic functionality, including distance.
Here is a Java implementation of [Haversine](http://en.wikipedia.org/wiki/Haversine_formula) formula. I use this in a project to calculate distance in miles between lat/longs. ``` public static double distFrom(double lat1, double lng1, double lat2, double lng2) { double earthRadius = 3958.75; // miles (or 6371.0 k...
How can I measure distance and create a bounding box based on two latitude+longitude points in Java?
[ "", "java", "geocoding", "latitude-longitude", "" ]
I am running some queries to track down a problem with our backup logs and would like to display datetime fields in 24-hour military time. Is there a simple way to do this? I've tried googling and could find nothing.
``` select to_char(sysdate,'DD/MM/YYYY HH24:MI:SS') from dual; ``` Give the time in 24 hour format. More options are described [here](http://www.oradev.com/oracle_date_format.jsp).
If you want all queries in your session to show the full datetime, then do ``` alter session set NLS_DATE_FORMAT='DD/MM/YYYY HH24:MI:SS' ``` at the start of your session.
How can I get Datetime to display in military time in oracle?
[ "", "sql", "oracle", "" ]
How can I discover any USB storage devices and/or CD/DVD writers available at a given time (using C# .Net2.0). I would like to present users with a choice of devices onto which a file can be stored for physically removal - i.e. not the hard drive.
``` using System.IO; DriveInfo[] allDrives = DriveInfo.GetDrives(); foreach (DriveInfo d in allDrives) { if (d.IsReady && d.DriveType == DriveType.Removable) { // This is the drive you want... } } ``` The DriveInfo class documentation is here: <http://msdn.microsoft.com/en-us/library/system.io.driveinfo.as...
this is VB.NET code to check for any removable drives or CDRom drives attached to the computer: ``` Me.lstDrives.Items.Clear() For Each item As DriveInfo In My.Computer.FileSystem.Drives If item.DriveType = DriveType.Removable Or item.DriveType = DriveType.CDRom Then Me.lstDrives.Items.Add(item.Name) E...
How to discover USB storage devices and writable CD/DVD drives (C#)
[ "", "c#", ".net-2.0", "" ]
I am looking for an open-source project involving c++ GUI(s) working with a database. I have not done it before, and am looking for a way to get my feet wet. Which can I work on?
How about this one <http://sourceforge.net/projects/sqlitebrowser/>: > SQLite Database browser is a light GUI editor for SQLite databases, built on top of QT. The main goal of the project is to allow non-technical users to create, modify and edit SQLite databases using a set of wizards and a spreadsheet-like interface...
Do a project you can get **involved** in and passionate about. Hopefully a product you use every day.
Which open-source C++ database GUI project should I help with?
[ "", "c++", "database", "qt", "open-source", "qt4", "" ]
How can I specify the filename when dumping data into the response stream? Right now I'm doing the following: ``` byte[] data= GetFoo(); Response.Clear(); Response.Buffer = true; Response.ContentType = "application/pdf"; Response.BinaryWrite(data); Response.End(); ``` With the code above, I get "foo.aspx...
Add a content-disposition to the header: ``` Response.AddHeader("content-disposition", @"attachment;filename=""MyFile.pdf"""); ```
FYI... if you use "inline" instead of "attachment" the file will open automatically in IE. Instead of prompting the user with a Open/Save dialogue. ``` Response.AppendHeader("content-disposition", string.Format("inline;FileName=\"{0}\"", fileName)); ```
Specifying filename for dynamic PDF in asp.net
[ "", "c#", "asp.net", "response", "" ]
Is it a good idea for me to use Qt Jambi in Java as a toolkit? I see that Qt Jambi is hard to learn, and Swing is easier than Qt Jambi, but I think that Qt Jambi is more powerful.
Two years ago, I started a Java Desktop Application and used Swing as a GUI framweork. Up to that point, I had experience with C++/MFC (*shudder*) and C++/Qt (*very nice*). After trying to get along with Swing for a while (including reading lots of tutorials and even a book) I came to the following conclusion: **Swin...
If you think being familiar with Qt would be useful in the future, when you might want to develop in C++ (or change some Qt-based software), I think it would be nice.
Should I use Qt Jambi in Java?
[ "", "java", "user-interface", "qt", "qt-jambi", "" ]
How do I initialize an automatic download of a file in Internet Explorer? For example, in the download page, I want the download link to appear and a message: "If you download doesn't start automatically .... etc". The download should begin shortly after the page loads. In Firefox this is easy, you just need to inclu...
[SourceForge](http://en.wikipedia.org/wiki/SourceForge) uses an `<iframe>` element with the `src=""` attribute pointing to the file to download. ``` <iframe width="1" height="1" frameborder="0" src="[File location]"></iframe> ``` (Side effect: no redirect, no JavaScript, original URL remains unchanged.)
I *hate* when sites complicate download so much and [use hacks instead of a good old link](http://adactio.com/journal/6022/). ### Dead simple version: ``` <a href="file.zip">Start automatic download!</a> ``` It works! In every browser! --- If you want to download a file that is usually displayed inline (such as an...
How to start automatic download of a file in Internet Explorer?
[ "", "javascript", "html", "internet-explorer", "meta-tags", "" ]
Do you have a common base class for Hibernate entities, i.e. a MappedSuperclass with id, version and other common properties? Are there any drawbacks? Example: ``` @MappedSuperclass() public class BaseEntity { private Long id; private Long version; ... @Id @GeneratedValue(strategy = GenerationType.A...
This works fine for us. As well as the ID and creation date, we also have a modified date. We also have an intermediate *TaggedBaseEntity* that implements a *Taggable* interface, because some of our web application's entities have tags, like questions on Stack Overflow.
The one that I use is primarily to implement hashCode() and equals(). I also added a method to pretty print the entity. In response to DR above, most of this can be overridden, but in my implementation you are stuck with an ID of type Long. ``` public abstract class BaseEntity implements Serializable { public abs...
Do you have a common base class for Hibernate entities?
[ "", "java", "hibernate", "entities", "base-class", "" ]
Once I've created a variable in the immediate window in C# (VS2008), is there any way to delete it so I can create a new variable with the same name but a different type? Apart from restarting the program that is. The reason would be to keep the immediate window's namespace clean, since it's difficult to keep track of...
I don't think it is possible to do what you are asking.
You could make a dictionary to hold your immediate window "variables". Then you can remove items from the dictionary when you're done with them.
Delete variables in immediate window in C#
[ "", "c#", "" ]
I have a function in Python which is iterating over the attributes returned from `dir(obj)`, and I want to check to see if any of the objects contained within is a function, method, built-in function, etc. Normally you could use `callable()` for this, but I don't want to include classes. The best I've come up with so f...
The inspect module has exactly what you want: ``` inspect.isroutine( obj ) ``` FYI, the code is: ``` def isroutine(object): """Return true if the object is any kind of function or method.""" return (isbuiltin(object) or isfunction(object) or ismethod(object) or ismethoddes...
If you want to exclude classes and other random objects that may have a `__call__` method, and only check for functions and methods, these three functions in the [`inspect` module](http://docs.python.org/lib/module-inspect.html) ``` inspect.isfunction(obj) inspect.isbuiltin(obj) inspect.ismethod(obj) ``` should do wh...
Is there a common way to check in Python if an object is any function type?
[ "", "python", "types", "" ]
I currentyl have no clue on how to sort an array which contains UTF-8 encoded strings in PHP. The array comes from a LDAP server so sorting via a database (would be no problem) is no solution. The following does not work on my windows development machine (although I'd think that this should be at least a possible solut...
Eventually this problem cannot be solved in a simple way without using recoded strings (UTF-8 → Windows-1252 or ISO-8859-1) as suggested by ΤΖΩΤΖΙΟΥ due to an obvious PHP bug as discovered by Huppie. To summarize the problem, I created the following code snippet which clearly demonstrates that the problem is the strcol...
``` $a = array( 'Кръстев', 'Делян1', 'делян1', 'Делян2', 'делян3', 'кръстев' ); $col = new \Collator('bg_BG'); $col->asort( $a ); var_dump( $a ); ``` Prints: ``` array 2 => string 'делян1' (length=11) 1 => string 'Делян1' (length=11) 3 => string 'Делян2' (length=11) 4 => string 'делян3' (length=11) 5 => str...
How to sort an array of UTF-8 strings?
[ "", "php", "arrays", "sorting", "utf-8", "" ]
Which browsers other than Firefox support Array.forEach()? [Mozilla say it's an extension to the standard](http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference:Objects:Array:forEach#Compatibility) and I realise it's trivial to add to the array prototype, I'm just wondering what other browsers support it?
The [JavaScript](http://en.wikipedia.org/wiki/JavaScript "JavaScript - Wikipedia, the free encyclopedia") article of Wikipedia lists the JS versions by browser. forEach is [part of JavaScript 1.6](http://developer.mozilla.org/en/New_in_JavaScript_1.6 "New in JavaScript 1.6"). So it is supported indeed by most browsers,...
I just checked this for another question: [JavaScript for...in vs for](https://stackoverflow.com/questions/242841/javascript-foreach-vs-for/6442930#6442930). On kangax's [ECMAScript 5 compatibility table](http://kangax.github.com/es5-compat-table/), Array.forEach gets a 'yes' for all browsers except IE8. As of Septem...
Which web browsers natively support Array.forEach()
[ "", "javascript", "cross-browser", "" ]
In my environment here I use Java to serialize the result set to XML. It happens basically like this: ``` //foreach column of each row xmlHandler.startElement(uri, lname, "column", attributes); String chars = rs.getString(i); xmlHandler.characters(chars.toCharArray(), 0, chars.length()); xmlHandler.endElement(uri, lna...
I found an interesting list in the [Xml Spec](http://www.w3.org/TR/2006/REC-xml11-20060816/#charsets): According to that List its discouraged to use the Character #26 (Hex: *#x1A*). > The characters defined in the > following ranges are also discouraged. > They are either control characters or > permanently undefined ...
[Extensible Markup Language (XML) 1.0](http://www.w3.org/TR/REC-xml/#syntax) says: > The ampersand character (&) and the > left angle bracket (<) must not appear > in their literal form, except when > used as markup delimiters, or within a > comment, a processing instruction, or > a CDATA section. If they are needed >...
How to encode characters from Oracle to XML?
[ "", "java", "xml", "oracle", "encoding", "" ]
If I hit a page which calls `session_start()`, how long would I have to wait before I get a new session ID when I refresh the page?
Check out php.ini the value set for session.gc\_maxlifetime is the ID lifetime in seconds. I believe the default is 1440 seconds (24 mins) <http://www.php.net/manual/en/session.configuration.php> **Edit:** As some comments point out, the above is not entirely accurate. A wonderful explanation of why, and how to impl...
The default in the php.ini for the `session.gc_maxlifetime` directive (the "gc" is for garbage collection) is 1440 seconds or 24 minutes. See the Session Runtime Configuation page in the manual: <http://www.php.net/manual/en/session.configuration.php> You can change this constant in the php.ini or .httpd.conf files i...
What is the default lifetime of a session?
[ "", "php", "session", "" ]
I'm having a problem with my Seam code and I can't seem to figure out what I'm doing wrong. It's doing my head in :) Here's an excerpt of the stack trace: ``` Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Long field com.oobjects.sso.manager.home.PresenceHome.customerId to java.lang.String ``` I...
You want to add a converter to your pages.xml file. Like this: ``` <param name="customerId" value="#{presenceHome.customerId}" converterId="javax.faces.Long" /> ``` See the seampay example provided with seam for more details.
try: ... `<f:param name="customerId" value="#{customerId.toString()}" />` ...
Seam Problem: Could not set field value by reflection
[ "", "java", "seam", "" ]
In a follow-up to a [previous question](https://stackoverflow.com/questions/54789/what-is-the-correct-net-exception-to-throw-when-try-to-insert-a-duplicate-objec) regarding exceptions, what are best practices for creating a custom exception in .NET? More specifically should you inherit from System.Exception, System.Ap...
Inherit from `System.Exception`. `System.ApplicationException` is useless and the design guidelines say "**Do not** throw or derive from `System.ApplicationException`." See <http://blogs.msdn.com/kcwalina/archive/2006/06/23/644822.aspx>
In the C# IDE, type 'exception' and hit TAB. This will expand to get you started in writing a new exception type. There are comments withs links to some discussion of exception practices. Personally, I'm a big fan of creating lots of small classes, at that extends to exception types. For example, in writing the Foo cl...
What are some best practices for creating my own custom exception?
[ "", "c#", ".net", "exception", "" ]
**Is there a better way of binding a list of base class to a UI other than downcasting e.g:** ``` static void Main(string[] args) { List<Animal> list = new List<Animal>(); Pig p = new Pig(5); Dog d = new Dog("/images/dog1.jpg"); list.Add(p); list.Add(d); foreach (Animal a in list) ...
When faced with this type of problem, I follow the [visitor pattern](http://en.wikipedia.org/wiki/Visitor_pattern). ``` interface IVisitor { void DoPigStuff(Piggy p); void DoDogStuff(Doggy d); } class GuiVisitor : IVisitor { void DoPigStuff(Piggy p) { label1.Text = String.Format("The pigs tail is {0}", p....
Why not make Animal include an abstract method that Pig and Dog are forced to implement ``` public class Animal { public abstract void DoStuff(); } public Dog : Animal { public override void DoStuff() { // Do dog specific stuff here } } public Pig : Animal { public override void DoStuff()...
c# downcasting when binding to and interface
[ "", "c#", "casting", "oop", "" ]
I'm not asking this question because of the merits of garbage collection first of all. My main reason for asking this is that I do know that Bjarne Stroustrup has said that C++ will have a garbage collector at some point in time. With that said, why hasn't it been added? There are already some garbage collectors for C...
Implicit garbage collection could have been added in, but it just didn't make the cut. Probably due to not just implementation complications, but also due to people not being able to come to a general consensus fast enough. A quote from Bjarne Stroustrup himself: > I had hoped that a garbage collector > which could b...
To add to the debate here. There are known issues with garbage collection, and understanding them helps understanding why there is none in C++. **1. Performance ?** The first complaint is often about performance, but most people don't really realize what they are talking about. As illustrated by Martin Beckett the p...
Why doesn't C++ have a garbage collector?
[ "", "c++", "garbage-collection", "c++11", "" ]
I've been using the following code to open Office Documents, PDF, etc. on my windows machines using Java and it's working fine, except for some reason when a filename has embedded it within it multiple contiguous spaces like "File[SPACE][SPACE]Test.doc". How can I make this work? I'm not averse to canning the whole pi...
If you are using Java 6 you can just use the [open method of java.awt.Desktop](http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html#open(java.io.File)) to launch the file using the default application for the current platform.
Not sure if this will help you much... I use java 1.5+'s [ProcessBuilder](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html) to launch external shell scripts in a java program. Basically I do the following: ( although this may not apply because you don't want to capture the commands output; you actu...
Better way of opening a Document from Java?
[ "", "java", "windows", "process", "" ]
I'm attempting to display a "LargeIcon" view in a listview control, however the images I specify are blurry. This is what I have so far: [alt text http://img220.imageshack.us/img220/1005/blurryiconsql3.jpg](http://img220.imageshack.us/img220/1005/blurryiconsql3.jpg) The .png files are 48x48 and that's what I have it s...
When adding a .PNG Icon format size the editor tends to pick the first entry size in that file, so it picks up the 16x16 entry and it's stretching that out. That's why you see the 16x16 in the properties there. As suggested, the support for PNG is poor, I'm often found myself rolling over to another format as well to a...
Be sure to set ImageList.ImageSize to 48 x 48 too.
Listview icons show up blurry (C#)
[ "", "c#", "listview", "imagelist", "blurry", "" ]
I have string like this ``` /c SomeText\MoreText "Some Text\More Text\Lol" SomeText ``` I want to tokenize it, however I can't just split on the spaces. I've come up with somewhat ugly parser that works, but I'm wondering if anyone has a more elegant design. This is in C# btw. **EDIT:** My ugly version, while ugly...
The computer term for what you're doing is [lexical analysis](http://en.wikipedia.org/wiki/Lexical_analysis); read that for a good summary of this common task. Based on your example, I'm guessing that you want whitespace to separate your words, but stuff in quotation marks should be treated as a "word" without the quo...
The Microsoft.VisualBasic.FileIO namespace (in Microsoft.VisualBasic.dll) has a TextFieldParser you can use to split on space delimeted text. It handles strings within quotes (i.e., "this is one token" thisistokentwo) well. Note, just because the DLL says VisualBasic doesn't mean you can only use it in a VB project. I...
Best way to parse Space Separated Text
[ "", "c#", "string", "tokenize", "" ]
What is the difference between old style and new style classes in Python? When should I use one or the other?
From *[New-style and classic classes](http://docs.python.org/2/reference/datamodel.html#new-style-and-classic-classes)*: > **Up to Python 2.1, old-style classes were the only flavour available to the user.** > > The concept of (old-style) class is unrelated to the concept of type: > if `x` is an instance of an old-sty...
**Declaration-wise:** New-style classes inherit from *object*, or from another new-style class. ``` class NewStyleClass(object): pass class AnotherNewStyleClass(NewStyleClass): pass ``` Old-style classes don't. ``` class OldStyleClass(): pass ``` **Python 3 Note:** Python 3 doesn't support old style ...
What is the difference between old style and new style classes in Python?
[ "", "python", "class", "oop", "types", "new-style-class", "" ]
Backgrounder: The [PIMPL Idiom](http://en.wikipedia.org/wiki/Opaque_pointer) (Pointer to IMPLementation) is a technique for implementation hiding in which a public class wraps a structure or class that cannot be seen outside the library the public class is part of. This hides internal implementation details and data ...
* Because you want `Purr()` to be able to use private members of `CatImpl`. `Cat::Purr()` would not be allowed such an access without a `friend` declaration. * Because you then don't mix responsibilities: one class implements, one class forwards.
I think most people refer to this as the *Handle Body* idiom. See James Coplien's book *[Advanced C++ Programming Styles and Idioms](https://rads.stackoverflow.com/amzn/click/com/0201548550)*. It's also known as the [Cheshire Cat](http://en.wikipedia.org/wiki/Cheshire_Cat) because of [Lewis Caroll's](https://en.wikiped...
Why should the "PIMPL" idiom be used?
[ "", "c++", "oop", "information-hiding", "pimpl-idiom", "" ]
The workflow is like this: 1. I receive a scan of a coupon with data (firstname, lastname, zip, city + misc information) on it. 2. Before I create a new customer, I have to search the database if the customer might exist already. Now my question: What's the best way to find an existing customer, when there is no uniq...
We are using the [Levenshtein distance](http://en.wikipedia.org/wiki/Levenshtein_distance) algorithm to check users for duplication. However we have quite strict rules to enter the data itself, so we have to check only for misstyping, case differences and such.
See this previous question: [Parse usable Street Address, City, State, Zip from a string](https://stackoverflow.com/questions/16413/parse-usable-street-address-city-state-zip-from-a-string#16444). [Soundex](http://en.wikipedia.org/wiki/Soundex) would help you if you require similiar matches.
How can I find similar address records?
[ "", "sql", "database", "" ]
I'm not sure how I should express this, but I'll give it a try. I recently started coding my portfolio in object-oriented PHP and I'm wondering if it's according to best practices to use a single page where the content changes depending on SQL data and the $\_GET variable? If so/not, why? Edit: Take a look at my n...
Are you asking about using the front controller pattern, where a single file serves all of your requests? Often this is done with an index.php and mod\_rewrite getting all of the requests with the rest of the URL being given to it as a parameter in the query string. <http://www.onlamp.com/pub/a/php/2004/07/08/front_co...
* Not scalable * Hard to manage code * Parser has to parse everything * Perfect example of Code Smell * One error crashes your whole site
Pros and cons of using one file for entire webpage?
[ "", "php", "file", "" ]
I'm using a C# MailMessage to attach a wave file (8K) to an email message. I'd like to provide a player within the body of that email message that will play that wave file if the user chooses to do so. I've tried using the embedded <object> version of WMP, and a cid: reference to the file, but Outlook 2003 rejects the ...
If you know the message recipients are running Outlook (which implies you're using this internally), you might be able to accomplish something even better by incorporating your player controls into a [custom Outlook form](http://www.outlookcode.com/article.aspx?id=35).
If it don't support objects tags, then try the Embed tag instead: <http://www.mioplanet.com/rsc/embed_mediaplayer.htm> I don't know it if works, but it is worth a shot :)
How do I embed Media Player in a C# MailMessage to play an Attachment
[ "", "c#", ".net", "wmp", "embedded-control", "" ]
I've written a simple SessionItem management class to handle all those pesky null checks and insert a default value if none exists. Here is my GetItem method: ``` public static T GetItem<T>(string key, Func<T> defaultValue) { if (HttpContext.Current.Session[key] == null) { HttpContext.Current.Session[k...
Since that is a func, a lambda would be the simplest way: ``` Foo foo = GetItem<Foo>("abc", () => new Foo("blah")); ``` Where [new Foo("blah")] is the func that is invoked as a default. You could also simplify to: ``` return ((T)HttpContext.Current.Session[key]) ?? defaultValue(); ``` Where ?? is the null-coalesci...
Why don't you pass the default value directly? What use is the functor? By the way, `defaultValue.Invoke()` is quite verbose. It's also possible to just write `defaultValue()`.
C# - How do I define an inline method Func<T> as a parameter?
[ "", "c#", "generics", "func", "inline-method", "" ]
Which tools do you use to convert between C# and VB.NET?
This has been asked so many times. Like here: [What is the best C# to VB.net converter?](https://stackoverflow.com/questions/88359/what-is-the-best-c-to-vbnet-converter)
Check out [Code Converter](http://converter.telerik.com/) by Telerik.
C# VB.NET Conversion
[ "", "c#", ".net", "vb.net", "" ]
To create a new event handler on a control you can do this ``` c.Click += new EventHandler(mainFormButton_Click); ``` or this ``` c.Click += mainFormButton_Click; ``` and to remove an event handler you can do this ``` c.Click -= mainFormButton_Click; ``` But how do you remove all event handlers from an event?
I found a solution on the [MSDN forums](http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/576f69e7-55aa-4574-8d31-417422954689/). The sample code below will remove all `Click` events from `button1`. ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); ...
You guys are making this WAY too hard on yourselves. It's this easy: ``` void OnFormClosing(object sender, FormClosingEventArgs e) { foreach(Delegate d in FindClicked.GetInvocationList()) { FindClicked -= (FindClickedHandler)d; } } ```
How to remove all event handlers from an event
[ "", "c#", ".net", "winforms", "events", "" ]
I have a table with say 3 columns. There's no primary key so there can be duplicate rows. I need to just keep one and delete the others. Any idea how to do this is Sql Server?
I'd SELECT DISTINCT the rows and throw them into a temporary table, then drop the source table and copy back the data from the temp. **EDIT:** now with code snippet! ``` INSERT INTO TABLE_2 SELECT DISTINCT * FROM TABLE_1 GO DELETE FROM TABLE_1 GO INSERT INTO TABLE_1 SELECT * FROM TABLE_2 GO ```
The following example works as well when your PK is just a subset of all table columns. (Note: I like the approach with inserting another surrogate id column more. But maybe this solution comes handy as well.) First find the duplicate rows: ``` SELECT col1, col2, count(*) FROM t1 GROUP BY col1, col2 HAVING count(*) ...
How can I delete duplicate rows in a table
[ "", "sql", "sql-server", "database", "" ]
I use a custom Matrix class in my application, and I frequently add multiple matrices: ``` Matrix result = a + b + c + d; // a, b, c and d are also Matrices ``` However, this creates an intermediate matrix for each addition operation. Since this is simple addition, it is possible to avoid the intermediate objects and...
You could limit yourself to a single small intermediate by using lazy evaluation. Something like ``` public class LazyMatrix { public static implicit operator Matrix(LazyMatrix l) { Matrix m = new Matrix(); foreach (Matrix x in l.Pending) { for (int i = 0; i < 2; ++i) ...
In C++ it is possible to use [Template Metaprograms](http://en.wikipedia.org/wiki/Template_metaprogramming) and also [here](http://ubiety.uwaterloo.ca/~tveldhui/papers/Template-Metaprograms/meta-art.html), using templates to do exactly this. However, the template programing is non-trivial. I don't know if a similar tec...
How to prevent creating intermediate objects in cascading operators?
[ "", "c#", ".net", "operators", "" ]
I am searching for a way to compress JavaScript code for the iPhone. Is there a way to avoid using a lot of CPU time on the small and rather slow device?
Use [JSMin](http://www.crockford.com/javascript/jsmin.html) and avoid [packer](http://dean.edwards.name/packer/) which is really more CPU consuming and slower to "deflate"
Use the [YUI Compressor](http://www.julienlecomte.net/yuicompressor/)
What is the best way to pack JavaScript code without getting performance flaws?
[ "", "javascript", "iphone", "compression", "" ]
If I have a Java source file (\*.java) or a class file (\*.class), how can I convert it to a .exe file? I also need an installer for my program.
### [javapackager](https://docs.oracle.com/javase/10/tools/javapackager.htm) > The Java Packager tool compiles, packages, and prepares Java and JavaFX applications for distribution. The javapackager command is the command-line version. > > – Oracle's documentation The `javapackager` utility ships with the JDK. It can...
# [Launch4j](http://launch4j.sourceforge.net/) > Launch4j is a cross-platform tool for wrapping Java applications distributed as jars in lightweight Windows native executables. The executable can be configured to search for a certain JRE version or use a bundled one, and it's possible to set runtime options, like the ...
How can I convert my Java program to an .exe file?
[ "", "java", "installation", "exe", "" ]
In C++ the storage class specifier static allocates memory from the data area. What does "data area" mean?
In addition to what Konrad said, declaring a variable as static basically means that the memory for it gets allocated with the program as it is loaded, as opposed to on the heap or the stack. Historically, using only static variables in a critical applications meant that the memory footprint of the application would no...
I'm not familiar with the term “data area” but memory is often divided into “code section” and “data section”. Code resides in the former, data in the latter. I presume this is what's meant here. Classically, there's no distinction between the two. However, many modern operating systems can prohibit the execution of c...
What is data area?
[ "", "c++", "memory", "static", "storage", "" ]
In a [question answer](https://stackoverflow.com/questions/9033#9099) I find the following coding tip:- 2) simple lambdas with one parameter: ``` x => x.ToString() //simplify so many calls ``` As someone who has not yet used 3.0 I don't really understand this tip but it looks interesting so I would appreciate an exp...
When you need to create an instance of a delegate which has a single parameter, lambda expressions allow you to create that delegate "inline" in a very concise manner. For instance, here's code to find a particular person in a list, by their name: ``` List<Person> list = new List<Person>(); // [..] Populate list here ...
This basically expands to: ``` private string Lambda(object x) { return x.ToString(); } ```
Explain x => x.ToString() //simplify so many calls
[ "", "c#", ".net-3.5", "lambda", "" ]
Is there a way to hide table rows without affecting the overall table width? I've got some javascript that shows/hides some table rows, but when the rows are set to `display: none;`, the table with shrinks to fit the contents of the visible rows.
If you are looking to preserve the overall width of the table, you can check it prior to hiding a row, and explicitly set the width style property to this value: ``` table.style.width = table.clientWidth + "px"; table.rows[3].style.display = "none"; ``` However, this may cause the individual columns to reflow when yo...
CSS rule [`visibility: collapse`](https://developer.mozilla.org/en-US/docs/Web/CSS/visibility#Values) was designed exactly for that. ``` tbody.collapsed > tr { visibility: collapse; } ``` After adding this CSS you could trigger visibility from JS with: ``` tbody.classList.toggle('collapsed'); ```
How to hide table rows without resizing overall width?
[ "", "javascript", "html", "css", "xhtml", "html-table", "" ]
Ok, here's one for the JavaScript gurus: In my app, one of the controllers passes a TreeMap to it's JSP. This map has car manufacturer's names as keys and Lists of Car objects as values. These Car objects are simple beans containing the car's name, id, year of production etc. So, the map looks something like this (thi...
Well anyway, as i said, i finally managed to do it by myself, so here's my answer... I receive the map from my controller like this (I'm using Spring, don't know how this works with other frameworks): ``` <c:set var="manufacturersAndModels" scope="page" value="${MANUFACTURERS_AND_MODELS_MAP}"/> ``` These are my comb...
I just love a challenge. No jQuery, just plain javascript, tested on Safari. I'd like to add the following remarks in advance: * It's faily long due to the error checking. * Two parts are generated; the first script node with the Map and the contents of the manufacterer SELECT * Works on My Machine (TM) (S...
Dynamicaly populating a combobox with values from a Map based on what's selected in another combobox
[ "", "javascript", "combobox", "maps", "" ]
I have several sources of tables with personal data, like this: ``` SOURCE 1 ID, FIRST_NAME, LAST_NAME, FIELD1, ... 1, jhon, gates ... SOURCE 2 ID, FIRST_NAME, LAST_NAME, ANOTHER_FIELD1, ... 1, jon, gate ... SOURCE 3 ID, FIRST_NAME, LAST_NAME, ANOTHER_FIELD1, ... 2, jhon, ballmer ... ``` So, assuming that records w...
The crux of the problem is to compute one or more measures of distance between each pair of entries and then consider them to be the same when one of the distances is less than a certain acceptable threshold. The key is to setup the analysis and then vary the acceptable distance until you reach what you consider to be ...
This sounds like a [Customer Data Integration](http://en.wikipedia.org/wiki/Customer_Data_Integration) problem. Search on that term and you might find some more information. Also, have a poke around inside [The Data Warehousing Institude](http://www.tdwi.org/), and you might find some answers there as well. **Edit:** ...
how to determine if a record in every source, represents the same person
[ "", "sql", "algorithm", "etl", "textmatching", "record-linkage", "" ]
What's the easiest way to print a stacktrace from a debugging printout? Often during testing you would like to know the callstack leading up to the situation provoking a debug message.
[Thread.dumpStack();](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Thread.html#dumpStack())
If you're using log4j ``` Exception e = new Exception(); log.error("error here", e); ``` will print the stacktrace to your log.
How do I in java add a stacktrace to my debugging printout
[ "", "java", "debugging", "" ]
Whats the most efficient way of selecting total number of records from a large table? Currently, Im simply doing ``` $result = mysql_query("SELECT id FROM table"); $total = mysql_num_rows($result) ``` I was told this was not very efficient or fast, if you have a lot of records in the table.
You were told correctly. mysql can do this count for you which is much more efficient. ``` $result = mysql_query( "select count(id) as num_rows from table" ); $row = mysql_fetch_object( $result ); $total = $row->num_rows; ```
You should use [SQL's built in COUNT function](http://dev.mysql.com/doc/refman/5.0/en/counting-rows.html): ``` $result = mysql_query("SELECT COUNT(id) FROM table"); ```
Whats the best way to get total # of records in a mysql table with php?
[ "", "php", "mysql", "" ]
In Java, one can declare a variable parameterised by an "unknown" generic type, which looks like this: ``` Foo<?> x; ``` Is there an equivalent construct to this question-mark, in C#?
The short answer is no. There isn't an equivalent feature in C#. A workaround, from [C# from a Java developer's perspective](http://www.25hoursaday.com/CsharpVsJava.html#generics) by Dare Obasanjo: In certain cases, one may need create a method that can operate on data structures containing any type as opposed to tho...
AFAIK you can not do that in C#. What the BCL does and there are plenties of examples there is to create a class that is not generic and then create a generic class that inherits the base behavior from the previous one. See example below. ``` class Foo { } class Foo<T> : Foo { } ``` The you can write something like ...
Is there an "anonymous" generic tag in C#, like '?' in Java?
[ "", "c#", "generics", "syntax", "" ]
I'm writing a shell for a project of mine, which by design parses commands that looks like this: COMMAND\_NAME ARG1="Long Value" ARG2=123 ARG3=me@me.com My problem is that Python's command line parsing libraries (getopt and optparse) forces me to use '-' or '--' in front of the arguments. This behavior doesn't match ...
You could split them up with shlex.split(), which can handle the quoted values you have, and pretty easily parse this with a very simple regular expression. Or, you can just use regular expressions for both splitting and parsing. Or simply use split(). ``` args = {} for arg in shlex.split(cmdln_args): key, value =...
1. Try to follow "[Standards for Command Line Interfaces](http://www.gnu.org/prep/standards/standards.html#Command_002dLine-Interfaces)" 2. Convert your arguments (as Thomas suggested) to OptionParser format. ``` parser.parse_args(["--"+p if "=" in p else p for p in sys.argv[1:]]) ``` If command-line argumen...
Customized command line parsing in Python
[ "", "python", "parsing", "shell", "command-line", "arguments", "" ]
I have the situation where i use GIS software which stores the information about GIS objects into separate database table for each type/class of GIS object (road, river, building, sea, ...) and keeps the metadata table in which it stores info about the class name and its DB table. Those GIS objects of different classe...
@Brian Chiasson Unfortunately, it's not an option to create all classes of GIS data because classes are created dynamically in the application. Every GIS data of the same type should be a class, but my user has the possibility to get new set of data and put it in the database. I can't know in front which classes my us...
It sounds like the simplest thing to do here may be to create an abstract base class with all of the common GIS members and then to inherit the other X classes that will have nothing more than the necessary NHibernate mappings. I would then use the Factory pattern to create the object of the specific type using your me...
(N)Hibernate - is it possible to dynamically map multiple tables to the one class
[ "", "c#", "nhibernate", "hibernate", "orm", "gis", "" ]
Using C# .NET 2.0, I have a composite data class that does have the `[Serializable]` attribute on it. I am creating an `XMLSerializer` class and passing that into the constructor: ``` XmlSerializer serializer = new XmlSerializer(typeof(DataClass)); ``` I am getting an exception saying: > There was an error reflectin...
Look at the inner exception that you are getting. It will tell you which field/property it is having trouble serializing. You can exclude fields/properties from xml serialization by decorating them with the [`[XmlIgnore]`](https://learn.microsoft.com/en-us/dotnet/api/system.xml.serialization.xmlignoreattribute) attrib...
Remember that serialized classes must have default (i.e. parameterless) constructors. If you have no constructor at all, that's fine; but if you have a constructor with a parameter, you'll need to add the default one too.
XmlSerializer - There was an error reflecting type
[ "", "c#", ".net", "xml", "serialization", ".net-2.0", "" ]
How would retrieve all customer's birthdays for a given month in SQL? What about MySQL? I was thinking of using the following with SQL server. ``` select c.name from cust c where datename(m,c.birthdate) = datename(m,@suppliedDate) order by c.name ```
don't forget the 29th February... ``` SELECT c.name FROM cust c WHERE ( MONTH(c.birthdate) = MONTH(@suppliedDate) AND DAY(c.birthdate) = DAY(@suppliedDate) ) OR ( MONTH(c.birthdate) = 2 AND DAY(c.birthdate) = 29 AND MONTH(@suppliedDate) = 3 AND DAY(@suppliedDate) = 1 AND (YEAR(@suppliedDate) % 4 = ...
If you're asking for all birthdays in a given *month*, then you should supply the *month*, not a *date*: ``` SELECT c.name FROM cust c WHERE datepart(m,c.birthdate) = @SuppliedMonth ```
Monthly Birthday SQL Query
[ "", "sql", "mysql", "" ]
The code currently does this and the fgetpos does handle files larger than 4GB but the seek returns an error, so any idea how to seek to the end of a `file > 4GB`? ``` fpos_t currentpos; sok=fseek(fp,0,SEEK_END); assert(sok==0,"Seek error!"); fgetpos(fp,&currentpos); m_filesize=currentpos; ```
If you're in Windows, you want [GetFileSizeEx (MSDN)](http://msdn.microsoft.com/en-us/library/aa364957(VS.85).aspx). The return value is a 64bit int. On linux [stat64 (manpage)](http://www.manpagez.com/man/2/stat64/) is correct. fstat if you're working with a FILE\*.
Ignore all the answers with "64" appearing in them. On Linux, you should add `-D_FILE_OFFSET_BITS=64` to your CFLAGS and use the `fseeko` and `ftello` functions which take/return `off_t` values instead of `long`. These are not part of C but POSIX. Other (non-Linux) POSIX systems may need different options to ensure tha...
Determining the size of a file larger than 4GB
[ "", "c++", "c", "fseek", "fgetpos", "" ]
I am going to work on a project where a fairly large web app needs to tweaked to handle several languages. The thing runs with a hand crafted PHP code but it's pretty clean. I was wondering what would be the best way to do that? 1. Making something on my own, trying to fit the actual architecture. 2. Rewriting a good...
There are a number of ways of tackling this. None of them "the best way" and all of them with problems in the short term or the long term. The very first thing to say is that multi lingual sites are not easy, translators and lovely people but hard to work with and most programmers see the problem as a technical one onl...
Work with languages files. 1. Replace each text string by a variable 2. Create one language file per language and in it define each variable with their corresponding text. (french.inc, dutch.inc ...) 3. Include the right file in each page. That's for small sites. If getting bigger, replace the files by a DB. :)
How would you transform a pre-existing web app into a multilingual one?
[ "", "php", "symfony", "internationalization", "" ]
How do you trace/profile your .NET applications? The MSDN online help mentions Visual Studio Team (which I do not possess) and there is the Windows Performance Toolkit. But, are there other solutions you can recommend? Preferably (of course) a solution that works without changing the code (manually) and that can be int...
See also [this question](https://stackoverflow.com/questions/49912/best-dotnet-memory-and-performance-profiler). JetBrains dotTrace is the best .NET profiler I have found (and I have tried pretty much every one there is), because it is the only one that has low enough overhead to handle a processor-intensive applicatio...
Happy birthday: <http://www.jetbrains.com/profiler/>
Profiling C# / .NET applications
[ "", "c#", ".net", "visual-studio", "profiling", "profiler", "" ]
I'm using a custom-built inhouse application that generates a standard set of reports on a weekly basis. I have no access to the source code of the application, and everyone tells me there is no documentation available for the Oracle database schema. (Aargh!) I've been asked to define the specs for a variant of an exi...
On the data dictionary side there are a lot of tools you can use to such as [Schema Spy](http://schemaspy.sourceforge.net/) To look at what queries are running look at views sys.v\_$sql and sys.v\_$sqltext. You will also need access to sys.all\_users One thing to note that queries that use parameters will show up onc...
Sorry for the short answer but it is late. Google "oracle event 10046 sql trace". It would be best to trace an individual session because figuring which SQL belongs to which session from v$sql is no easy if it is shared sql and being used by multiple users. If you want to impress your Oracle DBA friends, learn how to ...
How to see the actual Oracle SQL statement that is being executed
[ "", "sql", "oracle", "" ]
As compared to say: ``` REPLICATE(@padchar, @len - LEN(@str)) + @str ```
This is simply an inefficient use of SQL, no matter how you do it. perhaps something like ``` right('XXXXXXXXXXXX'+ rtrim(@str), @n) ``` where X is your padding character and @n is the number of characters in the resulting string (assuming you need the padding because you are dealing with a fixed length). But as I ...
I know this was originally asked back in 2008, but there are some new functions that were introduced with SQL Server 2012. The [FORMAT function](https://msdn.microsoft.com/en-us/library/hh213505(v=sql.110).aspx) simplifies padding left with zeros nicely. It will also perform the conversion for you: ``` declare @n as i...
Most efficient T-SQL way to pad a varchar on the left to a certain length?
[ "", "sql", "sql-server", "t-sql", "" ]
I need to determine the ID of a form field from within an action handler. The field is a part of a included facelets component and so the form will vary. **included.xhtml** ``` <ui:component> <h:inputText id="contained_field"/> <h:commandButton actionListener="#{backingBean.update}" value="Submit"/> </ui:componen...
Bind the button to your backing bean, then use getParent() until you find the nearest form.
Programmatically I would use jsight's method. You can know the id of your elements (unless you let JSF create them, I don't know the means for numbering in the ids) by looking at it. h:form is a naming container so as long as you don't have it wrapped in another naming container it will be containingForm:containedfield...
Determine the ID of the JSF container form
[ "", "java", "jsf", "seam", "facelets", "" ]
I am working on developing an on-screen keyboard with java. This keyboard has a `JComponent` for every possible key. When a mouse down is detected on the button, I want to send a specific keyboard code to the application currently on focus. The keyboard itself is within a `JFrame` with no decorations and set to always-...
Apparently the only way to do this is to have a JNI layer that will make the conversion from java to native. Java has no easy way to provide such funcionality. This could be an interesting concept for a small, third party library for someone who wants to learn JNI...
I found [jnativehook](http://code.google.com/p/jnativehook/) when I was trying to control a gamebot with actual keyboard and mouse commands (to be more "human-like").
Sending a keyboard event from java to any application (on-screen-keyboard)
[ "", "java", "events", "swing", "keyboard", "java-native-interface", "" ]
I have been using C# for a while now, and going back to C++ is a headache. I am trying to get some of my practices from C# with me to C++, but I am finding some resistance and I would be glad to accept your help. I would like to expose an iterator for a class like this: ``` template <class T> class MyContainer { publ...
You may find the following article interesting as it addresses exactly the problem you have posted: [On the Tension Between Object-Oriented and Generic Programming in C++ and What Type Erasure Can Do About It](http://www.artima.com/cppsource/type_erasure.html)
I have done the following before so that I got an iterator that was independent of the container. This may have been overkill since I could also have used an API where the caller passes in a `vector<T*>&` that should be populated with all the elements and then the caller can just iterate from the vector directly. ``` ...
How can I expose iterators without exposing the container used?
[ "", "c++", "stl", "iterator", "encapsulation", "" ]
I have a website laid out in tables. (a long mortgage form) in each table cell is one HTML object. (text box, radio buttons, etc) What can I do so when each table cell is "tabbed" into it highlights the cell with a very light red (not to be obtrusive, but tell the user where they are)?
This is the table I tested my code on: ``` <table id="myTable"> <tr> <td><input type="text" value="hello" /></td> <td><input type="checkbox" name="foo" value="2" /></td> <td><input type="button" value="hi" /></td> </tr> </table> ``` Here is the code that worked: ``` // here is a cross-browser compati...
Use jQuery to make your life easier, and you can do something like this: ``` $('#mytableid input').focus( function() { $(this).addClass('highlight'); }).blur( function() { $(this).removeClass('highlight'); }); ``` This is basically saying when any input element in your table is under focus add the "highlig...
JavaScript highlight table cell on tab in field
[ "", "javascript", "html", "" ]
I'm just meddling in the ways of the RESTful web service in C# using ASP.Net 2.0 and have managed (via a class library, a reference to dll produced by the former and some adjustment of my web.config) to coax out a URI format like so: http: //localhost/DevelopmentProject/testhandler/?input=thisismyinput Which unremark...
I kinda cheated. Try: [My Article About How I Got Round It](http://www.codeproject.com/KB/aspnet/RestServicesInASPNET2.aspx)
One solution is to use UrlRewriting to rewrite the Url to what you need. I use <http://urlrewriter.net/> to do all my rewriting, and you could setup something like this in your scenario ``` <rewriter> <rewrite url="DevelopmentProject/testhandler/([\w]+)" to="DevelopmentProject/testhandler/?input=$1" />...
How do I "smoothly" format HttpHandler URI?
[ "", "c#", "asp.net", "rest", "httphandler", "web-services", "" ]
I need something in between a full text search and an index search: I want to search for text in one column of my table (probably there will be an index on the column, too, if that matters). Problem is, I want to search for words in the column, but I don't want to match parts. For example, my column might contain b...
SQL Server 2000 or above. ``` SELECT * FROM dbo.TblBusinessNames WHERE BusinessName like '%[^A-z^0-9]Break%' -- In the middle of a sentence OR BusinessName like 'Break%' -- At the beginning of a sentence ``` Keyword Reference for **LIKE**: <http://msdn.microsoft.com/en-us/library/aa933232(SQL.80).as...
Your word delimiters are going to be many: space, tab, beginning of line, parentheses, periods, commas, exclamation/question marks etc. So, a pretty simple solution is to use a regex in your WHERE clause. (And it's going to be a lot more efficient than just ORing every possible delimiter you can think of.) Since you m...
Search for words in SQL Server index
[ "", "sql", "sql-server", "linq", "full-text-search", "" ]
I have a JLabel (actually, it is a JXLabel). I have put an icon and text on it. `<icon><text>` Now I wand to add some spacing on the left side of the component, like this: `<space><icon><text>` I DON'T accept suggestion to move the JLabel or add spacing by modifying the image. I just want to know how to do it wit...
I have found the solution! ``` setBorder(new EmptyBorder(0,10,0,0)); ``` Thanks everyone!
The like this: is not very clear, but you can add spacing by adding a transparent border of a certain width to the label
How to add a horizontal gap with a JLabel
[ "", "java", "swing", "jlabel", "swingx", "" ]
Should I stick with Sun's Java code conventions for PHP code?
For PHP, i'd suggest to follow [Zends suggestions](http://framework.zend.com/manual/1.12/en/manual.html) As you might know, [Zend is the most widely used framework!](https://stackoverflow.com/questions/2648/what-php-framework-would-you-choose-for-a-new-application-and-why)
You should be following one of the PSR standards for PHP approved by the [Framework Interop Group](http://www.php-fig.org/) * [PSR-0](https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-0.md) - Aims to provide a standard file, class and namespace convention.. * [PSR-1](https://github.com/php-fig/fig-stan...
Which Coding convention to follow for PHP?
[ "", "php", "coding-style", "" ]
How do you convert between hexadecimal numbers and decimal numbers in C#?
To convert from decimal to hex do... ``` string hexValue = decValue.ToString("X"); ``` To convert from hex to decimal do either... ``` int decValue = int.Parse(hexValue, System.Globalization.NumberStyles.HexNumber); ``` or ``` int decValue = Convert.ToInt32(hexValue, 16); ```
Hex -> decimal: ``` Convert.ToInt64(hexString, 16); ``` Decimal -> Hex ``` string.Format("{0:x}", intValue); ```
How to convert numbers between hexadecimal and decimal
[ "", "c#", "hex", "type-conversion", "decimal", "" ]
I recently started learning [Emacs](http://www.gnu.org/software/emacs/). I went through the tutorial, read some introductory articles, so far so good. Now I want to use it for Python development. From what I understand, there are two separate Python modes for Emacs: python-mode.el, which is part of the Python project;...
If you are using GNU Emacs 21 or before, or XEmacs, use python-mode.el. The GNU Emacs 22 python.el won't work on them. On GNU Emacs 22, python.el does work, and ties in better with GNU Emacs's own symbol parsing and completion, ElDoc, etc. I use XEmacs myself, so I don't use it, and I have heard people complain that it...
[This site](http://www.rwdev.eu/articles/emacspyeng) has a description of how to get Python code completion in Emacs. [Ropemacs](http://rope.sourceforge.net/ropemacs.html) is a way to get Rope to work in emacs. I haven't had extensive experience with either, but they're worth looking into.
Emacs and Python
[ "", "python", "emacs", "" ]
I have an enum that looks as follows: ``` public enum TransactionStatus { Open = 'O', Closed = 'C'}; ``` and I'm pulling data from the database with a single character indicating - you guessed it - whether 'O' the transaction is open or 'C' the transaction is closed. now because the data comes out of the database as...
``` static void Main(string[] args) { object val = 'O'; Console.WriteLine(EnumEqual(TransactionStatus.Open, val)); val = 'R'; Console.WriteLine(EnumEqual(DirectionStatus.Left, val)); Console.ReadLine(); } public static bool EnumEqual(Enum e, object boxedValue) { return...
Enums are generally messy in C# so when using .NET 2.0 its common to wrap the syntax with generics to avoid having to write such clumsy code. In .NET 1.1 you can do something like the below, although it's not much tidier than the original snippet: ``` protected bool CharEnumEqualsCharObj(TransactionStatus enum_status...
I need a helper method to compare a char Enum and a char boxed to an object
[ "", "c#", "enums", "casting", "" ]
I have an iterable of entries on which I would like to gather some simple statistics, say the count of all numbers divisible by two and the count of all numbers divisible by three. My first alternative, While only iterating through the list once and avoiding the list expansion (and keeping the [split loop](http://www....
Having to iterate over the list multiple times isn't elegant IMHO. I'd probably create a function that allows doing: ``` twos, threes = countmatching(xrange(1,10), lambda a: a % 2 == 0, lambda a: a % 3 == 0) ``` A starting point would be something like this: ...
Alt 4! But maybe you should refactor the code to a function that takes an argument which should contain the divisible number (two and three). And then you could have a better functionname. ``` def methodName(divNumber, r): return sum(1 for v in r if v % divNumber == 0) print methodName(2, xrange(1, 10)) print meth...
Most pythonic way of counting matching elements in something iterable
[ "", "python", "list-comprehension", "" ]
The problem itself is simple, but I can't figure out a solution that does it in one query, and here's my "abstraction" of the problem to allow for a simpler explanation: **I will let my original explenation stand, but here's a set of sample data and the result i expect:** Ok, so here's some sample data, i separated p...
This is fairly similar to what you wrote, but should be fairly speedy as NOT EXISTS is more efficient, in this case, than NOT IN... ``` mysql> select * from foo; +----+-----+ | id | col | +----+-----+ | 1 | Bar | | 1 | Foo | | 2 | Foo | | 3 | Bar | | 4 | Bar | | 4 | Foo | +----+-----+ SELECT id , col...
You can join the initial table to itself with an OUTER JOIN like this: ``` create table #mytest ( id int, Name varchar(20) ); go insert into #mytest values (1,'Foo'); insert into #mytest values (1,'Bar'); insert into #mytest values (2,'Foo'); insert into #mytest values (3,'Bar'); insert ...
Selecting unique rows in a set of two possibilities
[ "", "sql", "mysql", "sql-server", "database", "postgresql", "" ]
I have an `ArrayList<String>` that I'd like to return a copy of. `ArrayList` has a clone method which has the following signature: ``` public Object clone() ``` After I call this method, how do I cast the returned Object back to `ArrayList<String>`?
``` ArrayList newArrayList = (ArrayList) oldArrayList.clone(); ```
Why would you want to clone? Creating a new list usually makes more sense. ``` List<String> strs; ... List<String> newStrs = new ArrayList<>(strs); ``` Job done.
How do I clone a generic List in Java?
[ "", "java", "generics", "arraylist", "clone", "" ]
Is there anyway in Java to delete data (e.g., a variable value, object) and be sure it can't be recovered from memory? Does assigning `null` to a variable in Java delete the value from memory? Any ideas? Answers applicable to other languages are also acceptable.
Due to the wonders virtual memory, it is nearly impossible to delete something from memory in a completely irretrievable manner. Your best bet is to zero out the value fields; however: * This does not mean that an old (unzeroed) copy of the object won't be left on an unused swap page, which could persist across reboot...
Store sensitive data in an array, then "zero" it out as soon as possible. Any data in RAM can be copied to the disk by a virtual memory system. Data in RAM (or a core dump) can also be inspected by debugging tools. To minimize the chance of this happening, you should strive for the following * keep the time window a ...
Irretrievably destroying data in Java
[ "", "java", "security", "" ]
I'm trying to write a query that extracts and transforms data from a table and then insert those data into another table. Yes, this is a data warehousing query and I'm doing it in MS Access. So basically I want some query like this: ``` INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) VALUES (SELECT LongIntColumn...
No "VALUES", no parenthesis: ``` INSERT INTO Table2(LongIntColumn2, CurrencyColumn2) SELECT LongIntColumn1, Avg(CurrencyColumn) as CurrencyColumn1 FROM Table1 GROUP BY LongIntColumn1; ```
You have two syntax options: **Option 1** ``` CREATE TABLE Table1 ( id int identity(1, 1) not null, LongIntColumn1 int, CurrencyColumn money ) CREATE TABLE Table2 ( id int identity(1, 1) not null, LongIntColumn2 int, CurrencyColumn2 money ) INSERT INTO Table1 VALUES(12, 12.00) INSERT INTO Ta...
How to do INSERT into a table records extracted from another table
[ "", "sql", "ms-access", "" ]
Can you create websites with Chinese characters in PHP? UPDATE: Perhaps I should have said - is it straight forward. Because some languages like Java make it extremely easy. Perhaps localisation in PHP isn't as easy as Java???
Yes on both counts. Read [this guide](http://www.herongyang.com/PHP-Chinese/) on building Chinese websites in PHP.
Yes, but you need to know what you are doing... Read this [article](http://www.phpwact.org/php/i18n/charsets) (search for *PHP's Problem with Character Encoding*) for starters.
Is PHP international?
[ "", "php", "localization", "" ]
I was reading a book on programming skills wherein the author asks the interviewee, "How do you crash a JVM?" I thought that you could do so by writing an infinite for-loop that would eventually use up all the memory. Anybody has any idea?
The closest thing to a single "answer" is `System.exit()` which terminates the JVM immediately without proper cleanup. But apart from that, native code and resource exhaustion are the most likely answers. Alternatively you can go looking on Sun's bug tracker for bugs in your version of the JVM, some of which allow for ...
I wouldn't call throwing an OutOfMemoryError or StackOverflowError a crash. These are just normal exceptions. To really crash a VM there are 3 ways: 1. Use JNI and crash in the native code. 2. If no security manager is installed you can use reflection to crash the VM. This is VM specific, but normally a VM stores a bu...
How do you crash a JVM?
[ "", "java", "jvm", "" ]
What's the best way to store a linked list in a MySQL database so that inserts are simple (i.e. you don't have to re-index a bunch of stuff every time) and such that the list can easily be pulled out in order?
Store an integer column in your table called 'position'. Record a 0 for the first item in your list, a 1 for the second item, etc. Index that column in your database, and when you want to pull your values out, sort by that column. ``` alter table linked_list add column position integer not null default 0; alter tabl...
Using Adrian's solution, but instead of incrementing by 1, increment by 10 or even 100. Then insertions can be calculated at half of the difference of what you're inserting between without having to update everything below the insertion. Pick a number large enough to handle your average number of insertions - if its to...
Linked List in SQL
[ "", "sql", "data-structures", "" ]
I made a view to abstract columns of different tables and pre-filter and pre-sort them. There is one column whose content I don't care about but I need to know whether the content is null or not. So my view should pass an alias as "*true*" in case the value of this specified column **isn't null** and "*false*" in case ...
You have to use a **CASE** statement for this: ``` SELECT CASE WHEN columnName IS NULL THEN 'false' ELSE 'true' END FROM tableName; ```
Or you can do like this: ``` SELECT RealColumn, CAST(0 AS bit) AS FakeBitColumn FROM tblTable ```
How to output a boolean in T-SQL based on the content of a column?
[ "", "sql", "sql-server-2000", "" ]
I maintain a Java Swing application. For backwards compatibility with java 5 (for Apple machines), we maintain two codebases, 1 using features from Java 6, another without those features. The code is largely the same, except for 3-4 classes that uses Java 6 features. I wish to just maintain 1 codebase. Is there a wa...
Assuming that the classes have similar functionality with 1.5 vs. 6.0 differences in implementation you could merge them into one class. Then, without editing the source to comment/uncomment, you can rely on the optimization that the compiler always do. If an if expression is always false, the code in the if statement ...
The suggestions about using custom class loaders and dynamically commented code are a bit incredulous when it comes to maintenance and the preservation of the sanity of whichever poor soul picks up the project after you shuffle to pastures new. The solution is easy. Pull the affected classes out into two separate, ind...
Java Compilation - Is there a way to tell the compiler to ignore parts of my code?
[ "", "java", "swing", "compilation", "" ]
As far as i know it is not possible to do the following in C# 2.0 ``` public class Father { public virtual Father SomePropertyName { get { return this; } } } public class Child : Father { public override Child SomePropertyName { get { ...
This is not possible in any .NET language because of type-safety concerns. In type-safe languages, you must provide covariance for return values, and contravariance for parameters. Take this code: ``` class B { S Get(); Set(S); } class D : B { T Get(); Set(T); } ``` For the `Get` methods, covariance m...
You can re-declare (new), but you can't re-declare and override at the same time (with the same name). One option is to use a protected method to hide the detail - this allows both polymorphism and hiding at the same time: ``` public class Father { public Father SomePropertyName { get { ret...
Can I Override with derived types?
[ "", "c#", ".net", "inheritance", "covariance", "" ]
I'd like to capture the output of [`var_dump`](https://www.php.net/manual/en/function.var-dump.php) to a string. The PHP documentation says; > As with anything that outputs its result directly to the browser, the [output-control functions](https://www.php.net/manual/en/ref.outcontrol.php) can be used to capture the o...
Use output buffering: ``` <?php ob_start(); var_dump($someVar); $result = ob_get_clean(); ?> ```
# Try [`var_export`](http://php.net/var_export) You may want to check out [`var_export`](http://php.net/var_export) — while it doesn't provide the same output as `var_dump` it does provide a second `$return` parameter which will cause it to return its output rather than print it: ``` $debug = var_export($my_var, true...
How can I capture the result of var_dump to a string?
[ "", "php", "string", "var-dump", "" ]
I currently have heavily multi-threaded server application, and I'm shopping around for a good multi-threaded memory allocator. So far I'm torn between: * Sun's umem * Google's tcmalloc * Intel's threading building blocks allocator * Emery Berger's hoard From what I've found hoard might be the fastest, but I hadn't ...
I've used tcmalloc and read about Hoard. Both have similar implementations and both achieve roughly linear performance scaling with respect to the number of threads/CPUs (according to the graphs on their respective sites). So: if performance is really that incredibly crucial, then do performance/load testing. Otherwis...
The only way to really tell which memory allocator is right for your application is to try a few out. All of the allocators mentioned were written by smart folks and will beat the others on one particular microbenchmark or another. If all your application does all day long is malloc one 8 byte chunk in thread A and fre...
Multithreaded Memory Allocators for C/C++
[ "", "c++", "c", "memory", "malloc", "allocation", "" ]
The System.Diagnostics.EventLog class provides a way to interact with a windows event log. I use it all the time for simple logging... ``` System.Diagnostics.EventLog.WriteEntry("MyEventSource", "My Special Message") ``` Is there a way to set the user information in the resulting event log entry using .NET?
Toughie ... I looked for a way to fill the user field with a .NET method. Unfortunately there is none, and you must import the plain old Win32 API [ReportEvent function](<http://msdn.microsoft.com/en-us/library/aa363679(VS.85).aspx)> with a `DLLImportAttribute` You must also redeclare the function with the right type...
You need to add it yourself into the event message. Use the System.Security.Principal namespace to get the current identity of the thread logging the event.
.NET : How to set user information in an EventLog Entry?
[ "", "c#", ".net", "vb.net", "event-log", "" ]
I've got a CSV file containing latitude and longitude values, such as: > "25°36'55.57""E","45°39'12.52""N" Anyone have a quick and simple piece of C# code to convert this to double values? Thanks
If you mean C# code to do this: result = 25 + (36 / 60) + (55.57 / 3600) First you'll need to parse the expression with Regex or some other mechanism and split it into the individual parts. Then: ``` String hour = "25"; String minute = "36"; String second = "55.57"; Double result = (hour) + (minute) / 60 + (second) ...
Thanks for all the quick answers. Based on the answer by amdfan, I put this code together that does the job in C#. ``` /// <summary>The regular expression parser used to parse the lat/long</summary> private static Regex Parser = new Regex("^(?<deg>[-+0-9]+)[^0-9]+(?<min>[0-9]+)[^0-9]+(?<sec>[0-9.,]+)[^0-9.,ENSW]+(?<po...
What's the easiest way to convert latitude and longitude to double values
[ "", "c#", "gis", "" ]
I'd like to limit the size of the file that can be uploaded to an application. To achieve this, I'd like to abort the upload process from the server side when the size of the file being uploaded exceeds a limit. Is there a way to abort an upload process from the server side without waiting the HTTP request to finish?
You can do something like this (using the [Commons](http://commons.apache.org/fileupload/) library): ``` public class UploadFileServiceImpl extends HttpServlet { protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException { response.setContentT...
With JavaEE 6 / Servlet 3.0 the preferred way of doing that would be to use the [@MultipartConfig annotation](http://docs.oracle.com/javaee/6/tutorial/doc/gmhal.html) on your servlet like this: ``` @MultipartConfig(location="/tmp", fileSizeThreshold=1024*1024, maxFileSize=1024*1024*5, maxRequestSize=1024*1024*5*5...
Aborting upload from a servlet to limit file size
[ "", "java", "http", "servlets", "upload", "" ]
(MFC Question) What's the best way to determine the current displayed client area in a CScrollView? I only need the size of the visible portion, so GetClientRect() won't work here.
You do need to use GetClientRect(), but I think you're asking the wrong question. It is not so that in a scrolled view there is a very big client window that is physically scrolled. Instead, when you scroll, the DC's viewportext and mapping mode are adjusted, which make it seem like your view is bigger than it actually...
Inside your OnDraw() function, you could call pDC->GetViewportOrg and pDC->GetViewportExt. **EDIT**: Sorry, I forgot that Viewport extents are only scaling factors. I agree that what you really need here is the client rect.
CScrollView and window size
[ "", "c++", "winapi", "mfc", "" ]
Is it possible to split the information in a .csproj across more than one file? A bit like a project version of the `partial class` feature.
You can not have more than one master csproj. But because the underneath wiring of the csproj is done using msbuild you can simply have multiple partial csproj that import each other. The solution file would see the most *derived* csproj. **project1.csproj** ``` <Project DefaultTargets="Build" xmlns="http://schemas.m...
Yes, you can split information across several files. You can use [Import Element (MSBuild)](http://msdn.microsoft.com/en-us/library/92x05xfs.aspx). Note that Visual Studio will give you [annoying security warning](http://msdn.microsoft.com/en-us/library/ms228217.aspx) if you will try to open project file that includes...
Partial .csproj Files
[ "", "c#", "csproj", "" ]
I am developing an online strategy game using .Net v2. Although the game is primarily strategic, it does have some tactical elements that require reasonable network performance. I plan to use TCP packets for strategic data and UDP packets for tactical data. {EDIT} I forgot to mention that I am leaning away from WCF an...
Why limit yourself to .NET 2.0. .NET 3.0 (or 3.5) contains WCF and is a solid, performant communications subsystem with good security. .NET 3.0 is just .NET 2.0 with additional libraries (WCF, WF, WPF).
Microsoft's own .NET based [XNA](http://creators.xna.com/) allows you to create networked games on Windows and XBox 360.
C# Game Network Library
[ "", "c#", "network-programming", "" ]
I'm working on a C# winforms application (VS.NET 2008, .NET 3.5 sp 1). I have a search field on a form, and rather than have a label next to the search field I'd like to show some grey text in the background of the search field itself ('Search terms', for example). When the user starts entering text in the search field...
You will need to use some P/Inovke interop code to do this. Look for the Win32 API `SendMessage` function and the `EM_SETCUEBANNER` message.
Its better to post the code instead of link. I am posting this from [here](http://www.ageektrapped.com/blog/wp-content/uploads/code/cuebanner.cs) ``` //Copyright (c) 2008 Jason Kemp //Permission is hereby granted, free of charge, to any person obtaining a copy //of this software an...
Showing a hint for a C# winforms edit control
[ "", "c#", "winforms", "user-interface", "" ]
Pros. and cons? how long do you use it? What about jambi?
I've used Qt on a couple of projects I did in c++ on several platforms over a period of seven years. I think it works pretty well and definitely was quicker for me to develop a decent GUI app on the Mac than plodding through a language I didn't know (Objective-C) at the time. I think the signal/slot mechanism is a bit...
I have been using Qt for several years now for commercial development and have been very happy with it. One of the nice things with Qt is that it provides a large set of libraries as well as the GUI stuff (eg XML parsing, threads, networking), all in a consistent style and all multi-platform. This means we rarely need...
Do you use Qt and why do you use it?
[ "", "c++", "qt", "qt-jambi", "" ]
Working with python interactively, it's sometimes necessary to display a result which is some arbitrarily complex data structure (like lists with embedded lists, etc.) The default way to display them is just one massive linear dump which just wraps over and over and you have to parse carefully to read it. Is there som...
``` from pprint import pprint a = [0, 1, ['a', 'b', 'c'], 2, 3, 4] pprint(a) ``` Note that for a short list like my example, pprint will in fact print it all on one line. However, for more complex structures it does a pretty good job of pretty printing data.
Somtimes [YAML](http://pyyaml.org/) can be good for this. ``` import yaml a = [0, 1, ['a', 'b', 'c'], 2, 3, 4] print yaml.dump(a) ``` Produces: ``` - 0 - 1 - [a, b, c] - 2 - 3 - 4 ```
Is there a pretty printer for python data?
[ "", "python", "prettify", "" ]
I discovered that you can start your variable name with a '@' character in C#. In my C# project I was using a web service (I added a web reference to my project) that was written in Java. One of the interface objects defined in the WSDL had a member variable with the name "params". Obviously this is a reserved word in ...
Straight from the [C# Language Specification](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/), [Identifiers (C#)](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/language-specification/lexical-structure#identifiers) : > The prefix "@" enables the use of > ...
It just lets you use a reserved word as a variable name. Not recommended IMHO (except in cases like you have).
What's the use/meaning of the @ character in variable names in C#?
[ "", "c#", "variables", "naming", "specifications", "reserved-words", "" ]