Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I've the enum type `ReportTypeEnum` that get passed between methods in all my classes but I then need to pass this on the URL so I use the ordinal method to get the int value. After I get it in my other JSP page, I need to convert it to back to an `ReportTypeEnum` so that I can continue passing it.
How can I convert ordinal to the `ReportTypeEnum`?
Using Java 6 SE. | To convert an ordinal into its enum representation you might want to do this:
```
ReportTypeEnum value = ReportTypeEnum.values()[ordinal];
```
Please notice the array bounds.
Note that every call to `values()` returns a newly cloned array which might impact performance in a negative way. You may want to cache the array if it's going to be called often.
[Code example on how to cache `values()`](https://stackoverflow.com/a/19277247/4773888).
---
This answer was edited to include the feedback given inside the comments | This is almost certainly **a bad idea**. Certainly if the ordinal is *de-facto* persisted (e.g. because someone has bookmarked the URL) - it means that you must always preserve the `enum` ordering in future, which may not be obvious to code maintainers down the line.
Why not encode the `enum` using `myEnumValue.name()` (and decode via `ReportTypeEnum.valueOf(s)`) instead? | Convert from enum ordinal to enum type | [
"",
"java",
"enums",
""
] |
Using SWT, what is the common way to indicate that a menu item (from a taskbar menu) is the currently active selection? Checkmark? Bold? How is this done with code? | Use the [CHECK](http://help.eclipse.org/stable/nftopic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/swt/SWT.html#CHECK) style during instantiation:
```
MenuItem menuItem = new MenuItem(menu, SWT.CHECK);
```
Use [getSelection](http://help.eclipse.org/stable/nftopic/org.eclipse.platform.doc.isv/reference/api/org/eclipse/swt/widgets/MenuItem.html#getSelection()) to check status:
```
boolean isSelected = menuItem.getSelection();
``` | [org.eclipse.swt.widgets.MenuItem](http://help.eclipse.org/stable/index.jsp?topic=/org.eclipse.platform.doc.isv/reference/api/org/eclipse/swt/widgets/MenuItem.html) **setSelection(true)** / **getSelection()**
The style of the selection depends on the style of the menu item: CHECK, CASCADE, PUSH, RADIO, SEPARATOR, as in:
[](https://i.stack.imgur.com/ryw2M.png)
(source: [developpez.com](http://jmdoudoux.developpez.com/cours/developpons/java/images/swt047.png)) [](https://i.stack.imgur.com/kq5wn.png)
(source: [developpez.com](http://jmdoudoux.developpez.com/cours/developpons/java/images/swt046.png)) | Java SWT: How to indicate a menu item is selected | [
"",
"java",
"swt",
"menu",
""
] |
I have code that searches for all users in a department:
```
string Department = "Billing";
DirectorySearcher LdapSearcher = new DirectorySearcher();
LdapSearcher.PropertiesToLoad.Add("displayName");
LdapSearcher.PropertiesToLoad.Add("cn");
LdapSearcher.PropertiesToLoad.Add("department");
LdapSearcher.PropertiesToLoad.Add("title");
LdapSearcher.PropertiesToLoad.Add("memberOf");
LdapSearcher.Filter = string.Format("(&(objectClass=user)(department={0}))", Department);
SearchResultCollection src = LdapSearcher.FindAll();
```
What would the filter need to look like if I only wanted everyone in the "Manager Read Only" AD Group?
Am I going about this all wrong? | Looking at your search I have a couple of points for you. First, the search uses objectClass (non-indexed) instead of objectCategory (indexed). Huge performance issue with that query. You would most always want to combine the two together depending on what you are trying to retrieve:
```
(&(objectCategory=person)(objectClass=user)) = All users (no contacts)
(&(objectCategory=person)(objectClass=contact)) = All contacts (no users)
(&(objectCategory=person)) = All users and contacts
```
As for looking up the users in a group you can enumerate the list of member objects of the specific group. In the member attribute of the group object is the distinguishedName of each user.
[This article describes enumerating members of a group...](http://www.codeproject.com/KB/system/everythingInAD.aspx#24)
Don't forget that you may have to handle nested groups of the parent group, as there isn't a default way to handle this with LDAP queries. For that you may need to evaluate if the member object is a group and then get the member attribute for that child group.
Lastly, you should get in the habit of specifying a dns prefix to your query.
Without DNS prefix:
```
LDAP://ou=ouname,dc=domain,dc=com
```
With DNS prefix (all three work):
```
LDAP://servername/ou=ouname,dc=domain,dc=com
LDAP://servername.domain.com/ou=ouname,dc=domain,dc=com
LDAP://domain.com/ou=ouname,dc=domain,dc=com
```
A single domain won't cause you much issue but when you try and run a search in a multiple domain environment you will get bitten without this addition. Hope this helps move you closer to your goal. | I've always found [Howto: (Almost) Everything In Active Directory via C#](http://www.codeproject.com/KB/system/everythingInAD.aspx) helps for most AD questions. | Get List of Users From Active Directory In A Given AD Group | [
"",
"c#",
"active-directory",
""
] |
I have two tables with one identical column name, but different data. I want to join the tables, but access both columns (row["price"], row["other\_price"]): How can I rename/alias one of them in the select statement? (I do not want to rename them in the DB) | ```
SELECT table1.price, table2.price AS other_price ...
``` | ```
select t1.Column as Price, t2.Column as Other_Price
from table1 as t1 INNER JOIN table2 as t2
ON t1.Key = t2.Key
```
like this ? | How to rename columns with `SELECT`? | [
"",
"sql",
"database",
"select",
"rename",
"tablecolumn",
""
] |
I've inherited a code base and I'm writing a little tool to update a database for it. The code uses a data access layer like SubSonic (but it is home-grown). There are many properties of an object, like "id", "templateFROM" and "templateTO", but there are 50 of them.
On screen, I can't display all 50 properties each in their own textbox for data entry, so I have a listbox of all the possible properties, and one textbox for editing. When they choose a property in the listbox, I fill the textbox with the value that property corresponds to. Then I need to update the property after they are done editing.
Right now I'm using 2 huge switch case statements. This seems stupid to me. Is there a way to dynamically tell C# what property I want to set or get? Maybe like:
```
entObj."templateFROM" = _sVal;
```
?? | You need to use System.Reflection for that task.
```
entObj.GetType().GetProperty("templateFROM").SetValue(entObj, _sVal, null);
```
This should help you. | What you want is called [reflection](http://msdn.microsoft.com/en-us/library/ms173183(VS.80).aspx). | Dynamically getting/setting a property of an object in C# 2005 | [
"",
"c#",
"reflection",
""
] |
I have trouble dealing with my for loops now, I'm trying to compare two datum, basically it will compare 2 items, then it will write the matches and the mismatches on the webpage.
I managed to write the matches on the webpage, it was working good. But there's a bug in my mismatch compare.
It wrote all the data on the webpage X times, here's my JS code:
```
function testItems(i1, i2) {
var newArray = [];
var newArray2 = [];
var count = 0;
var count2 = 0;
for(var i = 0; i < i1.length; i++) {
for(var j = 0; j < i2.length; j++) {
if(i1[i] == i2[j]) {
newArray.push(i1[i]);
count++;
} if (i1[i] !== i2[j]) {
newArray2.push(i1[i]);
count2++;
}
}
}
count-=2;
count2-=2
writeHTML(count,count2, newArray, newArray2);
}
```
The result was horrible for the mismatches:
[alt text http://www.picamatic.com/show/2009/03/01/07/44/2523028\_672x48.jpg](http://www.picamatic.com/show/2009/03/01/07/44/2523028_672x48.jpg)
I was expecting it to show the mistakes, not all the strings. | The issue you're seeing is because of the nested for loop. You are essentially doing a cross-compare: for every item in i1, you are comparing it to every item in i2 (remember that j starts again at 0 every time i advances... the two loops don't run in parallel).
Since I understand from the comments below that you want to be able to compare one array to the other, even if the items in each are in a different order, I've edited my original suggestion. Note that the snippet below does not normalize differences in case between the two arrays... don't know if that's a concern. Also note that it only compares i1 against i2... not both i1 to i2 and i2 to i1, which would make the task a little more challenging.
```
function testItems(i1, i2) {
var newArray = [];
var newArray2 = [];
for (var i = 0; i < i1.length; i++) {
var found = false;
for (var j = 0; j < i2.length; j++) {
if (i1[i] == i2[j]) found = true;
}
if (found) {
newArray.push(i1[i])
} else {
newArray2.push(i1[i])
}
}
}
```
As an alternative, you could consider using a hash table to index i1/i2, but since the example of strings in your comment include spaces and I don't know if you're using any javascript helper libraries, it's probably best to stick with the nested for loops. The snippet also makes no attempt to weed out duplicates.
Another optimization you might consider is that your newArray and newArray2 arrays contain their own length property, so you don't need to pass the count to your HTML writer. When the writer receives the arrays, it can ask each one for the .length property to know how large each one is. | Not directly related to the question but you should see this:
[Google techtalks about javascript](http://www.youtube.com/watch?v=hQVTIJBZook)
Maybe it will enlighten you :) | Why is my nested for loop not working as I expected? | [
"",
"javascript",
""
] |
I am developing a graphics application using Qt 4.5 and am putting images in the QPixmapCache, I wanted to optimise this so that if a user inserts an image which is already in the cache it will use that.
Right now each image has a unique id which helps optimises itself on paint events. However I realise that if I could calculate a hash of the image I could lookup the cache to see if it already exists and use that (it would help more for duplicate objects of course).
My problem is that if its a large QPixmap will a hash calculation of it slow things down or is there a quicker way? | A couple of comments on this:
1. If you're going to be generating a hash/cache key of a pixmap, then you may want to skip the QPixmapCache and **use QCache directly**. This would eliminate some overhead of using QStrings as keys (unless you also want to use the file path to locate the items)
2. As of Qt4.4, QPixmap has a "hash" value associated with it (see **QPixmap::cacheKey()** ). The documentation claims "Distinct QPixmap objects can only have the same cache key if they refer to the same contents." However, since Qt uses shared-data copying, this may only apply to copied pixmaps and not to two distinct pixmaps loaded from the same image. A bit of testing would tell you if it works, and if it does, it would let you easily get a hash value.
3. If you really want to do a good, fairly quick cache with removing duplications, **you might want to look at your own data structure** that sorts according to sizes, color depths, image types, and things such as that. Then you would only need to hash the actual image data after you find the same type of image with the same dimensions, bit-depths, etc. Of course, if your users generally open a lot of images with those things the same, it wouldn't help at all.
4. Performance: Don't forget about the benchmarking stuff Qt added in 4.5, which would let you compare your various hashing ideas and see which one runs the fastest. I haven't checked it out yet, but it looks pretty neat. | Just in case anyone comes across this problem (and isn't too terribly experienced with hashing things, particularly something like an image), here's a VERY simple solution I used for hashing QPixmaps and entering them into a lookup table for later comparison:
```
qint32 HashClass::hashPixmap(QPixmap pix)
{
QImage image = pix.toImage();
qint32 hash = 0;
for(int y = 0; y < image.height(); y++)
{
for(int x = 0; x < image.width(); x++)
{
QRgb pixel = image.pixel(x,y);
hash += pixel;
hash += (hash << 10);
hash ^= (hash >> 6);
}
}
return hash;
}
```
Here is the hashing function itself (you can have it hash into a qint64 if you desire less collisions). As you can see I convert the pixmap into a QImage, and simply walk through its dimensions and perform a very simple one-at-a-time hash on each pixel and return the final result. There are many ways to improve this implementation (see the other answers to this question), but this is the basic gist of what needs to be done.
The OP mentioned how he would use this hashing function to then construct a lookup table for later comparing images. This would require a very simple lookup initialization function -- something like this:
```
void HashClass::initializeImageLookupTable()
{
imageTable.insert(hashPixmap(QPixmap(":/Image_Path1.png")), "ImageKey1");
imageTable.insert(hashPixmap(QPixmap(":/Image_Path2.png")), "ImageKey2");
imageTable.insert(hashPixmap(QPixmap(":/Image_Path3.png")), "ImageKey2");
// Etc...
}
```
I'm using a QMap here called imageTable which would need to be declared in the class as such:
```
QMap<qint32, QString> imageTable;
```
Then, finally, when you want to compare an image to the images in your lookup table (ie: "what image, out of the images I know it can be, is this particular image?"), you just call the hashing function on the image (which I'm assuming will also be a QPixmap) and the return QString value will allow you to figure that out. Something like this would work:
```
void HashClass::compareImage(const QPixmap& pixmap)
{
QString value = imageTable[hashPixmap(pixmap)];
// Do whatever needs to be done with the QString value and pixmap after this point.
}
```
That's it. I hope this helps someone -- it would have saved me some time, although I was happy to have the experience of figuring it out. | What is the best way to get the hash of a QPixmap? | [
"",
"c++",
"qt",
"caching",
"hash",
"qpixmap",
""
] |
Is there a way to add a property to the objects of a Linq query result other than the following?
```
var query = from x in db.Courses
select new
{
x.OldProperty1,
x.OldProperty2,
x.OldProperty3,
NewProperty = true
};
```
I want to do this without listing out all of the current properties of my object. There are many properties, and I don't want to have to update this code whenever I may change my class.
I am still learning with LINQ and I appreciate your suggestions. | Add it with partial classes:
```
public partial class Courses
{
public String NewProperty { get; set; }
}
```
Then you can assign it after you've created the object. | I suppose you could return a new object composed of the new property and the selected object, like this:
```
var query = from x in db.Courses
select new
{
Course = x,
NewProperty = true
};
``` | LINQ - Add property to results | [
"",
"c#",
".net",
"linq",
"linq-to-sql",
""
] |
I have a barcode scanner (which acts like a keyboard) and of course I have a keyboard too hooked up to a computer. The software is accepting input from both the scanner and the keyboard. I need to accept only the scanner's input. The code is written in C#. Is there a way to "disable" input from the keyboard and only accept input from the scanner?
Note:
Keyboard is part of a laptop...so it cannot be unplugged. Also, I tried putting the following code
protected override Boolean ProcessDialogKey(System.Windows.Forms.Keys keyData)
{
return true;
}
But then along with ignoring the keystrokes from the keyboard, the barcode scanner input is also ignored.
I cannot have the scanner send sentinal characters as, the scanner is being used by other applications and adding a sentinal character stream would mean modifying other code.
Also, I cannot use the timing method of determining if the input came from a barcode scanner (if its a bunch of characters followed by a pause) since the barcodes scanned could potentially be single character barcodes.
Yes, I am reading data from a stream.
I am trying to follow along with the article: Distinguishing Barcode Scanners from the Keyboard in WinForms. However I have the following questions:
1. I get an error NativeMethods is inaccessible due to its protection level. It seems as though I need to import a dll; is this correct? If so, how do I do it?
2. Which protected override void WndProc(ref Message m) definition should I use, there are two implementations in the article?
3. Am getting an error related to [SecurityPermission( SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] error CS0246: The type or namespace name 'SecurityPermission' could not be found (are you missing a using directive or an assembly reference?). How do I resolve this error?
4. There is also an error on the line containing: if ((from hardwareId in hardwareIds where deviceName.Contains(hardwareId) select hardwareId).Count() > 0) Error is error CS1026: ) expected.
5. Should I be placing all the code in the article in one .cs file called BarcodeScannerListener.cs?
Followup questions about C# solution source code posted by Nicholas Piasecki on <http://nicholas.piasecki.name/blog/2009/02/distinguishing-barcode-scanners-from-the-keyboard-in-winforms/>:
1. I was not able to open the solution in VS 2005, so I downloaded Visual C# 2008 Express Edition, and the code ran. However, after hooking up my barcode scanner and scanning a barcode, the program did not recognize the scan. I put a break point in OnBarcodeScanned method but it never got hit. I did change the App.config with the id of my Barcode scanner obtained using Device Manager. There seems to be 2 deviceNames with HID#Vid\_0536&Pid\_01c1 (which is obtained from Device Manager when the scanner is hooked up). I don't know if this is causing the scanning not to work. When iterating over the deviceNames, here is the list of devices I found (using the debugger):
"\??\HID#Vid\_0536&Pid\_01c1&MI\_01#9&25ca5370&0&0000#{4d1e55b2-f16f-11cf-88cb-001111000030}"
"\??\HID#Vid\_0536&Pid\_01c1&MI\_00#9&38e10b9&0&0000#{884b96c3-56ef-11d1-bc8c-00a0c91405dd}"
"\??\HID#Vid\_413c&Pid\_2101&MI\_00#8&1966e83d&0&0000#{884b96c3-56ef-11d1-bc8c-00a0c91405dd}"
"\??\HID#Vid\_413c&Pid\_3012#7&960fae0&0&0000#{378de44c-56ef-11d1-bc8c-00a0c91405dd}"
"\??\Root#RDP\_KBD#0000#{884b96c3-56ef-11d1-bc8c-00a0c91405dd}"
"\??\ACPI#PNP0303#4&2f94427b&0#{884b96c3-56ef-11d1-bc8c-00a0c91405dd}"
"\??\Root#RDP\_MOU#0000#{378de44c-56ef-11d1-bc8c-00a0c91405dd}"
"\??\ACPI#PNP0F13#4&2f94427b&0#{378de44c-56ef-11d1-bc8c-00a0c91405dd}"
So there are 2 entries for HID#Vid\_0536&Pid\_01c1; could that be causing the scanning not to work?
OK so it seems that I had to figure out a way to not depend on the ASCII 0x04 character being sent by the scanner...since my scanner does not send that character. After that, the barcode scanned event is fired and the popup with the barcode is shown. So thanks Nicholas for your help. | [You could use the Raw Input API to distinguish between the keyboard and the scanner like I did recently.](https://web.archive.org/web/20150108213851/http://nicholas.piasecki.name/blog/2009/02/distinguishing-barcode-scanners-from-the-keyboard-in-winforms) It doesn't matter how many keyboard or keyboard-like devices you have hooked up; you will see a `WM_INPUT` before the keystroke is mapped to a device-independent virtual key that you typically see in a `KeyDown` event.
Far easier is to do what others have recommended and configure the scanner to send sentinel characters before and after the barcode. (You usually do this by scanning special barcodes in the back of the scanner's user manual.) Then, your main form's `KeyPreview` event can watch those roll end and swallow the key events for any child control if it's in the middle of a barcode read. Or, if you wanted to be fancier, you could use a low-level keyboard hook with `SetWindowsHookEx()` to watch for those sentinels and swallow them there (advantage of this is you could still get the event even if your app didn't have focus).
I couldn't change the sentinel values on our barcode scanners among other things so I had to go the complicated route. Was definitely painful. Keep it simple if you can!
--
**Your update, seven years later:** If your use case is reading from a USB barcode scanner, Windows 10 has a nice, friendly API for this built-in in `Windows.Devices.PointOfService.BarcodeScanner`. It's a UWP/WinRT API, but you can use it from a regular desktop app as well; that's what I'm doing now. Here's some example code for it, straight from my app, to give you the gist:
```
{
using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows;
using Windows.Devices.Enumeration;
using Windows.Devices.PointOfService;
using Windows.Storage.Streams;
using PosBarcodeScanner = Windows.Devices.PointOfService.BarcodeScanner;
public class BarcodeScanner : IBarcodeScanner, IDisposable
{
private ClaimedBarcodeScanner scanner;
public event EventHandler<BarcodeScannedEventArgs> BarcodeScanned;
~BarcodeScanner()
{
this.Dispose(false);
}
public bool Exists
{
get
{
return this.scanner != null;
}
}
public void Dispose()
{
this.Dispose(true);
GC.SuppressFinalize(this);
}
public async Task StartAsync()
{
if (this.scanner == null)
{
var collection = await DeviceInformation.FindAllAsync(PosBarcodeScanner.GetDeviceSelector());
if (collection != null && collection.Count > 0)
{
var identity = collection.First().Id;
var device = await PosBarcodeScanner.FromIdAsync(identity);
if (device != null)
{
this.scanner = await device.ClaimScannerAsync();
if (this.scanner != null)
{
this.scanner.IsDecodeDataEnabled = true;
this.scanner.ReleaseDeviceRequested += WhenScannerReleaseDeviceRequested;
this.scanner.DataReceived += WhenScannerDataReceived;
await this.scanner.EnableAsync();
}
}
}
}
}
private void WhenScannerDataReceived(object sender, BarcodeScannerDataReceivedEventArgs args)
{
var data = args.Report.ScanDataLabel;
using (var reader = DataReader.FromBuffer(data))
{
var text = reader.ReadString(data.Length);
var bsea = new BarcodeScannedEventArgs(text);
this.BarcodeScanned?.Invoke(this, bsea);
}
}
private void WhenScannerReleaseDeviceRequested(object sender, ClaimedBarcodeScanner args)
{
args.RetainDevice();
}
private void Dispose(bool disposing)
{
if (disposing)
{
this.scanner = null;
}
}
}
}
```
Granted, you'll need a barcode scanner that supports the USB HID POS and isn't just a keyboard wedge. If your scanner is just a keyboard wedge, I recommend picking up something like a used Honeywell 4600G off eBay for like $25. Trust me, your sanity will be worth it. | What I did in a similar situation is distinguish between a scan and a user typing by looking at the speed of the input.
Lots of characters very close together then a pause is a scan. Anything else is keyboard input.
I don't know exactly your requirements, so maybe that won't do for you, but it's the best I've got :) | How to distinguish between multiple input devices in C# | [
"",
"c#",
"barcode-scanner",
""
] |
I'm developing a custom HyperTerminal like application in a WinForms .Net 2.0 application. I have a multiline TextBox in a Panel in which you can interact with a hardware device.
My customer wants to have a custom Caret, a filled rectangle the size of one character space instead of the vertical line that is by default.
I know .Net does not provide an option to do this by default, but there must some Windows function to do it. | Assume a form with a textbox on it:
```
public partial class Form1 : Form
{
[DllImport("user32.dll")]
static extern bool CreateCaret(IntPtr hWnd, IntPtr hBitmap, int nWidth, int nHeight);
[DllImport("user32.dll")]
static extern bool ShowCaret(IntPtr hWnd);
public Form1()
{
InitializeComponent();
}
private void Form1_Shown(object sender, EventArgs e)
{
CreateCaret(textBox1.Handle, IntPtr.Zero, 10, textBox1.Height);
ShowCaret(textBox1.Handle);
}
}
``` | These are the list of Native Caret functions provided by Windows you can use them for you application.
```
[DllImport("User32.dll")]
static extern bool CreateCaret(IntPtr hWnd, int hBitmap, int nWidth, int nHeight);
[DllImport("User32.dll")]
static extern bool SetCaretPos(int x, int y);
[DllImport("User32.dll")]
static extern bool DestroyCaret();
[DllImport("User32.dll")]
static extern bool ShowCaret(IntPtr hWnd);
[DllImport("User32.dll")]
static extern bool HideCaret(IntPtr hWnd);
```
Refer SharpDevelop, Source Code @ src\Libraries\ICSharpCode.TextEditor\Project\Src\Gui\Caret.cs | Custom Caret for WinForms TextBox | [
"",
"c#",
".net",
"winforms",
"caret",
""
] |
One of the things I loved about VB6 is that you had the ability to tell the development environment to break on all errors regardless of what error handling you had set up. Is it possible to do the same thing in VS2008 so that the debugger will stop on any error even if it happens inside a try-catch statement?
The problem is particularly hard when you are processing a file with say 500 records and it is failing on one of them - who knows which one - You don't want to modify the code so that your for counter is initialized outside that for loop - that is sloppy long-term. You just want the debugger to know to stop because of some setting you put somewhere. | Yes, go to "Debug" menu, select "Exceptions...", check "Thrown" for "Common Language Runtime Exceptions" | Sure, press Ctrl-Alt-E to bring up the exceptions window and tick the **Thrown** checkbox on Common Language Runtime Exceptions
That will stop the execution, open the source code where the exception was thrown, and tell you with a message window what error it is, pointing at the line it was thrown. | Can you set VS2008 to break on an error inside a try-catch statement | [
"",
"c#",
"vb.net",
"visual-studio",
"debugging",
"exception",
""
] |
Is there a way in python to programmatically determine the width of the console? I mean the number of characters that fits in one line without wrapping, not the pixel width of the window.
**Edit**
Looking for a solution that works on Linux | Not sure why it is in the module `shutil`, but it landed there in Python 3.3. See:
[Querying the size of the output terminal](http://docs.python.org/3/library/shutil.html#querying-the-size-of-the-output-terminal)
```
>>> import shutil
>>> shutil.get_terminal_size((80, 20)) # pass fallback
os.terminal_size(columns=87, lines=23) # returns a named-tuple
```
A low-level implementation is in the os module. Cross-platform—works under Linux, Mac OS, and Windows, probably other Unix-likes. There's a backport as well, though no longer relevant. | ```
import os
rows, columns = os.popen('stty size', 'r').read().split()
```
uses the 'stty size' command which according to [a thread on the python mailing list](http://mail.python.org/pipermail/python-list/2000-May/033312.html) is reasonably universal on linux. It opens the 'stty size' command as a file, 'reads' from it, and uses a simple string split to separate the coordinates.
Unlike the os.environ["COLUMNS"] value (which I can't access in spite of using bash as my standard shell) the data will also be up-to-date whereas I believe the os.environ["COLUMNS"] value would only be valid for the time of the launch of the python interpreter (suppose the user resized the window since then).
(See answer by @GringoSuave on how to do this on python 3.3+) | How to get Linux console window width in Python | [
"",
"python",
"linux",
"console",
"terminal",
"width",
""
] |
I recently tried to use backgroundworker instead of "classic" threads and I'm realizing that it's causing, at least for me, more problems than solutions.
I have a backgroundworker running a synchronous read (in this case from serialPort) and getting blocked around 30 seconds in 1 code line, then cancellationpending isn't the solution. I'm seeing that if the application gets closed at this point (either with the cross button and Application.Exit()) the process keeps zombie forever.
I need a way to force abort or to kill the backgroundworker thread. | I'm not very sure on what you're trying to accomplish, but maybe the [SerialPort.DataReceived](http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.datareceived.aspx) event is a better solution?
If you're already proficient with the usage of threads, I don't see the point in using BackgroundWorker. It's designed for people who don't understand threads in the first place.
Besides, I don't like the idea of aborting a thread. It feels dangerous, and multithreaded applications don't need any more risk taking. | I put one together that (i think) does the job. Please let me know if im waaaay off.
Here is a simple exaple of how it works.
```
var backgroundWorker = new BackgroundWorker(){WorkerSupportsCancellation = true};
backgroundWorker.DoWork += (sender, args) =>
{
var thisWorker = sender as BackgroundWorker;
var _child = new Thread(() =>
{
//..Do Some Code
});
_child .Start();
while (_child.IsAlive)
{
if (thisWorker.CancellationPending)
{
_child.Abort();
args.Cancel = true;
}
Thread.SpinWait(1);
}
};
backgroundWorker.RunWorkerAsync(parameter);
//..Do Something...
backgroundWorker.CancelAsync();
```
Since the background worker is part of the thread pool, we dont want to abort it. But we can run a thread internally which we can allow an abort to occur on. The backgroundWorker then basically runs until either the child thread is complete or we signal to it to kill the process. The background worker thread can then go back into the read pool. Typically I will wrap this up in a helper class and pass through the delegate method that I want the background thread to run passed in as the parameter and run that in the child thread.
Please someone let me know if im banging my head against a wall but it seems to work fine.. But thats the problem with threads isnt it.. the varying results you can get when you run it at different times. | Backgroundworker abort | [
"",
"c#",
"winforms",
"backgroundworker",
""
] |
What is the benefit of inheriting from std::binary\_function (or std::unary\_function)?
For example I have such code:
```
class Person
{
public:
Person();
Person(int a, std::string n);
Person(const Person& src);
int age;
std::string name;
};
Person::Person()
: age(0)
, name("")
{};
Person::Person(int a, std::string n)
: age(a)
, name(n)
{};
Person::Person(const Person& src)
{
age = src.age;
name = src.name;
};
struct PersonPrint : public std::unary_function<Person, void>{
void operator() (Person p){
std::cout << " Person age: " << p.age
<< " name: " << p.name << std::endl;
}
};
struct PersonGreater : public std::binary_function<Person, Person, bool>{
bool operator()(const Person& p1, const Person p2){
if (p1.age > p2.age) return true;
if (p1.name.compare(p2.name) > 0) return true;
return false;
}
};
int main(int count, char** args)
{
std::vector<Person> personVec;
Person p1(10, "Person1");
Person p2(12, "Person2");
Person p3(12, "Person3");
personVec.push_back(p1);
personVec.push_back(p2);
personVec.push_back(p3);
std::cout << "before sort: " << std::endl;
std::for_each(personVec.begin(), personVec.end(), PersonPrint());
std::sort(personVec.begin(), personVec.end(), PersonGreater());
std::cout << "after: " << std::endl;
std::for_each(personVec.begin(), personVec.end(), PersonPrint());
}
```
But I also could write this code without inheritance form `std::unary_function/std::binary_function`?
```
struct PersonPrint {
void operator() (Person p) {
std::cout << " Person age: " << p.age << " name: " << p.name << std::endl;
}
};
struct PersonGreater {
bool operator()(const Person& p1, const Person p2) {
if (p1.age > p2.age) return true;
if (p1.name.compare(p2.name) > 0) return true;
return false;
}
};
```
**UPDATED**
std::binary\_function and std::unary\_function are deprecated as of C++11 see comment by @AlexandreC. | Inheritance from [unary|binary]\_function just gives you an additional typedefs in your class:
For unary\_function
```
argument_type
result_type
```
For binary\_function
```
first_argument_type
second_argument_type
result_type
```
Which are those types you pass to [unary|binary]\_function.
In your case there is no benefits.
If you ever going to use your Functors with other std Functors modificators like not1, bind1st you have to inherit from [unart|binart]\_function.
And if you are going to store this template information for your purpose it is better to use ready solution. | Besides the typedefs (already mentioned), there is also as aspect of readability. When I see `struct Foo {...` my first thought will be "Foo is a type". But with `struct Foo : public unary_function<...` I already know that Foo is a functor. For a programmer (unlike compilers), types and functors are quite distinct. | What is the benefit of inheriting from std::binary_function (or std::unary function)? | [
"",
"c++",
"stl",
""
] |
I've made a custom control, it's a FlowLayoutPanel, into which I put a bunch of other custom controls (just Buttons, each with three Labels and a PictureBox overlayed)
It works ok with around 100 buttons, but bump that up to 1000 and it's in trouble. Bump that up to 5000 and it just dies after 20 seconds.
I have very little custom code, and I make judicious use of suspend and resume layout.
So what am I doing wrong? I'm sure my (fairly rapid) computer should be able to handle a few thousand buttons and labels.
(I'm fairly new to C# GUI stuff, so perhaps I should be doing things completely different anyway.)
Edit 1:
This is pretty much the only custom code at the moment:
```
flowLayoutPanel1.SuspendLayout();
foreach (DataRow row in dt.Rows) // dt is from a DB query
{
flowLayoutPanel1.Controls.Add(new PersonButton(row));
}
flowLayoutPanel1.ResumeLayout();
```
and in the PersonButton constructor:
```
this.label1.Text = row["FirstName"].ToString().Trim() + " "
+ row["Surname"].ToString().Trim();
```
(There should also be a picture attached but I'm not sure if anyone can see it.)
Edit 2:
I guess I really should be using a DataGridView, or ListView, but I wanted more than just a line of text and a small icon per row; I wanted it to look similar to the downloads view in firefox (Ctrl + J). (See screenshot)
Thanks very much for all your input, BTW. I guess I'll have to rethink...
[alt text http://img156.imageshack.us/img156/1057/capture.png](http://img156.imageshack.us/img156/1057/capture.png) | Can a C# WinForm app handle 1000 instances of any type of control? I am no WinForm Guru, but what you are expecting from your application might be unreasonable.
The fact that you want to show 1000+ controls of any type might be a sign that you are approaching the design of your software from the wrong direction. | You'll have to post some of the layout code or we won't be able to help much/at all.
Also, your #1 best bet is to profile your code. Profiling is the only surefire way to find out what exactly is performing slowly in your code. In my experience, this is especially true of UI code. | Super slow C# custom control | [
"",
"c#",
"optimization",
"user-controls",
""
] |
I want to Embed a chart in a Web Application developed using django.
I have come across [Google charts API](http://code.google.com/p/google-chartwrapper/), [ReportLab](http://code.djangoproject.com/wiki/Charts), [PyChart](http://home.gna.org/pychart/), [MatPlotLib](http://matplotlib.sourceforge.net/) and [ChartDirector](http://www.advsofteng.com/?gid=misc&gclid=CJLaibjeiJkCFQMwpAodXkETng)
I want to do it in the server side rather than send the AJAX request to Google chart APIs, as I also want to embed the chart into the PDF.
Which is the best option to use, and what are the relative merits and demerits of one over the other. | Another choice is [CairoPlot](http://linil.wordpress.com/2008/09/16/cairoplot-11/).
We picked matplotlib over the others for some serious graphing inside one of our django apps, primarily because it was the only one that gave us exactly the kind of control we needed.
Performance generating PNG's was fine for us but... it was a highly specialized app with less than 10 logins a day. | Well, I'm involved in an open source project, [Djime](http://djime.github.com/), that uses [OpenFlashChart 2](http://teethgrinder.co.uk/open-flash-chart-2/).
As you can see from [our code](http://github.com/mikl/djime/blob/e6832c6e8d2aa8a3801b16121a0499f3b6d63503/djime/statistics/flashcharts.py), generating the JSON-data that OFC uses is a bit complex, but the output is very nice and user friendly, since you can add tooltips, etc. to the different elements. | Charts in django Web Applications | [
"",
"python",
"django",
"charts",
""
] |
I am trying to create a winform application that searches through an XML doc.
for my search I need to convert the the XML attribute in the xpath condition to lower case, by using lower-case() xpath function.
this causes a problem related to the function namespace.
I have tried to add the namespace manualy:
```
XmlNamespaceManager nsMgr = new XmlNamespaceManager(prs.Doc.NameTable);
nsMgr.AddNamespace("fn", "http://www.w3.org/2005/02/xpath-functions");
XmlNodeList results = prs.Doc.SelectNodes("//function[starts-with(fn:lower-case(@name),'" + txtSearch.Text + "')]",nsMgr);
```
but still I get exception:
XsltContext is needed for this query because of an unknown function. | fn:lower-case is defined in [XQuery 1.0 and XPath 2.0](http://www.w3.org/TR/xpath-functions). XSLT 2.0 works with XPATH 2.0.
AFAIK, .NET hasn't support XPATH 2.0 yet. and the XSLT version from .NET is 1.0 as well not 2.0 yet. | The [`lower-case()`](http://www.w3.org/TR/xpath-functions/#func-lower-case) function is defined for [XPath 2.0](http://www.w3.org/TR/xpath20/).
In [XPath 1.0](http://www.w3.org/TR/xpath) to convert letters to lower case one can still use the
[`translate()`](http://www.w3.org/TR/xpath#function-translate) function as shown below:
```
translate(@attrName, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', 'abcdefghijklmnopqrstuvwxyz')
``` | xpath and c# | [
"",
"c#",
"xpath",
""
] |
I couldn't find any definitive answer to this question.
I suppose most implementation use merge sort that is stable but, is the stability a requirement or a side effect? | C++ Standard ISO/IEC 14882:2003 says:
> 23.2.2.4/31
>
> **Notes:** Stable: the relative order of the equivalent elements is preserved. If an exception is thrown the
> order of the elements in the list is indeterminate. | Yes, std::list<>::sort is guaranteed to be stable.
See <http://www.sgi.com/tech/stl/List.html> | Is std::list<>::sort stable? | [
"",
"c++",
"sorting",
"stl",
""
] |
Now, I'm not sure whether this is a stupid question, please bear with me if it is.
Is the lock on an object "recursive", i. e. if two objects have references to a third object in their fields and a thread is running a synchronized method on one of the two, can any other thread access the third object?
```
// a and b are some objects that implement Runnable
// they both reference the same third object
a.ref = c;
b.ref = c;
// a is run in a thread and processes some data in a loop for a long time
// the method the loop belongs to is declared synchronized
threadA = new Thread(a);
threadA.start();
a.someSyncedMethod(); // this would block ...
b.ref.someOtherSyncedMethod(); // ... but would this?
a.ref.someOtherSyncedMethod(); // ... and how about this?
``` | It's worth separating out the concepts of "a lock" and "locking an object". There's no real idea of "locking an object" - there's "acquiring (and releasing)" the lock *associated with* an object. Yes, it sounds like I'm nitpicking - but the distinction is important because if you talk about an *object* being locked it sounds like no other threads will be able to change anything in the object while that lock is held.
Instead, it just means that no other thread will be able to acquire the same lock while the lock is held. There's no direct relationship between the lock and any of the contents of the object that the lock is associated with.
Methods declared "synchronized" acquire the lock associated with the instance of the object they belong to. This only makes other synchronized methods on the same object wait, and synchronized statements that explicitly sync on it.
Personally I don't like synchronized methods - I like to make it clearer by explicitly synchronizing on a (private, final) member variable which is only used for synchronization. | > ```
> a.someSyncedMethod(); // this would block ...
> ```
Only if you mark either the run method with synchronized or have ThreadA run code in synchronized methods.
In the JVM, each object owns what's known as a monitor. Only one thread can own the monitor associated with a given object at a time. Synchronized is the means by which you tell the current thread to go get the monitor before continuing.
Also the class itself owns a monitor for static methods. | Java: What, if anything, is locked by synchronized methods apart from the object they belong to? | [
"",
"java",
"concurrency",
"locking",
"mutex",
"semaphore",
""
] |
I am able to find the cursor position. But I need to find out if the mouse is stable. If the mouse wasn't moved for more than 1 minute, then we have to alert the user.
How its possible, are there any special events for this? (Only for IE in javascript) | Set a timeout when the mouse is moved one minute into the future, and if the mouse is moved, clear the timeout:
```
var timeout;
document.onmousemove = function(){
clearTimeout(timeout);
timeout = setTimeout(function(){alert("move your mouse");}, 60000);
}
``` | **Here's a one-and-done function that can check any element for movement:**
```
function mouse (element, delay, callback) {
// Counter Object
element.ms = {};
// Counter Value
element.ms.x = 0;
// Counter Function
element.ms.y = function () {
// Callback Trigger
if ((++element.ms.x) == delay) element.ms.callback(element, element.ms);
};
// Counter Callback
element.ms.callback = callback;
// Function Toggle
element.ms.toggle = function (state) {
// Stop Loop
if ([0, "off"][state]) clearInterval(element.ms.z);
// Create Loop
if ([1, "on"][state]) element.ms.z = setInterval(element.ms.y, 1);
};
// Function Disable
element.ms.remove = function () {
// Delete Counter Object
element.ms = null; return delete element.ms;
};
// Function Trigger
element.onmousemove = function () {
// Reset Counter Value
element.ms.x = -1;
};
// Return
return element.ms;
};
```
**Usage:**
`mouse(element, delay, callback)`
**Examples:**
*Make a video player hide the mouse after 5 seconds when idle and fullscreen*
```
let x = mouse(video, 5000, function (a) {
if (document.webkitIsFullScreen) video.style.cursor = "none";
});
x.toggle(1); addEventListener("mousemove", function () {
video.style.cursor = "auto";
});
```
*Chat Room AFK (45 Seconds) (assuming you have a chat box and a send message function):*
```
let x = mouse(chatBox, (45e3), function (a) {
chatBox.send({ text: chatBox.username + " is AFK.", italic: true });
});
x.toggle(1); x.addEventListener("mousemove", function () {
chatBox.send({ text: chatBox.username + " is no longer AFK", italic: true });
});
``` | Detecting when the mouse is not moving | [
"",
"javascript",
"events",
"mouse",
""
] |
I want to be able to determine the output folder based on the platform name: AS3, AS4, AS5, SUN.
I couldn't figure out how to extract the platform name from the system. I experimented with:
```
uname -a
file /bin/bash
```
Thanks
**Solution**
./lsb\_release -a
Kudos to Paul Dixon | Some linux systems will have support for [lsb\_release](http://refspecs.freestandards.org/LSB_3.1.0/LSB-Core-generic/LSB-Core-generic/lsbrelease.html) | I think you'll have to look in a specific file for each OS. For example, on SunOS, you can type:
```
uname -s -r -v
```
For RHEL, check `/etc/issue`. | Find the unix platform name | [
"",
"c++",
"linux",
"bash",
""
] |
For making a scalable multiuser server in C#, which of these two types of servers are more efficient? You can see an example of the async server using the begin\* methods (like beginaccept, beginsend) [here](http://www.java2s.com/Code/CSharp/Network/AsyncTcpServer.htm), and the threadpool implementation [here](http://pastebin.com/m524c477e).
I know what a threadpool is and how it works so I pretty much understand how that implementation works. What about the async server though? Does that spawn a thread for each and every send, receive, and connection event? How efficient is that vs a threadpool?
By efficiency I just mean a general balance of speed and memory use.
## edit:
It has been suggested to me to use the begin() methods, but don't these create overhead when they spawn a new thread to take care of the send, receive, or connect event? Or do they end up using some kind of internal threadpool? If not, is there a way to make it so it does use a threadpool or should I just roll my own async socket server? | If by scalable, you mean really large numbers of connections, you should also consider a number of other aspects beyond use of the thread-pool.
1) If you are using .NET3.5, consider SocketAsyncEventArgs rather than the BeginXXX/EndXXX. The approach is described in [MSDN Magazine](http://msdn.microsoft.com/en-us/magazine/cc163356.aspx). These allow for more efficient dispatch and processing of the underlying async i/o.
2) Consider your [memory usage very carefully](http://codebetter.com/blogs/gregyoung/archive/2007/06/18/async-sockets-and-buffer-management.aspx). Byte[] buffers allocated for asynchronous i/o are pinned, forcing the GC to work around them during the compaction phase which in turn may result in fragmentation and OutOfMemoryExceptions under load. Also, you have consider the lower-level native issues of async i/o such as available memory in the non-paged pool.
Some of the available techniques are using a single shared zero-byte buffer for all pending receives, and using pooled buffers (from memory that does not compacted - either LOH or native heap) for I/O that will actually transfer data. | The TcpServer implementation is going to be better, as it's going to take advantage of I/O completion ports to perform the asynchronous work, while the threadpool implementation is generally going to have to burn a thread to wait on the connections that are being accepted.
Generally speaking, use the async methods on things like files, databases, sockets (things that have an underlying unmanaged implementation to them) as they will utilize I/O completion ports for their work, which is generally more efficient than moving the code to the thread pool. However, it is going to add complexity to your code, so that is something you have to account for. | C# begin*() method vs threadpool for a server | [
"",
"c#",
"networking",
"sockets",
""
] |
My program has a component - dubbed the Scheduler - that lets other components register points in time at which they want to be called back. This should work much like the Unix cron service, i. e. you tell the Scheduler "notify me at ten minutes past every full hour".
I realize there are no real callbacks in Java.
Here's my approach, is there a library which already does this stuff? Feel free to suggest improvements, too.
Register call to Scheduler passes:
* a time specification containing hour, minute, second, year month, dom, dow, where each item may be unspecified, meaning "execute it every hour / minute etc." (just like crontabs)
* an object containing data that will tell the calling object what to do when it is notified by the Scheduler. The Scheduler does not process this data, just stores it and passes it back upon notification.
* a reference to the calling object
Upon startup, or after a new registration request, the Scheduler starts with a Calendar object of the current system time and checks if there are any entries in the database that match this point in time. If there are, they are executed and the process starts over. If there aren't, the time in the Calendar object is incremented by one second and the entreis are rechecked. This repeats until there is one entry or more that match(es). (Discrete Event Simulation)
The Scheduler will then remember that timestamp, sleep and wake every second to check if it is already there. If it happens to wake up and the time has already passed, it starts over, likewise if the time has come and the jobs have been executed.
---
**Edit**: Thanks for pointing me to Quartz. I'm looking for something much smaller, however. | If your needs are simple, consider using [java.util.Timer](http://java.sun.com/javase/6/docs/api/java/util/Timer.html):
```
public class TimerDemo {
public static void main(String[] args) {
// non-daemon threads prevent termination of VM
final boolean isDaemon = false;
Timer timer = new Timer(isDaemon);
final long threeSeconds = 3 * 1000;
final long delay = 0;
timer.schedule(new HelloTask(), delay, threeSeconds);
Calendar calendar = Calendar.getInstance();
calendar.add(Calendar.MINUTE, 1);
Date oneMinuteFromNow = calendar.getTime();
timer.schedule(new KillTask(timer), oneMinuteFromNow);
}
static class HelloTask extends TimerTask {
@Override
public void run() {
System.out.println("Hello");
}
}
static class KillTask extends TimerTask {
private final Timer timer;
public KillTask(Timer timer) {
this.timer = timer;
}
@Override
public void run() {
System.out.println("Cancelling timer");
timer.cancel();
}
}
}
```
As has been [noted](https://stackoverflow.com/questions/614257/java-library-class-to-handle-scheduled-execution-of-callbacks/614353#614353), the [ExecutorService](http://java.sun.com/javase/6/docs/api/java/util/concurrent/ExecutorService.html) of [java.util.concurrent](http://java.sun.com/javase/6/docs/api/java/util/concurrent/package-frame.html) offers a richer API if you need it. | Lookup [Quartz](http://www.quartz-scheduler.org/) | Java library class to handle scheduled execution of "callbacks"? | [
"",
"java",
"design-patterns",
"cron",
"scheduling",
"scheduled-tasks",
""
] |
I have two radio buttons and want to post the value of the selected one.
How can I get the value with jQuery?
I can get all of them like this:
```
$("form :radio")
```
How do I know which one is selected? | To get the value of the **selected** `radioName` item of a form with id `myForm`:
```
$('input[name=radioName]:checked', '#myForm').val()
```
Here's an example:
```
$('#myForm input').on('change', function() {
alert($('input[name=radioName]:checked', '#myForm').val());
});
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<fieldset>
<legend>Choose radioName</legend>
<label><input type="radio" name="radioName" value="1" /> 1</label> <br />
<label><input type="radio" name="radioName" value="2" /> 2</label> <br />
<label><input type="radio" name="radioName" value="3" /> 3</label> <br />
</fieldset>
</form>
``` | Use this..
```
$("#myform input[type='radio']:checked").val();
``` | How can I know which radio button is selected via jQuery? | [
"",
"javascript",
"jquery",
"html",
"jquery-selectors",
"radio-button",
""
] |
I prefer a lib solely based on pthreads. What is a good c++ lib to for threading? | I looked at some options some time ago. Here are some:
* [Boost Thread](http://www.boost.org/doc/libs/1_38_0/doc/html/thread.html) - This is the most standard choice. Boost is the most standard library for C++, that is not in the official standard.
* [POCO](http://pocoproject.org/) - Has thread support and a lot more. Is my preferred choice because it lets you set thread priorities, something boost doesn't support. Thread priorities are important for my application domain (soft real-time).
* [Zthread](http://en.wikipedia.org/wiki/Zthread) - Looks a good library. I have no experience with it.
* [ACE](http://www.cs.wustl.edu/~schmidt/ACE.html) - Well known library. I have no experience with it.
Then you have libraries that let you operate at an higher abstraction level like [Thread Buildings Blocks](http://www.intel.com/cd/software/products/asmo-na/eng/294797.htm). | How about [boost threads](http://www.boost.org/doc/libs/1_38_0/doc/html/thread.html)?
> Boost.Thread enables the use of
> multiple threads of execution with
> shared data in portable C++ code. It
> provides classes and functions for
> managing the threads themselves, along
> with others for synchronizing data
> between the threads or providing
> separate copies of data specific to
> individual threads. | Good c++ lib for threading | [
"",
"c++",
"multithreading",
""
] |
Is there a jQuery library or any leads on implementing that photo tagging like in Facebook and Orkut Photo albums?
Thanks | I didn't find any suitable plugins for this purpose. So I ended up writing myself a small plug-in to mark areas over an image based on the coordinates loaded through an XML file.
The basic code is required is:
```
<div id="imageholder">
<!-- The main image -->
<img src="<link to image file>" alt="Image">
<!-- The grid tags -->
<div class="gridtag" style="bottom: 100px; left: 106px; height: 41px; width: 41px;"/>
<div class="gridtag" style="bottom: 300px; left: 56px; height: 100px; width: 56px;"/>
<div class="gridtag" ...
</div>
```
And the basic CSS styling required:
```
#imageholder{
height:500px;
width:497px;
position:relative;
}
div.gridtag {
border:1px solid #F0F0F0;
display:block;
position:absolute;
z-index:3;
}
```
In the above the divs with class "gridtags" are added using jQuery through XML or JSON and by binding events on this divs, we can make phototagging similar in Orkut.
PS: This only one side of the phototagging, ie. if we already have the coordinates we can mark on an image and add click events, which is the part actually i wanted. :) You guys has to write code for doing the marking part of the phototagging. | Hmmm, I found that the new version of [Img Notes](http://www.sanisoft.com/blog/2009/01/23/img-notes-v02-a-couple-of-bug-fixes-and-some-more/) seems to do exactly what you want.
Checkout the [Demo](http://www.sanisoft.com/downloads/imgnotes-0.2/example.html). It allows you to easily add tag notes and show them using JQuery. He also depends on the [imgAreaSelect](http://odyniec.net/projects/imgareaselect/) jquery plugin for adding notes. | Phototagging like in Facebook and Orkut album photos? | [
"",
"javascript",
"jquery",
"web-applications",
"jquery-plugins",
""
] |
Related:
* [How to catch exceptions from a ThreadPool.QueueUserWorkItem?](https://stackoverflow.com/questions/753841)
* [Exceptions on .Net ThreadPool Threads](https://stackoverflow.com/questions/668265/exceptions-on-net-threadpool-threads)
---
If a method throws an exceptions that is called by the ThreadPool.QueueUserWorkItem method where will the exception be thrown? or will it just be eaten?
I mean it will never be thrown on the calling thread right?
--- | NO, the exception will never propagate to another thread. It will eventually crash the thread, and be caught by the runtime. At this point the runtime raises the AppDomain.UnhandledException event where the exception can be observed.
You can read more about this [here](http://msdn.microsoft.com/en-us/library/system.appdomain.unhandledexception.aspx). | The exception will crash your application if is not caught inside your thread callback (except for ThreadAbortException and AppDomainUnloadedException that are swallowed). Note that in .NET 1.1 all exceptions were swallowed. The behavior was changed in .NET 2.0.
I found this link: <http://msdn.microsoft.com/en-us/library/ms228965.aspx> | Exceptions on threadpool threads | [
"",
"c#",
"multithreading",
"threadpool",
""
] |
I have a stream object, and I want to create and output xml using some kind of xml stream, based on data in my input stream. I haven't done much work with streams, so I am trying to learn how to do this as efficiently as possible. The idea is that I do not want to load the entire input stream in memory, then create the entire output stream in memory because at some point you end up with at least double the size of the input stream taking up memory.
There must be ways so that as data is read in the input stream, the xml stream is built and the data read from the input stream is discarded. Additionally, I would like to architect it so that the xml stream isn't built completely then passed out, but instead the xml stream can be read as it is being built. Does anyone have some code samples, or good resources for learning about this? | For writing your XML out as a stream, use [XmlTextWriter](http://msdn.microsoft.com/en-us/library/system.xml.xmltextwriter.aspx).
You can give it a stream to write to. This will give you what you want (stream output) and give you a lot of flexibility. By passing the stream to use to your code as an argument, you could hook up a memory stream, or a file stream or just about anything without the XML formatting code needing to know. The XmlTextWriter will periodically flush the data (so it wont stick around unless nothing reads it from the stream), just remember to do a final flush/close at the end.
Streams are also how you will handle input. As you process that input and can decide on what XML elements to write, use the XmlTextWriter to write them and it will take care of streaming that data out to whoever will be reading it. So you end up with a loop (or loops) that is reading a bit, doing some processing, then writing to the XmlTextWriter all at once. | XmlTextReader is used if you need to access the XML as raw data without the overhead of an in memory Document Object Model (DOM)
XmlTextReader provides a faster mechanism for reading XML. The following code loads XmlTextReader from a stream.
```
using (XmlTextReader reader= new XmlTextReader (stream)) {
while (reader.Read())
{
switch (reader.NodeType)
{
case XmlNodeType.Element: // The node is an Element.
Console.Write("<" + reader.Name);
Console.WriteLine(">");
break;
case XmlNodeType.Text: //Display the text in each element.
Console.WriteLine (reader.Value);
break;
case XmlNodeType. EndElement: //Display end of element.
Console.Write("</" + reader.Name);
Console.WriteLine(">");
break;
}
}
}
``` | Help with streams (.net) | [
"",
"c#",
".net",
"streaming",
"stream",
"iostream",
""
] |
I am trying to port this line from MS SQL Server to SQLite
```
IF NOT EXISTS(SELECT 1 FROM EVENTTYPE WHERE EventTypeName = 'ANI Received')
INSERT INTO EVENTTYPE (EventTypeName) VALUES ('ANI Received');
```
It seems that SQLite does not support IF NOT EXISTS or at least I can't make it work.
Am I missing something simple? Is there a workaround? | How about this?
```
INSERT OR IGNORE INTO EVENTTYPE (EventTypeName) VALUES 'ANI Received'
```
(Untested as I don't have SQLite... however [this link](http://www.sqlite.org/lang_insert.html) is quite descriptive.)
Additionally, this should also work:
```
INSERT INTO EVENTTYPE (EventTypeName)
SELECT 'ANI Received'
WHERE NOT EXISTS (SELECT 1 FROM EVENTTYPE WHERE EventTypeName = 'ANI Received');
``` | If you want to ignore the insertion of existing value, there must be a Key field in your Table. Just create a table With Primary Key Field Like:
```
CREATE TABLE IF NOT EXISTS TblUsers (UserId INTEGER PRIMARY KEY, UserName varchar(100), ContactName varchar(100),Password varchar(100));
```
And Then Insert Or Replace / Insert Or Ignore Query on the Table Like:
```
INSERT OR REPLACE INTO TblUsers (UserId, UserName, ContactName ,Password) VALUES('1','UserName','ContactName','Password');
```
It Will Not Let it Re-Enter The Existing Primary key Value... This Is how you can Check Whether a Value exists in the table or not. | How to do IF NOT EXISTS in SQLite | [
"",
"sql",
"sqlite",
""
] |
I'm usign inheritance in linq2sql and have entites Supplier and Buyer that inherits from Client. I need to be able "upgrade" a Buyer to a Supplier.
I've tried:
```
Client client = ClientMethods.ValidateId<Client>(clientId);
client.ClientTypeId = ClientMethods.CLIENT_TYPE_SUPPLIER;
db.SubmitChanges();
```
But get "Not allowed: Inheritance discriminator change from '1' to '2' would change type from 'Buyer' to 'Supplier'."
The only solution I can find is to do this without linq2sql and write a SP?? | I am wondering why you even have the two different sub classes if it is a natural situation that you want to change from one type to the other. I think that you should refactor what you have and make the buyer and supplier one entity. Then if you have behavior that should be different based on whether or not the client is a buyer or supplier I would extract that into a seperate object which you can set or add to the client. | i just had the same problem, and solved\*) it by doubling the discriminator field into one computed column that is actually used as discriminator value and an integer column storing the value ...
\*) - one of the famous solutions that could have nasty side effects, so be warned | Linq2sql inheritance cast | [
"",
"c#",
"linq-to-sql",
""
] |
```
std::vector< std::vector<coords> >::iterator iter;
for(iter = characters.begin(); iter != characters.end(); iter++)
{
std::vector<coords>* cha = iter; // doesn't work.
}
// does work.
std::vector<coords>* character = &characters.at(0);
coords* first = &character->at(0);
```
And I don't get why. Isn't iter supposed to be a pointer to an element of the type that it's container is supposed to 'contain'?
Anyone willing to shed light on this?
By doesn't work I mean:
```
error C2440: 'initializing' : cannot convert from 'std::_Vector_iterator<_Ty,_Alloc>' to 'std::vector<_Ty> *'
```
Which doesn't make a whole lot of sense to me. | An iterator is a type that can be dereferenced like a pointer, i.e., it has an explicit `operator*()` and `operator->()`. It doesn't have to be a pointer.
So use `&*iter` if you want to get the address of the vector. | To clarify further on MSN's answer, you can think of the iterator as a wrapper to an individual item of the container, but it also has some smarts for incrementing (++iter), decrementing (++iter) etc. Remember, the underlying data structure may not be a contiguous block of memory depending on the container type / implementation. To access the actual value, you can
1) derefence the iterator, eg
`Type t = *iter;`
2) treat the iterator as a pointer to the container type, eg
`iter->someFuncOnTheContainerType();` | Accessing vector elements inside another vector through an iterator? | [
"",
"c++",
"vector",
"iterator",
"element",
""
] |
I'm just curious how this is done directly by browsers. I heard that .length property of Array in Javascript Engines in fact uses invisible setters and getters to achieve functionality of ECMA-s standard that says: "whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted"). I understand that setter is needed in this case, but what with getter? Do we really need to call native getter to get this value? Or this is only a some mistake with understanding Javascript Engine somewhere? | A property is either implemented as a field or as setter/getter methods.
If it's a field then it's just a value, when setting the value nothing more happens than that the value changes.
If you have a setter method in order to perform something more whenever the value is set, you also have a getter method to match, even if the getter method doesn't do anything more than just return the value. You don't want to mix the two ways of implementing a property, it's just a lot simpler to go all the way in either direction. | Have a look at [**defineGetter** and **defineSetter**](https://developer.mozilla.org/En/Core_JavaScript_1.5_Guide:Creating_New_Objects:Defining_Getters_and_Setters). This might be how Firefox does it, but I'm not sure about the other browsers.
Does it really matter? .length could be implemented in c++ for all I know. It could be a builtin part of the javascript engine, and not really implementable in javascript in anyway. All that you, the user, needs to know is that the length holds the length of the array, and if you change it the length of the array changes. | Javascript Array .length property/method of JavascriptEngine | [
"",
"javascript",
"arrays",
""
] |
is there a way to slice a string lets say i have this variable
```
$output=Country=UNITED STATES (US) &City=Scottsdale, AZ &Latitude=33.686 &Longitude=-111.87
```
i want to slice it in a way i want to pull latitude and longitude values in to seperate variables, subtok is not serving the purpose | You don't need a regular expression for this; use `explode()` to split up the string, first by `&`, and then by `=`, which you can use to effectively parse it into a nice little array mapping names to values. | ```
$output='Country=UNITED STATES (US) &City=Scottsdale, AZ &Latitude=33.686 &Longitude=-111.87';
parse_str($output, $array);
$latitude = $array['latitude'];
```
You could also just do
```
parse_str($output);
echo $latitude;
```
I think using an array is better as you are not creating variables all over the place, which could potentially be dangerous (like register\_globals) if you don't trust the input string. | string slicing, php | [
"",
"php",
"string",
"tokenize",
""
] |
For an application I am writing, I want to have extreme extensibility and extension methods seem to give me what I want, plus the ability to call them without an instance, which I need too.
I remember reading that static methods are faster than instance methods but don't get the advantages of GC. Is this correct?
It's highly unlikely I will change my design unless I find a superior alternative by design not speed. But still for extra information I wanna know the differences in speed, GC, etc.
EDIT: Thanks. More info: Let's say we have a Person class:
```
class Person
```
which can have an instance Distance method so like:
```
this.Distance (Person p)
```
This is great, but this doesn't give me the ability to calculate the distance between 2 points (say Point3), without creating instances of the Person class.
What I want to do is this:
```
class Person (no Distance methods)
```
but extension methods of Distance:
```
Distance (this Person, Person)
Distance (this Point3, Point3)
```
This way I can both do:
```
myPerson.Distance (yourPerson)
```
and
```
Extensions.Distance (pointA, pointB)
```
EDIT2: @Jon, yeah I think that was what was meant by (don't get the advantages of GC), but I somehow thought that the static methods create this burden/overhead. | What do you mean by "don't get the advantages of GC"? Methods aren't garbage collected - instances are.
Virtual methods are *slightly* slower than non-virtual ones, and I guess there's that pesky null check before any instance method, but it's not significant. Go with the most appropriate design.
Static methods are a pain for testing though - for instance, if you authenticate in method `Foo()` by calling some static method, then when you're testing `Foo()` you can't make it just call a mock authenticator (unless the static method itself lets you do that). If you give the original instance of whatever you're testing a mock implementation of some interface containing an `Authenticate()` method, however, you can make it behave however you want.
EDIT: In this case, it sounds like what you really need is an instance method on your `Point` type to calculate the distance between two points ("this" one and another) - or potentially a static factory method on the `Distance` type. | Choosing between static and instance methods is a matter of object-oriented design. If the method you are writing is a *behavior* of a an object, then it should be an instance method. If it doesn't depend on an instance of an object, it should be static.
Basically, static methods belong to a type while instance methods belong to instances of a type. | Static methods vs instance methods in C# | [
"",
"c#",
".net",
"garbage-collection",
"clr",
"methods",
""
] |
The original title here was
**Workaround for SFINAE bug in VS2005 C++**
This is tentative use of SFINAE to make the equivalent for the is\_pod template class that exists in TR1 (In VS2005 there's no TR1 yet). It should have its *value* member true when the template parameter is a POD type (including primitive types and structs made of them) and false when it's not (like with non-trivial constructors).
```
template <typename T> class is_pod
{
public:
typedef char Yes;
typedef struct {char a[2];} No;
template <typename C> static Yes test(int)
{
union {T validPodType;} u;
}
template <typename C> static No test(...)
{
}
enum {value = (sizeof(test<T>(0)) == sizeof(Yes))};
};
class NonPOD
{
public:
NonPod(const NonPod &);
virtual ~NonPOD();
};
int main()
{
bool a = is_pod<char>::value;
bool b = is_pod<NonPOD>::value;
if (a)
printf("char is POD\n");
if (b)
printf("NonPOD is POD ?!?!?\n");
return 0;
}
```
The problem is, not only VS 2005 doesn't have TR1, it won't care about the union above (which shouldn't be valid when the template parameter is not a POD), so both a and b evaluate to true.
---
Thanks for the answers posted below. After reading carefully them (and the code) I realized that what I was trying to do was really a wrong approach. The idea was to combine SFINAE behavior with an adaptation to the template *must\_be\_pod* (which I found in the book *Imperfect C++*, but it can be found in another places, too). Actually, this would require a quite particular set of rules for SFINAE, which are not what the standard defines, obviously. This is not really a bug in VS, after all. | The biggest problem with your approach is you don't do SFINAE here - SFINAE only applies to parameter types and return type here.
However, of all the SFINAE situations in the standard, none applies to your situation. They are
* arrays of void, references, functions, or of invalid size
* type member that is not a type
* pointers to references, references to references, references to void
* pointer to member of a non-class type
* invalid conversions of template value parameters
* function types with arguments of type void
* const/volatile function type
That's probably why in Boost documentation, there is:
> Without some (as yet unspecified) help
> from the compiler, ispod will never
> report that a class or struct is a
> POD; this is always safe, if possibly
> sub-optimal. Currently (May 2005) only
> MWCW 9 and Visual C++ 8 have the
> necessary compiler-\_intrinsics. | This doesn't work with VS2008 either, but I suspect you knew that too. SFINAE is for deducing template arguments for template parameters; you can't really deduce the type of something that reveals the constructor-ness of a type, even though you can create a type that is incompatible with another type (i.e., unions can't use non-POD).
In fact, VS 2008 uses compiler support for traits to implement `std::tr1::type_traits`. | Using SFINAE to detect POD-ness of a type in C++ | [
"",
"c++",
"visual-studio-2005",
"sfinae",
""
] |
What order should headers be declared in a header / cpp file? Obviously those that are required by subsequent headers should be earlier and class specific headers should be in cpp scope not header scope, but is there a set order convention / best practice? | In a header file you have to include ALL the headers to make it compilable. And don't forget to use forward declarations instead of some headers.
In a source file:
* corresponded header file
* necessary project headers
* 3rd party libraries headers
* standard libraries headers
* system headers
In that order you will not miss any of your header files that forgot to include libraries by their own. | Good practice: every .h file should have a .cpp that includes that .h first before anything else. This proves that any .h file can be put first.
Even if the header requires no implementation, you make a .cpp that just includes that .h file and nothing else.
This then means that you can answer your question any way you like. It doesn't matter what order you include them in.
For further great tips, try this book: [Large-Scale C++ Software Design](https://rads.stackoverflow.com/amzn/click/com/0201633620) - it's a shame it's so expensive, but it is practically a survival guide for C++ source code layout. | In what order should headers be included? | [
"",
"c++",
"include",
"header-files",
"code-organization",
""
] |
I am working on C++ since last 4-5 years . Recently I have bought iphone and macbook and want do do some programming for iphone.
So I have started reading one book about Objective-C. I have also learn that we can program with Ruby and Python on MAC.
So my question is which one to study? Which language you guys see the FUTURE???
Can we program with these languages on other platforms? Or are these only limited on MAC?
I am just a beginner in objective-C.Need some expert thoughts which way to go.
AC | I use all the languages C++, Ruby, Python and Objective-C. I like each one in different ways. If you want to get into Mac and iPhone development as others I recommend Objective-C.
One of the benefits not mentioned is that Objective-C is a proper superset of C (C++ is almost a superset), that means you can bring over all your C programming knowledge from doing C++ to Objective-C programming. In fact you can also mix in C++ code in Objective-C code.
You can't do that in a seamless way in Python and Ruby. The reason why you can do this is that Objective-C is actually a very simple language.
Originally it was just C with a custom made preprocessor which took statements like this:
```
[rectangle setX: 10 y: 10 width: 20 height: 20];
```
and converted it to this before compiling:
```
objc_msgSend(rectangle, "setX:y:width:height:", 10, 10, 20, 20);
```
Apart from that Ruby, Python and Objective-C are very similar in their object model at least compared to C++. In C++ classes are created at compile time. In Objective-C, Ruby and Python classes are things created at runtime.
I wrote some stuff on [why Obj-C is cool here](http://loadcode.blogspot.com/2007/09/why-objective-c-is-cool.html) | If you want to program for iphone then you should use objective-C. The entire iphone API is based on objective-C, and you have the benefits of using interface builder and IDE support from Xcode. | Study Objective-C , Ruby OR Python? | [
"",
"python",
"objective-c",
"ruby",
"programming-languages",
""
] |
I'm looking for a way to check if a server is still available.
We have a offline application that saves data on the server, but if the serverconnection drops (it happens occasionally), we have to save the data to a local database instead of the online database.
So we need a continues check to see if the server is still available.
We are using C# for this application
The check on the `sqlconnection.open` is not really an option because this takes about 20 sec before an error is thrown, we can't wait this long + I'm using some http services as well. | Just use the [System.Net.NetworkInformation.Ping](https://msdn.microsoft.com/en-us/library/system.net.networkinformation.ping(v=vs.110).aspx) class. If your server does not respond to ping (for some reason you decided to block ICMP Echo request) you'll have to invent your own service for this. Personally, I'm all for not blocking ICMP Echo requests, and I think this is the way to go. The ping command has been used for ages to check **reachability of hosts**.
```
using System.Net.NetworkInformation;
var ping = new Ping();
var reply = ping.Send("google.com", 60 * 1000); // 1 minute time out (in ms)
// or...
reply = ping.Send(new IPAddress(new byte[]{127,0,0,1}), 3000);
``` | If the connection is as unreliable as you say, I would not use a seperate check, but **make saving the data local part of the exception handling**.
I mean if the connection fails and throws an exception, you switch strategies and save the data locally.
If you check first and the connection drops afterwards (when you actually save data), then you still would still run into an exception you need to handle. So the initial check was unnecessary. The check would only be useful if you can assume that after a succesfull check the connection is up and stays up. | Check if a server is available | [
"",
"c#",
""
] |
Basically I am trying to render a simple image in an ASP.NET handler:
```
public void ProcessRequest (HttpContext context)
{
Bitmap image = new Bitmap(16, 16);
Graphics graph = Graphics.FromImage(image);
graph.FillEllipse(Brushes.Green, 0, 0, 16, 16);
context.Response.ContentType = "image/png";
image.Save(context.Response.OutputStream, ImageFormat.Png);
}
```
But I get the following exception:
```
System.Runtime.InteropServices.ExternalException: A generic error
occurred in GDI+.
at System.Drawing.Image.Save(Stream stream, ImageCodecInfo encoder,
EncoderParameters encoderParams)
```
The solution is to use this instead of having image write to OutputStream:
```
MemoryStream temp = new MemoryStream();
image.Save(temp, ImageFormat.Png);
byte[] buffer = temp.GetBuffer();
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
```
So I'm just curious as to why the first variant is problematic?
Edit: The HRESULT is 80004005 which is just "generic". | The writer indeed needs to seek to write in the stream properly.
But in your last source code, make sure that you do use either MemoryStream.ToArray() to get the proper data or, if you do not want to copy the data, use MemoryStream.GetBuffer() with MemoryStream.Length and not the length of the returned array.
GetBuffer will return the internal buffer used by the MemoryStream, and its length generally greater than the length of the data that has been written to the stream.
This will avoid you to send garbage at the end of the stream, and not mess up some strict image decoder that would not tolerate trailing garbage. (And transfer less data...) | Image.Save(MemoryStream stream) does require a MemoryStream object that can be seeked upon. The context.Response.OutputStream is forward-only and doesn't support seeking, so you need an intermediate stream. However, you don't need the byte array buffer. You can write directly from the temporary memory stream into the context.Response.OutputStream:
```
/// <summary>
/// Sends a given image to the client browser as a PNG encoded image.
/// </summary>
/// <param name="image">The image object to send.</param>
private void SendImage(Image image)
{
// Get the PNG image codec
ImageCodecInfo codec = GetCodec("image/png");
// Configure to encode at high quality
using (EncoderParameters ep = new EncoderParameters())
{
ep.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
// Encode the image
using (MemoryStream ms = new MemoryStream())
{
image.Save(ms, codec, ep);
// Send the encoded image to the browser
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "image/png";
ms.WriteTo(HttpContext.Current.Response.OutputStream);
}
}
}
```
A fully functional code sample is available here:
[Auto-Generate Anti-Aliased Text Images with ASP.NET](http://www.dlssoftwarestudios.com/blog/?p=63) | Cannot render image to HttpContext.Response.OutputStream | [
"",
"c#",
"asp.net",
"gdi+",
"system.drawing",
""
] |
What is the best, DBMS-independent way of generating an ID number that will be used immediately in an INSERT statement, keeping the IDs roughly in sequence? | DBMS independent? That's a problem. The two most common methods are auto incrementing columns, and sequences, and most DBMSes do one or the other but not both. So the database independent way is to have another table with one column with one value that you lock, select, update, and unlock.
Usually I say "to hell with DBMS independence" and do it with sequences in PostgreSQL, or autoincrement columns in MySQL. For my purposes, supporting both is better than trying to find out one way that works everywhere. | If you can create a [Globally Unique Identifier](http://en.wikipedia.org/wiki/Globally_Unique_Identifier) (GUID) in your chosen programming language - consider that as your id.
They are harder to work with when troubleshooting (it is much easier to type in a `where` condition that is an INT) but there are also some advantages. By assigning the GUID as your key locally, you can easily build parent-child record relationships without first having to save the parent to the database and retrieve the id. And since the GUID, by definition, is unique, you don't have to worry about incrementing your key on the server. | What is the best way to generate an ID for a SQL Insert? | [
"",
"sql",
"rdbms-agnostic",
""
] |
OK I have a mySQL Database that looks something like this
**ID - an int and the unique ID of the recorded**
**Title - The name of the item**
**Description - The items description**
I want to search both title and description of key words, currently I'm using.
**SELECT \* From ‘item’ where title LIKE %key%**
And this works and as there’s not much in the database, as however searching for “this key” doesn’t find “this that key” I want to improve the search engine of the site, and may be even add some kind of ranking system to it (but that’s a long time away).
So to the question, I’ve heard about something called “Full text search” it is (as far as I can tell) a staple of database design, but being a Newby to this subject I know nothing about it so…
1) Do you think it would be useful?
And an additional questron…
2) What can I read about database design / search engine design that will point me in the right direction.
If it’s of relevance the site is currently written in stright PHP (I.E. without a framework) (thro the thought of converting it to Ruby on Rails has crossed my mind)
**update**
Thanks all, I'll go for Fulltext search.
And for any one finding this later, I found a good [tutorial](http://www.devarticles.com/c/a/MySQL/Getting-Started-With-MySQLs-Full-Text-Search-Capabilities/) on fulltext search as well. | The problem with the '%keyword%' type search is that there is no way to efficiently search on it in a regular table, even if you create an index on that column. Think about how you would look that string up in the phone book. There is actually no way to optimize it - you have to scan the entire phone book - and that is what MySQL does, a full table scan.
If you change that search to 'keyword%' and use an index, you can get very fast searching. It sounds like this is not what you want, though.
So with that in mind, I have used fulltext indexing/searching quite a bit, and here are a few pros and cons:
**Pros**
* Very fast
* Returns results sorted by relevance (by default, although you can use any sorting)
* Stop words can be used.
**Cons**
* Only works with MyISAM tables
* Words that are too short are ignored (default minimum is 4 letters)
* Requires different SQL in where clause, so you will need to modify existing queries.
* Does not match partial strings (for example, 'word' does not match 'keyword', only 'word')
[Here is some good documentation on full-text searching](http://dev.mysql.com/doc/refman/5.0/en/fulltext-natural-language.html).
Another option is to use a searching system such as [Sphinx](http://www.sphinxsearch.com/). It can be extremely fast and flexible. It is optimized for searching and integrates well with MySQL. | You might also consider Zend\_Lucene. It's slightly easier to integrate than Sphinx, because it is pure PHP. | Is Full Text search the answer? | [
"",
"php",
"mysql",
"search",
""
] |
I'm trying to build some code for dynamically sorting a Linq IQueryable<>.
The obvious way is here, which sorts a list using a string for the field name
<http://dvanderboom.wordpress.com/2008/12/19/dynamically-composing-linq-orderby-clauses/>
However I want one change - compile time checking of field names, and the ability to use refactoring/Find All References to support later maintenance. That means I want to define the fields as f=>f.Name, instead of as strings.
For my specific use I want to encapsulate some code that would decide which of a list of named "OrderBy" expressions should be used based on user input, without writing different code every time.
Here is the gist of what I've written:
```
var list = from m Movies select m; // Get our list
var sorter = list.GetSorter(...); // Pass in some global user settings object
sorter.AddSort("NAME", m=>m.Name);
sorter.AddSort("YEAR", m=>m.Year).ThenBy(m=>m.Year);
list = sorter.GetSortedList();
...
public class Sorter<TSource>
...
public static Sorter<TSource> GetSorter(this IQueryable<TSource> source, ...)
```
The GetSortedList function determines which of the named sorts to use, which results in a List object, where each FieldData contains the MethodInfo and Type values of the fields passed in AddSort:
```
public SorterItem<TSource> AddSort(Func<T, TKey> field)
{
MethodInfo ... = field.Method;
Type ... = TypeOf(TKey);
// Create item, add item to diction, add fields to item's List<>
// The item has the ThenBy method, which just adds another field to the List<>
}
```
I'm not sure if there is a way to store the entire field object in a way that would allow it be returned later (it would be impossible to cast, since it is a generic type)
Is there a way I could adapt the sample code, or come up with entirely new code, in order to sort using strongly typed field names *after* they have been stored in some container and retrieved (losing any generic type casting) | The easiest way to do this would be to have your AddSort() function take an Expression<Func<Movie>> instead of just a Func. This allows your sort method to inspect the Expression to extract out the name of the property that you want to sort on. You can then store this name internally as a string, so storing is very easy and you can use the sorting algorithm you linked to, but you also get type safety and compile time checking for valid property names.
```
static void Main(string[] args)
{
var query = from m in Movies select m;
var sorter = new Sorter<Movie>();
sorter.AddSort("NAME", m => m.Name);
}
class Sorter<T>
{
public void AddSort(string name, Expression<Func<T, object>> func)
{
string fieldName = (func.Body as MemberExpression).Member.Name;
}
}
```
In this case, i've used object as the return type of the func, because its easily automatically convertible, but you could implement that with different types, or generics, as appropriate, if you require more functionality. In this case, since the Expression is just there to be inspected, it doesn't really matter.
The other possible way is to still take a Func, and store that in the dictionary itself. Then, when it comes to sorting, and you need to get the value to sort on, you can call something like:
```
// assuming a dictionary of fields to sort for, called m_fields
m_fields[fieldName](currentItem)
``` | Bummer! I must learn how to read the specifications from end to end :-(
However, now that I have spent too much time fooling around rather than working, I will post my results anyway hoping this will inspire people to read, think, understand (important) and then act. Or how to be too clever with generics, lambdas and funny Linq stuff.
> A neat trick I discovered during this
> exercise, are those private inner
> classes which derives from `Dictionary`.
> Their whole purpose is to remove all
> those angle brackets in order to
> improve readability.
Oh, almost forgot the code:
**UPDATE: Made the code generic and to use `IQueryable` instead of `IEnumerable`**
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using NUnit.Framework;
using NUnit.Framework.SyntaxHelpers;
namespace StackOverflow.StrongTypedLinqSort
{
[TestFixture]
public class SpecifyUserDefinedSorting
{
private Sorter<Movie> sorter;
[SetUp]
public void Setup()
{
var unsorted = from m in Movies select m;
sorter = new Sorter<Movie>(unsorted);
sorter.Define("NAME", m1 => m1.Name);
sorter.Define("YEAR", m2 => m2.Year);
}
[Test]
public void SortByNameThenYear()
{
var sorted = sorter.SortBy("NAME", "YEAR");
var movies = sorted.ToArray();
Assert.That(movies[0].Name, Is.EqualTo("A"));
Assert.That(movies[0].Year, Is.EqualTo(2000));
Assert.That(movies[1].Year, Is.EqualTo(2001));
Assert.That(movies[2].Name, Is.EqualTo("B"));
}
[Test]
public void SortByYearThenName()
{
var sorted = sorter.SortBy("YEAR", "NAME");
var movies = sorted.ToArray();
Assert.That(movies[0].Name, Is.EqualTo("B"));
Assert.That(movies[1].Year, Is.EqualTo(2000));
}
[Test]
public void SortByYearOnly()
{
var sorted = sorter.SortBy("YEAR");
var movies = sorted.ToArray();
Assert.That(movies[0].Name, Is.EqualTo("B"));
}
private static IQueryable<Movie> Movies
{
get { return CreateMovies().AsQueryable(); }
}
private static IEnumerable<Movie> CreateMovies()
{
yield return new Movie {Name = "B", Year = 1990};
yield return new Movie {Name = "A", Year = 2001};
yield return new Movie {Name = "A", Year = 2000};
}
}
internal class Sorter<E>
{
public Sorter(IQueryable<E> unsorted)
{
this.unsorted = unsorted;
}
public void Define<P>(string name, Expression<Func<E, P>> selector)
{
firstPasses.Add(name, s => s.OrderBy(selector));
nextPasses.Add(name, s => s.ThenBy(selector));
}
public IOrderedQueryable<E> SortBy(params string[] names)
{
IOrderedQueryable<E> result = null;
foreach (var name in names)
{
result = result == null
? SortFirst(name, unsorted)
: SortNext(name, result);
}
return result;
}
private IOrderedQueryable<E> SortFirst(string name, IQueryable<E> source)
{
return firstPasses[name].Invoke(source);
}
private IOrderedQueryable<E> SortNext(string name, IOrderedQueryable<E> source)
{
return nextPasses[name].Invoke(source);
}
private readonly IQueryable<E> unsorted;
private readonly FirstPasses firstPasses = new FirstPasses();
private readonly NextPasses nextPasses = new NextPasses();
private class FirstPasses : Dictionary<string, Func<IQueryable<E>, IOrderedQueryable<E>>> {}
private class NextPasses : Dictionary<string, Func<IOrderedQueryable<E>, IOrderedQueryable<E>>> {}
}
internal class Movie
{
public string Name { get; set; }
public int Year { get; set; }
}
}
``` | Strongly typed dynamic Linq sorting | [
"",
"c#",
".net",
"linq",
""
] |
i have a LoginWindow with username and password to access in the software after that the user authenticated i want show in the next window(the mainWindow of the software) the name of the user authenticated in a TextBlock ...i show a code snippet of my LoginWindow:
```
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
public bool ValidateApplicationUser(string userName, string password)
{
{
var AuthContext = new DataClasses1DataContext();
var query = from c in AuthContext.Users
where (c.Username == userName.ToLower() && c.Password == password.ToLower())
select c;
if(query.Count() != 0 )
{
return true;
}
return false;
}
}
private void mahhh(object sender, RoutedEventArgs e)
{
bool authenticated = true;
{
if (usernameTextBox.Text !="" && passwordTextBox.Text != "")
{
authenticated = ValidateApplicationUser(usernameTextBox.Text , passwordTextBox.Text);
}
}
if (!authenticated)
{
MessageBox.Show("Invalid login. Try again.");
}
else
{
MessageBox.Show("Congradulations! You're a valid user!");
MainWindow c = new MainWindow();
c.ShowDialog();
}
}
}
```
If I authenticate with the username"Marc" in the MainWindow i will show the username "Marc" in a TextBlock and I don't know I make it?
How I can do it? | Simply, Pass the UserName to the constructor of the Main window like this
```
MainWindow c = New MainWindow(usernameTextBox.Text);
```
And in the constructor of the main window receive the value in variable and do whatever you want with it, like this
```
private String _userName;
public MainWindow(string userName)
{
_userName = userName
}
``` | i think you had some mistake in yr code (it will allow empty field to log) , it has to be like :
```
bool authenticated = true;
{
if (usernameTextBox.Text !="" && passwordTextBox.Text != "")
{
authenticated = ValidateApplicationUser(usernameTextBox.Text , passwordTextBox.Text);
}
}
if (!authenticated || usernameTextBox.Text == "" || passwordTextBox.Text == "")
{
MessageBox.Show("Invalid login. Try again.");
}
else
{
MessageBox.Show("Congradulations! You're a valid user!");
MainWindow c = new MainWindow();
c.ShowDialog();
}
``` | Binding TextBlock Linq ToSql & WPF | [
"",
"c#",
".net",
"wpf",
"linq-to-sql",
""
] |
I'm looking for a C# example showing how to access a remote SOAP Web Service, and logging (to a file, or even just to a string I can do whatever with) all complete raw SOAP requests and complete raw SOAP responses.
I found some other posts on StackOverflow with similar topics, but they seem to reference a web.config file, which my *desktop* application does not have. I assume this is because they are using C# in the form of a web application querying a remote SOAP web service. Mine is a desktop application.
Any takers? | You could use [SOAP extensions](http://msdn.microsoft.com/en-us/library/esw638yk%28VS.71%29.aspx) to get the SOAP content as a string and then log it wherever. | In the above post, that should be "app.config" and "web.config", and the better URL is the one at <http://msdn.microsoft.com/en-us/library/ms730064.aspx>. | C# SOAP Web Services client - example that shows how to log all raw SOAP intput and output? | [
"",
"c#",
"web-services",
"logging",
"soap",
""
] |
Can someone provide a good explanation (hopefully with examples) of these 3 most important delegates:
* Predicate
* Action
* Func | * `Predicate`: essentially `Func<T, bool>`; asks the question "does the specified argument satisfy the condition represented by the delegate?" Used in things like List.FindAll.
* `Action`: Perform an action given the arguments. Very general purpose. Not used much in LINQ as it implies side-effects, basically.
* `Func`: Used *extensively* in LINQ, usually to transform the argument, e.g. by projecting a complex structure to one property.
Other important delegates:
* `EventHandler`/`EventHandler<T>`: Used all over WinForms
* `Comparison<T>`: Like `IComparer<T>` but in delegate form. | `Action`, `Func` and `Predicate` all belong to the delegate family.
`Action` : Action can take n input parameters but it returns void.
`Func` : Func can take n input parameters but it will always return the result of the provided type. `Func<T1,T2,T3,TResult>`, here T1,T2,T3 are input parameters and TResult is the output of it.
`Predicate` : Predicate is also a form of Func but it will always return bool. In simple words it is wrapper of `Func<T,bool>`. | Delegates: Predicate vs. Action vs. Func | [
"",
"c#",
"delegates",
"predicate",
"func",
""
] |
I have an HSQLDB database with a generated ID and I want the auto-incrementing values to always be above 100,000. Is this possible with HSQLDB? Is this possible with any database? | According to the [HSQL Documentation](http://hsqldb.sourceforge.net/doc/guide/ch02.html):
> Since 1.7.2, the SQL standard syntax
> is used by default, which allows the
> initial value to be specified. The
> supported form is( INTEGER
> GENERATED BY DEFAULT AS IDENTITY(START
> WITH n, [INCREMENT BY m])PRIMARY KEY,
> ...). Support has also been added for
> BIGINT identity columns. As a result,
> an IDENTITY column is simply an
> INTEGER or BIGINT column with its
> default value generated by a sequence
> generator.
...
> The next IDENTITY value to be used can
> be set with the
>
> ```
> ALTER TABLE <table name> ALTER COLUMN <column name> RESTART WITH <new value>;
> ``` | [Here's how to do it in HSQLDB](http://hsqldb.org/doc/2.0/guide/databaseobjects-chapt.html#dbc_number_sequence):
> The next IDENTITY value to be used can be changed with the following statement. Note that this statement is not used in normal operation and is only for special purposes, for example resetting the identity generator:
>
> ```
> ALTER TABLE ALTER COLUMN <column name> RESTART WITH <new value>;
> ```
As far as I know, all SQL databases allow you to set a seed value for the auto-increment fields.
**Update:** Here's a list of [identity/auto-increment implementations in the major SQL databases](http://troels.arvin.dk/db/rdbms/#mix-identity). | Auto incrementing ID value | [
"",
"sql",
"primary-key",
"identity",
"hsqldb",
""
] |
Using C# 3.5 I wanted to build up a predicate to send to a where clause piece by piece. I have created a very simple Console Application to illustrate the solution that I arrived at. This works perfectly. Absolutely perfectly. But I have NO idea how or why.
```
public static Func<Tran, bool> GetPredicate()
{
Func<Tran, bool> predicate = null;
predicate += t => t.Response == "00";
predicate += t => t.Amount < 100;
return predicate;
}
```
When I say 'predicate +=', what does that mean? predicate -= appears to do nothing and ^=, &=, \*=, /= aren't liked by the compiler.
The compiler doesn't like 'predicate = predicate + t => t.Response....' either.
What have I stumbled on? I know what it does, but how does it do it?
If anyone wants to go delve into more complicated lambda's, please do so. | "delegate += method" is operator for multicast delegate to combine method to delegate.
In the other hand "delegate -= method" is operator to remove method from delegate.
It is useful for Action.
```
Action action = Method1;
action += Method2;
action += Method3;
action -= Method2;
action();
```
In this case, only Method1 and Method3 will run, Method2 will not run because you remove the method before invoke the delegate.
If you use multicast delegate with Func, the result will be last method.
```
Func<int> func = () => 1;
func += () => 2;
func += () => 3;
int result = func();
```
In this case, the result will be 3, since method "() => 3" is the last method added to delegate. Anyway all method will be called.
In your case, method "t => t.Amount < 100" will be effective.
If you want to combine predicate, I suggest these extension methods.
```
public static Func<T, bool> AndAlso<T>(
this Func<T, bool> predicate1,
Func<T, bool> predicate2)
{
return arg => predicate1(arg) && predicate2(arg);
}
public static Func<T, bool> OrElse<T>(
this Func<T, bool> predicate1,
Func<T, bool> predicate2)
{
return arg => predicate1(arg) || predicate2(arg);
}
```
Usage
```
public static Func<Tran, bool> GetPredicate() {
Func<Tran, bool> predicate = null;
predicate = t => t.Response == "00";
predicate = predicate.AndAlso(t => t.Amount < 100);
return predicate;
}
```
EDIT: correct the name of extension methods as Keith suggest. | When you use += or -= when delegate types, that just gives a call to `Delegate.Combine` and `Delegate.Remove`.
The important thing about multicast delegates is that the return value of *all but the last executed delegate* is ignored. They all get executed (unless an exception is thrown), but only the last return value is used.
For predicates, you might want to do something like:
```
public static Func<T, bool> And<T>(params Func<T, bool>[] predicates)
{
return t => predicates.All(predicate => predicate(t));
}
public static Func<T, bool> Or<T>(params Func<T, bool>[] predicates)
{
return t => predicates.Any(predicate => predicate(t));
}
```
You'd then do:
```
Func<string, bool> predicate = And<string>(
t => t.Length > 10,
t => t.Length < 20);
```
EDIT: Here's a more general solution which is quite fun, if a bit bizarre...
```
public static Func<TInput, TOuput> Combine<TInput, TOutput>
(Func<TOutput, TOutput, TOutput> aggregator,
params Func<TInput, TOuput>[] delegates) {
// delegates[0] provides the initial value
return t => delegates.Skip(1).Aggregate(delegates[0](t), aggregator);
}
```
So you *could* then implement And as:
```
public static Func<T, bool> And<T>(params Func<T, bool>[] predicates) {
return Combine<T, bool>((x, y) => x && y, predicates);
}
```
(I personally prefer this over using `GetInvocationList()`, because you end up with a predicate you can pass to other bits of LINQ etc.) | Concatenating Lambda Functions in C# | [
"",
"c#",
"lambda",
""
] |
Is there a way to iterate over every property of an object using the Prototype JavaScript framework?
Here's the situation: I am getting an AJAX response in JSON that looks something like this:
```
{foo: 1, bar: 2, barobj: {75: true, 76: false, 85: true}}
```
If I evaluate that json response in to a variable `response`, I want to be able to iterate over each property in the `response.barobj` object to see which indexes are true and which are false.
Prototype has both `Object.keys()` and `Object.values()` but oddly seems to not have a simple `Object.each()` function! I could take the results of Object.keys() and Object.values() and cross-reference the other as I iterate through one, but that is such a hack that I am sure there is a proper way to do it! | You have to first [convert your object literal to a Prototype Hash](http://prototypejs.org/doc/latest/language/Hash/):
```
// Store your object literal
var obj = {foo: 1, bar: 2, barobj: {75: true, 76: false, 85: true}}
// Iterate like so. The $H() construct creates a prototype-extended Hash.
$H(obj).each(function(pair){
alert(pair.key);
alert(pair.value);
});
``` | There's no need for Prototype here: JavaScript has [`for..in`](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Statements/for...in) loops. If you're not sure that no one messed with `Object.prototype`, check `hasOwnProperty()` as well, ie
```
for(var prop in obj) {
if(obj.hasOwnProperty(prop))
doSomethingWith(obj[prop]);
}
``` | Iterating over every property of an object in javascript using Prototype? | [
"",
"javascript",
"prototypejs",
""
] |
I am looking for CLI specification.
Where can I find it to download? | Why not ask google?
<http://www.ecma-international.org/publications/standards/Ecma-335.htm> | I think you're after [ECMA 335](http://www.ecma-international.org/publications/standards/Ecma-335.htm). | Where can I find CLI specification? | [
"",
"c#",
".net",
"specifications",
""
] |
JSON allows you to [retrieve data in multiple formats](http://docs.jquery.com/Ajax/jQuery.get) from an AJAX call. For example:
```
$.get(sourceUrl, data, callBack, 'json');
```
could be used to get and parse JSON code from `sourceUrl`.
JSON is the simply JavaScript code used to describe data. This could be evaled by a JavaScript interpreter to get a data structure back.
It's generally a bad idea to evaluate code from remote sources. I know the JSON spec doesn't specifically allow for function declarations, but there's no reason you couldn't include one in code and have an unsafe and naive consumer compile/execute the code.
How does jQuery handle the parsing? Does it evaluate this code? What safeguards are in place to stop someone from hacking `sourceUrl` and distributing malicious code? | The last time I looked (late 2008) the JQuery functions get() getJSON() etc internally eval the JSon string and so are exposed to the same security issue as eval.
Therefore it is a very good idea to use a parsing function that validates the JSON string to ensure it contains no dodgy non-JSON javascript code, before using eval() in any form.
You can find such a function at <https://github.com/douglascrockford/JSON-js/blob/master/json2.js>.
See [JSON and Broswer Security](http://yuiblog.com/blog/2007/04/10/json-and-browser-security/) for a good discussion of this area.
In summary, using JQuery's JSON functions without parsing the input JSON (using the above linked function or similar) is not 100% safe.
NB: If this sort of parsing is still missing from getJSON (might have recently been added) it is even more important to understand this risk due to the cross domain capability, from the JQuery reference docs:
> As of jQuery 1.2, you can load JSON
> data located on another domain if you
> specify a JSONP callback, which can be
> done like so: "myurl?callback=?".
> jQuery automatically replaces the ?
> with the correct method name to call,
> calling your specified callback. | `$.getJSON()` is used to execute (rather than using `eval`) javascript code from remote sources (using the JSONP idiom if a callback is specified). When using this method, it is totally up to you to trust the source, because they will have control to your entire page (they can even be sending cookies around).
From [Douglas Crockford](http://javascript.crockford.com/script.html) site about *The Script Tag Hack* (jsonp):
> So the script can access and use
> its cookies. It can access the
> originating server using the user's
> authorization. It can inspect the DOM
> and the JavaScript global object, and
> send any information it finds anywhere
> in the world. The Script Tag Hack is
> not secure and should be avoided. | Is getting JSON data with jQuery safe? | [
"",
"javascript",
"jquery",
"security",
""
] |
I'm in the process of learning Python while implementing build scripts and such. And for the moment everything is working fine in that the scripts do what they need to do. But I keep having the feeling I'm missing something, such as "The Python Way". I know build scripts and glue scripts are not really the most exciting development work and may hardly be a candidate for revealing the true power of Python but I'd still like the opportunity to have my mind blown. I develop mostly in C# and I find that my Python code looks awfully similar in structure and style to a lot of my C# code. In other words I feel like I'm thinking in C# but writing in Python.
Am I really missing something?
(Note: I realize this isn't so much a programming question and it's quite broad and there may not be a definitive answer so mod me down into oblivion if you have to.) | I would recommend that you read up on [Generators, Iterators](http://www.ibm.com/developerworks/library/l-pycon.html), [`itertools`](http://www.ibm.com/developerworks/linux/library/l-cpyiter.html) and above all [List Comprehensions](http://docs.python.org/tutorial/datastructures.html).
These are the pillars of anything Pythonic. And for everything else, there is [PEP-8](http://www.python.org/dev/peps/pep-0008/).
Read up on these concepts and try using them wherever appropriate. All the best!
PS: Don't forget to `import this` ;)
**Addendum**: I would also aggregate some excellent suggestions given by others in this thread here:
* Read [Code Like a Pythonista: Idiomatic Python](http://python.net/~goodger/projects/pycon/2007/idiomatic/handout.html) (from [David Grant](https://stackoverflow.com/users/26829/david-grant))
* Solving problems from [Project Euler](http://projecteuler.net/) is a great idea (from [Nick Fortescue](https://stackoverflow.com/users/5346/nick-fortescue))
* [This excellent presentation](http://www.dabeaz.com/generators/) on Generators and Iterators by David Beazley (from [André](https://stackoverflow.com/users/9683/andr233))
* Learn about [Scons](http://www.scons.org/) (from the venerable [S.Lott](https://stackoverflow.com/users/10661/s-lott)) | No - this is common for folks who move to Python from other C-like languages. I believe what you are looking for is ways to make your code more ["Pythonic"](http://shalabh.infogami.com/Be_Pythonic2). The good news is the more Python you write the more Pythonic your code will become. It is a natural overflow of the "how can I do this more simply" attitude.
Another good place to look at is [The Zen of Python](http://www.python.org/dev/peps/pep-0020/). These attitudes towards Python development will also help you in the same regard. | Python: Am I missing something? | [
"",
"python",
""
] |
I am a novice with Regex usage in C#.
I want a regex to find the next keyword from a given list but which is not surrounded by the quotes.
e.g.
if i have a code which looks like:
```
while (t < 10)
{
string s = "get if stmt";
u = GetVal(t, s);
for(;u<8;u++)
{
t++;
}
}
```
i tried using the Regex as @"(.\*?)\s(FOR|WHILE|IF)\s"
but it gives me the "if" as next keyword.
whereas, i want to get the next keyword after while as "for" and not as "if" which is surrounded by quotes.
Can it be done in anyway using Regex? Or i will have to use conventional programming? | Try the following RegEx (**Edit:** fixed).
```
(?:[^\"]|(?:(?:.*?\"){2})*?)(?: |^)(?<kw>for|while|if)[ (]
```
Note: Because this RegEx literal includes quotes, you can't use the @ sign before the string. Remember that if you add any RegEx special chars to the string, you'll need to double-escape them appropiatlye (e.g. \w). Insure that you also specify the Multiline parameter when matching with the RegEx, so the caret (^) is treated as the start of a new line.
This hasn't been tested, but should do the job. Let me know if there's any problems. Also, depending on what more you want to do here, I might recommend using standard text-parsing (non-RegEx), as it will quickly become more readable depending on how much data you want to extract from the code. Hope that helps anyway.
**Edit:**
Here's some example code, which I've tested and am pretty confident that it works as intended.
```
var input = "while t < 10 loop\n s => 'this is if stmt'; for u in 8..12 loop \n}";
var pattern = "(?:[^\"]|(?:(?:.*?\"){2})*?)(?: |^)(?<kw>for|while|if)[ (]";
var matches = Regex.Matches(input, pattern);
var firstKeyword = matches[0].Groups["kw"].Value;
// The following line is a one-line solution for .NET 3.5/C# 3.0 to get an array of all found keywords.
var keywords = matches.Cast<Match>().Select(match => match.Groups["kw"].Value).ToArray();
```
Hopefully this should be your complete solution now... | If you decide to go the Regex route you can [use this site](http://www.nregex.com/nregex/default.aspx) to test your regular expression | Regex to match all except a string in quotes in C# | [
"",
"c#",
"regex",
""
] |
I'm a newbie to Eclipse and can't figure out how to get the JavaDocs for SWT and JFace to show up when I am editing.
How do I do this? Thanks! | I assume you've dowloaded the jars yourself and referenced them in your project. If so, you can right click the jar in the project explorer (in the 'Referenced Libraries' node) and click 'Properties'. The window that appears you can define the location of the jar's JavaDoc and source, if you have those available.
You can also reach this by clicking Project > Properties > Java Build Path > Libraries and expanding the node for the jar to which you want to add javadoc/source.
Also worth mentioning that if you use Maven (<http://maven.apache.org/>) for building your project, it's dependency management system will take care of finding sources and javadocs for you. But that's a different topic entirly. Also might be worth looking at Ivy (<http://ant.apache.org/ivy/>) - similar dependency management system, but can be used without selling your soul to Maven, I'm told.
---
You might also mean that you can't actually see the javadocs: Window > Show View > Other... > Java > JavaDoc. This view will show you the javadoc for whatever is currently in focus. Or just mouse over a method to see the javadoc in a popup. | Following the advice from ukulele, I was able to right click on the jar and set the javadoc location. In this case the location for the online javadoc was:
<http://help.eclipse.org/stable/nftopic/org.eclipse.platform.doc.isv/reference/api/>
Found from the SWT website:
<http://www.eclipse.org/swt/docs.php>
Thanks! | How to get JavaDoc for SWT and JFace in Eclipse? | [
"",
"java",
"eclipse",
"swt",
"javadoc",
"jface",
""
] |
I have to read business rules stored in XML file (I am using VC++/MFC/MSXML). XML consists of rules. Each rule has a set of conditions and actions. What would be an elegant OOP design for such system? What design patterns would you use if you where a designer of such system?
update:
Rules are put in sequence and executed one buy one if all conditions of rule are met.
example of xml:
```
<rules>
<!-- rule no. 1 -->
<rule name="rule no. 1">
<conditions>
<condition name="condition no. 1" type="ATTR_EMPTY">
<parameters>
<parameter name="attribute_name">ttt</parameter>
<parameter name="workflow_id">3</parameter>
<parameter name="workflow_state_id">5</parameter>
</parameters>
</condition>
<condition name="condition no. 2" type="ATTR_EMPTY">
<parameters>
<parameter name="attribute_name">ttt</parameter>
<parameter name="enviroment_id">3</parameter>
</parameters>
</condition>
</conditions>
<actions>
<action name="action no. 1" type="ATTR_CLEAR">
<parameters>
<parameter name="attribute_name">ttt</parameter>
</parameters>
</action>
</actions>
</rule>
</rules>
``` | Difficult to tell from such a brief description, but I would make each rule an object which manages its own conditions and actions. The rules would be created by a factory from the XML and stored in some sort of dictionary. | XML is really just the low level transport layer, is the any higher level format on top of it you using? That way you can get recommendations to specific libraries.
Edit:
OK a downvote so this wasn't the answer you were looking for.
You could probably get an oo design but you will need to post a snippet of the xml or a detailed specification. | Elegant way to read business rules stored in XML file | [
"",
"c++",
"xml",
"design-patterns",
""
] |
I've scoured the Web looking for examples on how to do this. I've found a few that seem to be a little more involved then they need to be. So my question is, using iTextSharp, is there a fairly concise way to append one PDF document to another one?
Optimally this would NOT involve a third file. Just open the first PDF doc, append the second PDF doc to the first and then close them both. | Ok, It's not straight forward, but it works and is surprisingly fast. (And it uses a 3rd file, no such thing as open and append.) I 'discovered' this in the docs/examples. Here's the code:
```
private void CombineMultiplePDFs( string[] fileNames, string outFile ) {
int pageOffset = 0;
ArrayList master = new ArrayList();
int f = 0;
Document document = null;
PdfCopy writer = null;
while ( f < fileNames.Length ) {
// we create a reader for a certain document
PdfReader reader = new PdfReader( fileNames[ f ] );
reader.ConsolidateNamedDestinations();
// we retrieve the total number of pages
int n = reader.NumberOfPages;
ArrayList bookmarks = SimpleBookmark.GetBookmark( reader );
if ( bookmarks != null ) {
if ( pageOffset != 0 ) {
SimpleBookmark.ShiftPageNumbers( bookmarks, pageOffset, null );
}
master.AddRange( bookmarks );
}
pageOffset += n;
if ( f == 0 ) {
// step 1: creation of a document-object
document = new Document( reader.GetPageSizeWithRotation( 1 ) );
// step 2: we create a writer that listens to the document
writer = new PdfCopy( document, new FileStream( outFile, FileMode.Create ) );
// step 3: we open the document
document.Open();
}
// step 4: we add content
for ( int i = 0; i < n; ) {
++i;
if ( writer != null ) {
PdfImportedPage page = writer.GetImportedPage( reader, i );
writer.AddPage( page );
}
}
PRAcroForm form = reader.AcroForm;
if ( form != null && writer != null ) {
writer.CopyAcroForm( reader );
}
f++;
}
if ( master.Count > 0 && writer != null ) {
writer.Outlines = master;
}
// step 5: we close the document
if ( document != null ) {
document.Close();
}
}
``` | I really may be missing something, but I did something much simpler. I concede this solution probably won't update bookmarks (as in the best answer here so far), but it works flawlessly for me. Since I was merging documents with fillable forms, I used PdfCopyFields instead of PdfCopy.
Here is the code (I've stripped all error handling to make the actual code more visible, add a try..finally to close opened resources if you plan on using the code):
```
void MergePdfStreams(List<Stream> Source, Stream Dest)
{
PdfCopyFields copy = new PdfCopyFields(Dest);
foreach (Stream source in Source)
{
PdfReader reader = new PdfReader(source);
copy.AddDocument(reader);
}
copy.Close();
}
```
You can pass any stream, be it a FileStream, a MemoryStream (useful when reading the PDF from databases, no need for temporary files, etc.)
Sample usage:
```
void TestMergePdfStreams()
{
List<Stream> sources = new List<Stream>()
{
new FileStream("template1.pdf", FileMode.Open),
new FileStream("template2.pdf", FileMode.Open),
new MemoryStream((byte[])someDataRow["PDF_COLUMN_NAME"])
};
MergePdfStreams(sources, new FileStream("MergedOutput.pdf", FileMode.Create));
}
``` | Is there a straight forward way to append one PDF doc to another using iTextSharp? | [
"",
"c#",
"pdf",
"itext",
""
] |
What is better between JSP and velocity in
- Performance
- Ease of use
- Ease of creating reusable components
- Availability of open source 3rd parties
- IDE support | Advantages of Velocity:
* strict separation of view from business logic
* simple syntax that can be understood by graphic designers | @Vartec:
I don't think that the "strict separation of view from business logic" is a velocity feature that is not present in jsp. You can do business logic in jsp (more or less) but it's not recommended at all. But I agree in your point regarding the syntax.
**Performance**
JSP is compiled to Java, so I don't think that velocity is faster. (have not done benchmarks myself)
**Ease of use**
For designers: velocity
For programmers: (IMHO) jsp, because it's closer to code
**Ease of creating reusable components**
JSP has lots of components
Velocity has no components itself (not component oriented)
**Availability of open source 3rd parties**
I have seen far more projects using JSP or JSP related technologies than velocity. Maybe because velocity is really low level... :-)
**IDE support**
There are plenty of tools for jsp. Especially the eclipse jboss plugin/tool suite has a good jsp editor.
Plugins for Velocity are mostly not functional or pretty basic (you get lucky if you have syntax highlighting)
**Update**
If you are looking for a templating engine now, I'd suggest to have a look at thymeleaf. It's comparably lightweight to velocity and can be used just to template some text based templates with a few lines of code or used as a full featured templating engine for example within a webapp. | JSP vs Velocity what is better? | [
"",
"java",
"jsp",
"velocity",
""
] |
Application requests KML data through AJAX from server. This data is stored in javascript variables, and displayed in Google Earth plugin.
In javascript, how do I provide a link to download the KML data stored in javascript variable (as a string) without requiring a request back to server?
This link:
<http://forum.mootools.net/viewtopic.php?id=9728>
suggests the use of data URI, but that probably won't work across enough browsers for my needs. Probably simplest just to go back to server to get data again for download, but curious if anyone has pulled this off with javascript. | Short answer: you can't and still be platform independent. Most browsers just don't allow javascript to manipulate the filesystem.
That said, you might be able to get away with some very platform-specific hacks. For example, IE offers the execCommand function, which you could use to call SaveAs. If you did that within an IFrame that had the data you wanted to save, you might get it working -- but only on IE. Other options (again, I'm going Microsoft specific here) include [this Silverlight hack](http://pagebrooks.com/archive/2008/07/16/save-file-dialog-in-silverlight.aspx), or ActiveX controls.
I think for full platform compatibility, you're just going to have to suck it up and provide a server-side download option.
[Edit]
Whoops! I didn't do enough due diligence when I went link-hunting. It turns out the Silverlight hack I linked to has a server-side component. Looks like you're pretty SOL.
[Edit2]
I found a nice summary of browser compatibility for execCommand [here](http://www.quirksmode.org/dom/execCommand.html). Although it lists question marks for the "saveas" command, maybe that might be a good route for you after all. Worth a try, perhaps?
[Edit3]
Well, I decided to do a proof of concept of the approach I suggested, and I got something fairly simple working in IE. Unfortunately, I proved in the process that this approach [will not work for Firefox](https://developer.mozilla.org/en/Rich-Text_Editing_in_Mozilla#Executing_Commands) and doesn't appear to work in Chrome/Safari, either. So it's very platform dependent. But it works! Here's a complete working page:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Javascript File Saver</title>
<script type="text/javascript">
function PageLoad() {
var fdoc = window.frames["Frame"].document;
fdoc.body.appendChild(fdoc.createTextNode("foo,bar,baz"));
}
function Save() {
var fdoc = window.frames["Frame"].document;
fdoc.execCommand("SaveAs", true);
}
</script>
</head>
<body onload="PageLoad();">
<h2>Javascript File Saver</h2>
<iframe id="Frame" style="width: 400px;">Noframe</iframe><br />
<button onclick="Save();">Save</button>
</body>
</html>
``` | This will work! It works for me.
[enter link description here](https://ourcodeworld.com/articles/read/189/how-to-create-a-file-and-generate-a-download-with-javascript-in-the-browser-without-a-server)
```
`function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
}
// Start file download.
download('hello.txt','This is the content of my file ');
`
``` | How do I download JavaScript string as a file | [
"",
"javascript",
"ajax",
"file-io",
""
] |
The company I work for has taken on a support contract for a large order processing system. As part of the initial system audit I noticed that the passwords stored in the database were actually the hashcode of the password.
Essentially:
```
string pwd = "some pasword";
string securePwd = pwd.GetHashCode();
```
My question is, how secure or otherwise is this?
I'm not comfortable with it, but I don't know enough about how GetHashCode works. I would prefer to use something like an MD5 hash, but if I'm wasting my time then I won't bother. | `GetHashCode` returns a 32 bit integer as the hash value. Considering the [birthday paradox](http://en.wikipedia.org/wiki/Birthday_paradox), it's not a long enough hash value due to the relatively high probability of collisions, even if it were explicitly designed to be collision resistant, which is not.
You should go for SHA256 or another cryptographically secure hash function designed to handle such a task.
To store passwords, just using a simple hash function is not enough. You should add some random "salt" per user and iterate enough times so that it would be computationally expensive to brute force. Therefore, you should use something like bcrypt, [scrypt](http://en.wikipedia.org/wiki/Scrypt), PBKDF2, with a large number of iterations. | You should use a salted, cryptographically strong hash, such as `SHA256Managed`.
Jeff Attwood has a few good posts on this topic:
[Rainbow Hash Cracking](http://www.codinghorror.com/blog/archives/000949.html)
[You're Probably Storing Passwords Incorrectly](http://www.codinghorror.com/blog/archives/000953.html) | Using GetHashCode to "secure" users passwords | [
"",
"c#",
".net",
"security",
"cryptography",
""
] |
How can I sort a List by order of case e.g.
* smtp:user@domain.com
* smtp:user@otherdomain.com
* SMTP:user@anotherdomain.com
I would like to sort so that the upper case record is first in the list e.g SMTP:user@anotherdomain.com. | You can use StringComparer.Ordinal to get a case sensitive sorting:
```
List<string> l = new List<string>();
l.Add("smtp:a");
l.Add("smtp:c");
l.Add("SMTP:b");
l.Sort(StringComparer.Ordinal);
``` | I was writing another example while t4rzsan has answered =) I prefer t4rzsan´s answer... anyway, this is the answer I was writing.
```
//Like ob says, you could create your custom string comparer
public class MyStringComparer : IComparer<string>
{
public int Compare(string x, string y)
{
// Return -1 if string x should be before string y
// Return 1 if string x should be after string y
// Return 0 if string x is the same string as y
}
}
```
Example of using your own string comparer:
```
public class Program
{
static void Main(string[] args)
{
List<string> MyList = new List<string>();
MyList.Add("smtp:user@domain.com");
MyList.Add("smtp:user@otherdomain.com");
MyList.Add("SMTP:user@anotherdomain.com");
MyList.Sort(new MyStringComparer());
foreach (string s in MyList)
{
Console.WriteLine(s);
}
Console.ReadLine();
}
}
``` | Sorting a list based on string case | [
"",
"c#",
"sorting",
"list",
""
] |
I have a PHP web app located on **shared hosting**.
My goal is to modify .htaccess file from PHP code when the PHP page is running.
I need that .htaccess to insert a couple of mod\_rewrite lines into it.
The problem is that on Windows+Apache I can dynamically modify .htaccess file
but the same code on Linux reports a problem when I try to access this file in any
way (copy or fopen):
`"failed to open stream: Permission denied"`
I have given .htaccess file 777 permissions - still no result.
WHat prevents me from doing this? How can I develop a workaround?
P.S.
My initial goal was to be able to add a new RewriteRule into .htaccess that maps a
newly added category\_id with new category\_name.
If it wasn't shared hosting, I would use something like RewriteMap (in main Apache config) and would be able to access the map file.
This is the first real limitation I've been unable to tackle with PHP+Apache, but I hope it's circuventable too. | I want to suggest something else that also works. Instead of writing a rule for every 'special' url, why not use one for all?
I found it a whole lot easier to use what wordpress uses: every url is redirected to the index.
All you have to do is, set up the index file, read in the directory that was loaded (perhaps using $\_SERVER['URI\_REQUEST']), and deal with it.
add to .htaccess this:
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
```
Thanks to that chunck you have a system somewhat unlimited at your disposal. If you ever feel like renaming you categrory url, or add another special case, it's already ready! | This seems like an overly-complex solution to just having a general "load category" page that takes the category name from the URL and loads the corresponding ID.
For example, if the URL is:
```
http://yoursite.com/category/programming
```
I would remap that to something like:
```
http://yoursite.com/category.php?name=programming
``` | Is PHP allowed to modify .htaccess file in current folder? | [
"",
"php",
"apache",
".htaccess",
"mod-rewrite",
"permissions",
""
] |
I have a simple C# function:
```
public static double Floor(double value, double step)
{
return Math.Floor(value / step) * step;
}
```
That calculates the higher number, lower than or equal to "value", that is multiple of "step". But it lacks precision, as seen in the following tests:
```
[TestMethod()]
public void FloorTest()
{
int decimals = 6;
double value = 5F;
double step = 2F;
double expected = 4F;
double actual = Class.Floor(value, step);
Assert.AreEqual(expected, actual);
value = -11.5F;
step = 1.1F;
expected = -12.1F;
actual = Class.Floor(value, step);
Assert.AreEqual(Math.Round(expected, decimals),Math.Round(actual, decimals));
Assert.AreEqual(expected, actual);
}
```
The first and second asserts are ok, but the third fails, because the result is only equal until the 6th decimal place. Why is that? Is there any way to correct this?
**Update** If I debug the test I see that the values are equal until the 8th decimal place instead of the 6th, maybe because Math.Round introduces some imprecision.
**Note** In my test code I wrote the "F" suffix (explicit float constant) where I meant "D" (double), so if I change that I can have more precision. | If you omit all the F postfixes (ie `-12.1` instead of `-12.1F`) you will get equality to a few digits more. Your constants (and especially the expected values) are now floats because of the `F`. If you are doing that on purpose then please explain.
But for the rest i concur with the other answers on comparing double or float values for equality, it's just not reliable. | I actually sort of wish they hadn't implemented the == operator for floats and doubles. It's almost always the wrong thing to do to ever ask if a double or a float is equal to any other value. | Double precision problems on .NET | [
"",
"c#",
".net",
"math",
"double",
""
] |
I am looking for a java port of this file,
[Jenkins Hash in C](http://burtleburtle.net/bob/c/lookup2.c) | [This](http://256stuff.com/sources/jenkins_hash_java/) looks like one.
Though, by the looks of description on the Wikipedia article you could port it yourself without too much trouble. | [Hsieh's hash](http://www.azillionmonkeys.com/qed/hash.html) is even better. I don't know of a java implementation - i'm writing one right now. | Java port of Hash by Jenkins | [
"",
"java",
"hash",
""
] |
I'm working on a project that is going to make heavy use of JBoss Messaging (JMS). I'm tasked with building an easy to use wrapper around Messaging for other developers and am thinking about using JMS's Message Selectors to provide a filtering technique to keep unnecessary sending of messages to a minimum. I'm curious if anyone has any experience with doing so in regards to performance? My fear is that the JMS provider may get bogged down with the Message Selectors, effectively defeating the whole purpose. It would be much nicer however than creating a long list of Topics/Queues for every message type.
Ultimately I'll undoubtedly end up using some combination of the two, but am concerned with the impact on performance whichever way I lean more towards. | As Martin mentioned, by default most JMS implementations will process message selectors on the client, *unless* they are part of a durable subscription, when *most* JMS implementations will process them on the server as well to avoid too many messages getting persisted when there's a significant reduction in the number of messages that get past the selector. Some systems (like SonicMQ) allow you to specify that message selectors should be processed on the server, which is a good option in a case where you have excess CPU available on your message brokers but not on your consumers.
Bear in mind that while topic-based selection is usually faster, it can be quite cumbersome, because if you want to listen to 5 different things, you have to have 5 different MessageConsumers. Each of those in a naive driver implementation is a different thread, and that can start to add up. For that reason, it is often useful to support both from publication so that some clients can listen only to the topics that they want, and others can listen to the topic hierarchies they want (e.g. foo.#) with message selectors (or code-based selectors).
However, **you should always test against your application and your broker**. Every broker handles the situation differently, and every application functions differently. You can't just say "always use technique X" because each technique for client-directed message processing has different tradeoffs. Benchmark, benchmark, benchmark.
One thing to bear in mind with message selectors is that they aren't dynamically changeable, so you have the possibility of losing messages or having to manually manage a complicated switchover scenario. Imagine the following use case:
1. You are listening to a message selector of the form (Ticker in ('CSCO', 'MSFT'))
2. User wants to start listening to AAPL
3. You have to shut down the old MessageConsumer and start a new one with a selector in the form (Ticker in ('CSCO, 'MSFT', 'AAPL'))
4. During the switchover, you either lose messages (because you shut down the old one before starting the new one) or you have to manually remove duplicates (because you have the new one started before the old one) | My two cents:
I asked myself exactly the same question concerning ActiveMQ.
* First, I did not use selectors and created lots of topics. Performance was horrible as the broker could not handle 100's of topics without a lot of resources.
* then I used a combination of topics/selectors. I now have a small number of topics. The selection works well. But the load is not very heavy, no more than 10 msg/s
I did develop an abstraction layer, allowing the developers to code without asking questions, and we did tests by switching the implementations. | JMS Messaging Performance: Lots of Topics/Queues vs. Extensive Filtering (Message Selectors) | [
"",
"java",
"performance",
"jboss",
"jms",
"messaging",
""
] |
I have a `byte[]` that is represented by an `Image`. I am downloading this `Image` via a `WebClient`. When the `WebClient` has downloaded the picture and I reference it using its URL, I get a `byte[]`. My question is, how do I load a `byte[]` into an `Image` element in WPF? Thank you.
*Note*: This is complementary to the question I asked here: [Generate Image at Runtime](https://stackoverflow.com/questions/580359/generate-image-at-runtime). I cannot seem to get that approach to work, so I am trying a different approach. | You can use a [`BitmapImage`](http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx), and sets its [`StreamSource`](http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.streamsource.aspx) to a stream containing the binary data. If you want to make a `stream` from a `byte[]`, use a [`MemoryStream`](http://msdn.microsoft.com/en-us/library/system.io.memorystream.aspx):
```
MemoryStream stream = new MemoryStream(bytes);
``` | Create a `BitmapImage` from the `MemoryStream` as below:
```
MemoryStream byteStream = new MemoryStream(bytes);
BitmapImage image = new BitmapImage();
image.BeginInit();
image.StreamSource = byteStream;
image.EndInit();
```
And in XAML you can create an `Image` control and set the above `image` as the **`Source`** property. | Load a byte[] into an Image at Runtime | [
"",
"c#",
"wpf",
"image",
""
] |
You can do this with JavaScript:
```
function bar(test) {
alert(test);
}
var foo = bar;
foo('hi');
```
I'd like to be able to do something similar with a jQuery event:
```
var foo = $('#bork').click;
foo(function() { alert('I was just clicked.'); });
```
However, I get an error when the page loads: `this.bind is not a function`. Am I doing something wrong with the events here? Is there a better way to get the same effect? | ```
$('#bork').bind('click', foo);
function foo() { alert('i was just clicked'); }
``` | The other answers don't seem to be addressing the technical question:
Why does this work:
```
$('#bork').click(function() { alert('I was just clicked.'); });
```
But not this:
```
var foo = $('#bork').click;
foo(function() { alert('I was just clicked.'); });
```
The two appear to be the same, but the problem is that "`this`" within the implementation of the `click` function refers to the jQuery object in the first example, but it refers to `foo` in the second example. Since you have not defined `foo.bind`, the call to "`this.bind`" in the implementation of `click` fails.
Here is [a great article about the ins and outs of binding/scoping in Javascript](http://www.alistapart.com/articles/getoutbindingsituations). | Passing a jQuery event as a variable | [
"",
"javascript",
"jquery",
""
] |
We have to add a basic HTML editor to our product. As we only support IE at present (most customers are still on IE 6), I have been told to use the Internet Explorer built-in XHTML editing capabilities – e.g. `<div contentEditable="true">` as explained at "[Editing a Web Page](http://www.maconstateit.net/tutorials/JSDHTML/JSDHTML12/jsdhtml12-02.htm)" .
**Apart** from not working in other browsers. (The management does not consider it being a problem. Our customers will put up with our software only working with IE. We have never lost any money by our software only working in IE; most customers will only let their staff use IE6 at present anyway)
What **other** problem are we likely to get with contentEditable?
---
**Update**
The HTML editor I wrote with “contentEditable” proved to very hard to get reliable, with many [problems](https://stackoverflow.com/questions/527866/why-is-contenteditable-removing-id-from-div). If I had to do this again, I would push **very hard** to one of the many open source solutions (e.g. TinyMCE) or buy in a supported HTML editor.
No doubt that a very skilled jscript programmer can get “contentEditable” to work well given enough time. It just that all the examples on the web looks so simple, until you test common operations like doing a cut/paste from word and trying to edit the resulting HTML. (just the sort of things a customer will do)
(Just search for “contentEditable” on stackoverflow to get some ideal of the problems other people have had) | The contentEditable property works in Safari, Firefox 3, and Opera 9.
Since manipulation will undoubtably be through selections, your biggest problem will be getting the selection/ranges working across browsers ([see here)](https://stackoverflow.com/questions/361130/get-selected-text-and-selected-nodes-on-a-page/364476#364476).
There are also numerous [little bugs](https://bugzilla.mozilla.org/show_bug.cgi?id=454191) across browsers which may or may not bite you. These include incompatible case-sensitivity, incompatible methods of turning it off again (removeAttribute vs. setting to false).
Despite these flaws, I find it works rather well. | How about using some open-source solution that works in all major browsers?
[TinyMCE](http://tinymce.moxiecode.com/)
There are other projects as well, but that's what I'd use. | Risk of using contentEditable in IE | [
"",
"javascript",
"html",
"internet-explorer",
"contenteditable",
""
] |
I have a query that takes too long and frequently times out. It's a proximity based zip code search table-value function. Is there anyway to index based on the query, so it doesn't have to recalculate all of these values every time? The postal code and zip code list combined is over a million rows.
Here is the table function.
```
Create FUNCTION [dbo].[ZipsInRadius] (@zipCode varchar(15),
@radius int, @unit char(1))
RETURNS @areaResults TABLE(
Zip varchar (30),
City varchar (255),
St varchar (20),
Lat decimal (16,12),
Long decimal (16,12))
BEGIN
DECLARE @iStartLat decimal(16, 12)
DECLARE @iStartLong decimal(16, 12)
SELECT
@iStartLat = CAST(Latitude AS decimal(16, 12)),
@iStartLong = CAST(Longitude AS decimal(16, 12))
FROM zip
WHERE zipcode LIKE @zipCode + '%'
SELECT
@iStartLat = CAST(Latitude AS decimal(16, 12)),
@iStartLong = CAST(Longitude AS decimal(16, 12))
FROM postalcode
WHERE postalcode LIKE @zipCode + '%'
DECLARE @latRange decimal(16, 12)
DECLARE @longRange decimal(16, 12)
IF (@unit = 'K') --Get distance in kilometers
BEGIN
SELECT @LatRange =
(CAST(@radius / ((6076.0 / 5280.0) * 60.0)
AS decimal(16, 12))) * 0.621371
SELECT @LongRange =
(@radius / (((cos(@iStartLat * pi() / 180.0) * 6076.0)
/ 5280.0) * 60)) * 0.621371
END
ELSE --Get distance in miles (the default)
BEGIN
SELECT @LatRange = CAST(@radius / ((6076.0 / 5280.0) * 60.0)
AS decimal(16, 12))
SELECT @LongRange =
@radius / (((cos(@iStartLat * pi() / 180.0) * 6076.0)
/ 5280.0) * 60)
END
DECLARE @lowLatitude decimal(16, 12)
DECLARE @highLatitude decimal(16, 12)
DECLARE @lowLongitude decimal (16, 12)
DECLARE @highLongitude decimal (16, 12)
SELECT @lowLatitude = @iStartLat - @latRange
SELECT @highLatitude = @iStartLat + @latRange
SELECT @lowLongitude = @iStartLong - @longRange
SELECT @highLongitude = @iStartLong + @longRange
INSERT INTO @areaResults (zip, city, st, lat, long)
SELECT ZIPcode, CITY, STate, LATitude, LONGitude
FROM Zip Z
WHERE Z.Latitude <= @highLatitude
AND Z.Latitude >= @lowLatitude
AND Z.Longitude >= @lowLongitude
AND Z.Longitude <= @highLongitude
INSERT INTO @areaResults (zip, city, st, lat, long)
SELECT postalcode, CITY, province, LATitude, LONGitude
FROM postalcode z
WHERE Z.Latitude <= @highLatitude
AND Z.Latitude >= @lowLatitude
AND Z.Longitude >= @lowLongitude
AND Z.Longitude <= @highLongitude
RETURN
END
``` | I would recommend an multi-column index on Longitude and Latitude.
It's good that you are using a bounding box, which would ordinarily speed up your query. With the index I mention, you should see huge improvements.
On a side note, you have your latitude/longitudes stored in a Decimal(16,12). 12 digits of precision is probably TONS more than you need. The fifth digit (in lat/long units) represents approximately 3 feet. so.. the 12th digit might actually represent nano-meters (or less). By using a smaller data type, your tables (and indexes) will be more efficient. This is especially true with zip code searchs because the lat/longs you have are a point representing the center of a zip code, the position isn't very exact to begin with. For longitude, I usually use Decimal(8,5). Since Latitude is usually in the range -90 to 90, you can get away with Decimal(7,5) for latitude. | It takes me milliseconds, maybe your approach is wrong take a look here: [SQL Server Zipcode Latitude/Longitude proximity distance search](http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/sql-server-zipcode-latitude-longitude-pr) 2000/2005 version
or for the 2008 version by using the geography datatype here: [SQL Server 2008 Proximity Search With The Geography Data Type](http://blogs.lessthandot.com/index.php/DataMgmt/DataDesign/sql-server-2008-proximity-search-with-th) | Indexing on a query | [
"",
"sql",
""
] |
I'm a bit of newbie to c#/.net development, but I've put together a stock tracking application for a small set of assets in my company. I have also set up the database it connects to in SQL 2000.
It currently works brilliantly when a network connection is available, but I want to expand it for use when I'm away from a connection.
First off I'll need to know if there's a connection available. So I put this together:
```
private int availableNetAdapters()
{
int nicCount = 0;
foreach (NetworkInterface nic in NetworkInterface.GetAllNetworkInterfaces())
{
if (nic.OperationalStatus == OperationalStatus.Up)
{
nicCount++;
}
}
return nicCount;
}
```
Seems to work, but I have to test for ">1" as something as "MS TCP Loopback interface" is always detected regardless of the other adapter sates.
Is there a better/easier way to check connectivity?
G | `System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()`
You can also use the events `NetworkAvailabilityChanged` and `NetworkAddressChanged` in that class to monitor IP address and network availability changes.
EDIT: Be aware that this method checks all available network interfaces that may be on the computer (wireless, lan, etc.). If anyone of them is connected, it will return true. | Some more things to remember:
* Avaialable Network connection != Available internet connection.
* Internet Access != access to a specific web site (think proxy filters, or the site could just be down)
Therefore it's generally best to test for access to the specific resource you need directly.
These resources are volatile; you have to handle the exception when they go down anyway. So it's generally best to just go get a resource as if you know for sure it exists and put your development time in to making sure your exception handler does a nice job with the failures. | What's the easiest way to verify there's an available network connection? | [
"",
"c#",
".net",
".net-2.0",
"networking",
""
] |
I've heard the latest PHP has support for namespaces. I know variables defined in the global scope have *no* namespace, so how does one make a variable in a different namespace?
Is it just a way of categorising variables/functions? | Namespaces are a programming language mechanism for organizing variables, functions and classes. PHP 5.3 adds support for namespaces, which I'll demonstrate in the following example:
Say you would like to combine two projects which use the same class name **User**, but have different implementations of each:
```
// Code for Project One (proj1.php)
<?php
class User {
protected $userId;
public function getUserId() {
return $this->userId;
}
}
$user = new User;
echo $user->getUserId();
?>
// Code for Project Two (proj2.php)
<?php
class User {
public $user_id;
}
$user = new User;
echo $user->user_id;
?>
<?php
// Combine the two projects
require 'proj1.php';
require 'proj2.php'; // Naming collision!
$myUser = new User; // Which class to use?
?>
```
For versions of PHP less than 5.3, you would have to go through the trouble of changing the class name for all instances of the class **User** used by one of the projects to prevent a naming collision:
```
<?php
class ProjectOne_User {
// ...
}
$user = new ProjectOne_User; // Code in Project One has to be changed too
?>
```
For versions of PHP greater than or equal to 5.3, you can use namespaces when creating a project, by adding a namespace declaration:
```
<?php
// Code for Project One (proj1.php)
namespace ProjectOne;
class User {
// ...
}
$user = new User;
?>
<?php
// Combine the two projects
require 'proj1.php';
use ProjectOne as One; // Declare namespace to use
require 'proj2.php' // No collision!
$user = new \One\User; // State which version of User class to use (using fully qualified namespace)
echo $user->user_id; // Use ProjectOne implementation
?>
```
For more information:
* [PHP.net Namespaces](http://us.php.net/language.namespaces)
* [PHP Namespaces](http://blog.agoraproduction.com/index.php?/archives/47-PHP-Namespaces-Part-1-Basic-usage-gotchas.html) | A [namespace](http://www.php.net/manual/en/language.namespaces.php) allows you to organize code and gives you a way to encapsulate your items.
You can visualize namespaces as a file system uses directories to group related files.
Basically namespaces provide you a way in which to group related classes, functions and constants.
They also help to avoid name collisions between your PHP classes/functions/constants, and improve the code readability, avoiding extra-long class names.
Example namespace declaration:
```
<?php
namespace MyProject;
const CONNECT_OK = 1;
class Connection { /* ... */ }
function connect() { /* ... */ }
?>
``` | What is a namespace and how is it implemented in PHP? | [
"",
"php",
"namespaces",
""
] |
I have created a small game, in which some blocks are move around a main div. The mouse which also holding a div (I had assigned the position of cursor to that div).
I just want to trace out, whether the cursor div is moving over the blocks(those are also div). If it comes like that then the game will be over.
How can I detect whether the block or cursor div moves over each other? | If you're using jQuery, you can find the left, top, width and height of a div by using these:
```
$(myDiv).offset().left
$(myDiv).offset().top
myDiv.offsetWidth
myDiv.offsetHeight
```
Use those to work out the left, right, top and bottom of each div. Then two divs overlap each other if:
```
left1 < right2 && left2 < right1 && top1 < bottom2 && top2 < bottom1
``` | This is not a straightforward task using plain javascript, because you have to trace the div's ancestry and sum the relative positions until you find an absolutely positioned div.
On the other hand, this task is quite trivial with a javascript library such as jQuery or Prototype. In jQuery, for example, [`$(myDiv).offset()`](http://docs.jquery.com/CSS) returns the div's position relative to the document.
If you also include [jQuery UI](http://docs.jquery.com/UI/), and make your main div a "Draggable", and all other divs "Droppable", all you need is hook up on the [Droppable's over event](http://docs.jquery.com/UI/API/1.7/Droppable#events) to get notified when the main div is dragged over the other one. | Detecting the position of a div | [
"",
"javascript",
"html",
""
] |
I'm looking for an optimization library. My two requirements are that it does not use JNI and that it does not have license restrictions preventing it from being used on multiple computers commercially.
The only one I've found that meets these requirements is Choco, but it is unusably buggy. | Since I couldn't find any optimization software in Java I wrote my own implementation of the Simplex Method and submitted it to Apache Commons Math library: <https://issues.apache.org/jira/browse/MATH-246> | <http://ojalgo.org/generated/org/ojalgo/optimisation/linear/LinearSolver.html> | Java Library? - Simplex / Linear Programming / Optimization | [
"",
"java",
"mathematical-optimization",
"linear-programming",
""
] |
I'm writing an asp.net mvc app and I've get a list of service calls that I display in a table. When the user clicks the table header I want to tell my controller to sort the list by that column.
```
public ActionResult Index(int? page, string sortBy, string sortDirection)
{
int pageIndex = page == null ? 0 : (int)page - 1;
IServiceCallService scService = new ServiceCallService();
IPagedList<ServiceCall> serviceCalls = scService.GetOpenServiceCalls("").ToPagedList(pageIndex, 2);
return View("List", serviceCalls);
}
```
How do I incorporate the sortBy and sortDirection. I think I could do something like:
```
IPagedList<ServiceCall> serviceCalls = sc.Service.GetOpenServiceCalls("").OrderBy(sortBy).ToPagedList(pageIndex, 2);
```
But that doesn't work because I assume OrderBy wants a lambda like p => p.CreateDate but not sure how to do this.
I know ways I could do it but they are ugly and I'm sure C# has something simple here that I'm just missing.
Thanks. | Don't forget about the handy-dandy DataBinder:
```
var serviceCalls = sc.Service.GetOpenServiceCalls("").OrderBy(call => DataBinder.Eval(call, sortBy));
return serviceCalls.ToPagedList(pageIndex, 2);
```
DataBinder.Eval from Msdn docs
> Uses reflection to parse and evaluate
> a data-binding expression again an
> object at run time. | You could also use leverage jQuery and use something like [Table Sorter](http://tablesorter.com/ "TableSorter") if you're just looking to sort the list. It'd also be real time and all ajax-y. | How can I sort a List<T> when the user clicks on a table header? | [
"",
"c#",
"asp.net",
"asp.net-mvc",
"sorting",
""
] |
If class `B` and class `C` extend class `A` and I have an object of type `B` or `C`, how can I determine of which type it is an instance? | ```
if (obj instanceof C) {
//your code
}
``` | Use [`Object.getClass`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/Object.html#getClass()). It returns the runtime type of the object. Here's how to call it using your example:
```
class A {}
class B extends A {}
class C extends A {}
class Main {
public static void main(String args[]) {
C c = new C();
Class clazz = c.getClass();
System.out.println(clazz);
}
}
```
Output:
```
class C
```
You can also compare two `Class` instances to see if two objects are the same type.
```
class A {}
class B extends A {}
class C extends A {}
class Main {
public static void main(String args[]) {
B b = new B();
Class c1 = b.getClass();
C c = new C();
Class c2 = c.getClass();
System.out.println(c1 == c2);
}
}
``` | How to determine an object's class? | [
"",
"java",
"inheritance",
""
] |
Assume that I have a dropdownlist with 2 items and, by default, the first item is selected. If I select the click the first item in the dropdownlist, is there a way I can get the SelectedIndexChanged() event to still fire?
I thought I could do it by setting the SelectedIndex of the dropdownlist to -1, but that didn't work, because it does not display the currently selected value, so it is misleading.
An issue I have on this is that the dropdownlist is used for sorting. I have the sorting semi-working in that if I select the second item, it will sort in ascending order for example, but if I want to sort in descending order now using the second item, I have to select another item and then go back to the second item.
Even if I add a Select By, I think the best solution to sorting is to just have more items in the dropdownlist like:
Sort Numbers (Asc)
Sort Numbers (Desc)
Sort Alphabet (Asc)
Sort Alphabet (Desc) | Note: This is based on the updated content of the question.
Let's say you have one drop down list and one listbox (dropdownlist1 and listbox1)
You can set up your initial drop down list in your page\_load event as such:
```
dropdownlist1.items.insert(0, "----Select Sort Method----")
dropdownlist1.items.insert(1, new ListItem("Alphabetic Ascending", "AlphaAsc"))
dropdownlist1.items.insert(2, new ListItem("Alphabetic Descending", "AlphaDesc"))
dropdownlist1.items.insert(3, new ListItem("Numeric Ascending", "NumAsc"))
dropdownlist1.items.insert(4, new ListItem("Numeric Descending", "NumDesc"))
dropdownlist1.selectedindex = 0
```
Then on your dropdownlist1.selectedindexchanged event you would handle it as such:
```
if dropdownlist1.selectedindex <> 0 then
select case dropdownlist1.selectedvalue
case "AlphaAsc"
Insert Code to Sort ListBox1 Alphabetically in ascending order
case "AlphaDesc"
Insert Code to sort ListBox1 Alphabetically in descending order
case "NumAsc"
Insert code to sort ListBox1 Numerically in ascending order
case "NumDesc"
Insert code to sort ListBox1 Numerically in descending order
end select
end if
```
Note: You would want to make sure that your dropdownlist1's AutoPostBack property is set to true if you want the sorting to happen immediately upon selection of an item. | Unfortunately no: the event will only fire if the user changes the selection from one item to another.
You might consider adding an item with the text "Please select..." to the top of your list. | SelectedIndexChanged event does not fire if Item is already selected in a dropdownlist? | [
"",
"c#",
"asp.net",
""
] |
I have a remoting application (2 player Magic the Gathering Game) using windows form in C# and I am seeing very poor
performance in mono. One thing I can think of that might affect the performance is that I have custom images for button background and form backgrounds(.png). Moreover I heavily use card images (.jpg). Lastly I have stuck very strictly to .NET 2.0.
What can I look for to improve windows Form performance in mono? If this is not possible is there a quick winforms to gtk# converter or tool that helps in converting? | Did you try to [profile your code](http://www.mono-project.com/Performance_Tips). Maybe that shows you where the bottlenecks are...
I think one big problem is
> Whereas the .Net implementation is a
> binding to the Win32 toolkit, the Mono
> implementation is written in C# to
> allow it to work on multiple platforms
as mentioned [here](http://www.mono-project.com/Gui_Toolkits) and
> System.Windows.Forms in Mono is
> implemented using System.Drawing. All
> controls are natively drawn through
> System.Drawing. System.Windows.Forms
> implements its own driver interface to
> communicate with the host OS windowing
> system.
as described [here](http://www.mono-project.com/WinForms).
I don't know of a converter from winforms to gtk#..., but if you really want to bother with converting your game to gtk#, [this](http://mono-project.com/GtkSharpTutorials) might be a good starting point. | It would be useful if you could detail exactly what the performance problems are that you are observing.
Mono's Windows.Forms implementation is a bit slower today due to some of the requirements imposed by trying to support the WndProc model embedded into it properly.
It is an area that could be improved and likely many of the lessons from Wine could be applied to Mono's Winforms implementation. | How do I improve performance of winforms application in Mono? | [
"",
"c#",
"winforms",
"performance",
"mono",
"gtk#",
""
] |
I have a class (say `MyClass`) that uses (has as a private field) a `TcpClient` object. `MyClass` implements `IDisposable` calling `TcpClient.Close` in the `Dispose` method.
My question is should `MyClass` also implement a finalizer to call `Dispose(bool Disposing)` to free the `TcpClient’s` unmanaged resources in case `MyClass.Dispose` is not called by the calling code?
Thanks | **No you shouldn't.**
Because **you should never call a method on an other object in a finalizer**, it could have been finalized before your object.
The finalizer of your TcpClient will be called by the garbage collector, so let him do.
The pattern in Dispose is :
```
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
// dispose managed resources (here your TcpClient)
}
// dispose your unmanaged resources
// handles etc using static interop methods.
}
``` | No you shouldn't.
From [this](http://blogs.msdn.com/bclteam/archive/2007/10/30/dispose-pattern-and-object-lifetime-brian-grunkemeyer.aspx) excellent post:
> Finalization is fundamentally
> different from ending an object’s
> lifetime. From a correctness point of
> view, there is no ordering between
> finalizers (outside of a special case
> for critical finalizers), so if you
> have two objects that the GC thinks
> are dead at the same time, you cannot
> predict which finalizer will complete
> first. This means you can’t have a
> finalizer that interacts with any
> finalizable objects stored in instance
> variables.
This is my reference implementation of the disposable/finalize pattern with comments explaining when to use what:
```
/// <summary>
/// Example of how to implement the dispose pattern.
/// </summary>
public class PerfectDisposableClass : IDisposable
{
/// <summary>
/// Type constructor.
/// </summary>
public PerfectDisposableClass()
{
Console.WriteLine( "Constructing" );
}
/// <summary>
/// Dispose method, disposes resources and suppresses finalization.
/// </summary>
public void Dispose()
{
Dispose( true );
GC.SuppressFinalize(this);
}
/// <summary>
/// Disposes resources used by class.
/// </summary>
/// <param name="disposing">
/// True if called from user code, false if called from finalizer.
/// When true will also call dispose for any managed objects.
/// </param>
protected virtual void Dispose(bool disposing)
{
Console.WriteLine( "Dispose(bool disposing) called, disposing = {0}", disposing );
if (disposing)
{
// Call dispose here for any managed objects (use lock if thread safety required), e.g.
//
// if( myManagedObject != null )
// {
// myManagedObject.Dispose();
// myManagedObject = null;
// }
}
}
/// <summary>
/// Called by the finalizer. Note that if <see cref="Dispose()"/> has been called then finalization will
/// have been suspended and therefore never called.
/// </summary>
/// <remarks>
/// This is a safety net to ensure that our resources (managed and unmanaged) are cleaned up after usage as
/// we can guarantee that the finalizer will be called at some point providing <see cref="Dispose()"/> is
/// not called.
/// Adding a finalizer, however, IS EXPENSIVE. So only add if using unmanaged resources (and even then try
/// and avoid a finalizer by using <see cref="SafeHandle"/>).
/// </remarks>
~PerfectDisposableClass()
{
Dispose(false);
}
}
``` | Need to implement a finalizer on a class that uses TcpClient? | [
"",
"c#",
"idisposable",
"finalizer",
"unmanagedresources",
""
] |
I'm using Qt Jambi 4.4 for a project I'm working on (and designing the windows in the Qt Designer eclipse plugin). One of the windows I'd like to use is a preview window which is basically just a window with a QWebView on it. How can I make it so that the QWebView resizes as the window does? I've set the sizePolicy to expanding for both Horizontal and Vertical position. What else do I need to do?
(also bear in mind that I'm a newbie to both Java and eclipse and need to be talked to in stupid people terms on both of those subjects)
**UPDATE**
Just to illustrate the point, here are a couple of screenshots (I've made the window background bright just to illustrate my point):
[alt text http://img13.imageshack.us/img13/2103/screenshot2oi7.jpg](http://img13.imageshack.us/img13/2103/screenshot2oi7.jpg)
[alt text http://img152.imageshack.us/img152/6250/screenshot1mz9.jpg](http://img152.imageshack.us/img152/6250/screenshot1mz9.jpg) | I don't know Jambi, but with Qt Designer just give the background the focus and then apply a layout from the toolbar. Then the main widget will get resized by that layout manager -- if you don't add that layout manager you'll get the widget resizing but the contents staying at their old positions. | I haven't used qt-jambi, but if it is anything like Qt in C++ or PyQt, the QWebView would resize automatically as the window size changes. As far as I know, setting size policies/ expansion factors, adding QSpacerItem objects etc. is only necessary if the sizing behavior is not working right. Just laying it out using an appropriate layout within the preview window should be sufficient. Do let me know if I have misunderstood the question. | How do I make controls autosizing in Qt designer? | [
"",
"java",
"user-interface",
"qt",
"qt-jambi",
""
] |
Recently i moved to office 2007. im trying to import excel file to sql server 2000 using import and export data tool ,the tool gave data source as excel 97 - 2000 but while importing xlsx file ,im getting error "Error source Microsoft Jet databse Engine", external table is not in the expected format. Can you tell me how can i import office excel file xlsx to sql server 2000 using import and export data tool.
Appreciate your prompt comments | I agree with "schooner", the easiest way to import Excel 2007 into SQL 2K is to save the excel document into a 97-2003 format. | You could use an OLEDB connection, assuming DTS supports it. It's been a while since I've used it, so I can't remember. Connection looks something like this: Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\myFolder\myExcel2007file.xlsx;Extended Properties="Excel 12.0 Xml;HDR=YES";
If your DTS server doesn't have Office installed you'll need to install the drivers:
<http://www.microsoft.com/downloads/details.aspx?familyid=7554F536-8C28-4598-9B72-EF94E038C891&displaylang=en> | How can import xlsx file to Sql server 2000 | [
"",
"sql",
"sql-server",
""
] |
I'm looking for a tool or a script that will take the console log from my web app, parse out the garbage collection information and display it in a meaningful way.
I'm starting up on a Sun Java 1.4.2 JVM with the following flags:
```
-verbose:gc -XX:+PrintGCTimeStamps -XX:+PrintGCDetails
```
The log output looks like this:
```
54.736: [Full GC 54.737: [Tenured: 172798K->18092K(174784K), 2.3792658 secs] 257598K->18092K(259584K), [Perm : 20476K->20476K(20480K)], 2.4715398 secs]
```
Making sense of a few hundred of these kinds of log entries would be much easier if I had a tool that would visually graph garbage collection trends. | IBM's GC toolkit does exactly what you ask.
<https://www.ibm.com/developerworks/java/jdk/tools/gcmv/>
I'm not sure if it's compatible with GC logs from Sun's JVM though. | [gcviewer](http://www.tagtraum.com/gcviewer.html) does what you want. | Know of any Java garbage collection log analysis tools? | [
"",
"java",
"performance",
"logging",
"garbage-collection",
""
] |
I have an "Estate" entity, and this entity has a collection "EstateFeatures"(type:EstateFeature) and EstateFeature has a property "MyFeatureValue".
*Note: These are the limited properties for the question. All Entities has an Id and all necesarry etc*
**Estate**
```
IList<EstateFeature> EstateFeatures;
```
**EstateFeature**
```
FeatureValue MyFeatureValue;
```
**FeatureValue**
```
public virtual long Id;
```
I am trying to get Real Estates which have the given FeatureValue.Id
```
DetachedCriteria query = DetachedCriteria.For<Estate>();
Conjunction and = new Conjuction();
foreach (var id in idCollection)
and.Add(Expression.Eq("MyFeatureValue.Id",id);
query
.CreateCriteria("EstateFeatures")
.Add(and);
IList<Estate> estates = query.GetExecutableCriteria(session).List<Estate>();
```
Nothing returned from this query, am i doing something wrong ?
Thanks | You will need to make sure that you join MyFeatureValue one time for each feature that you want your Estate to have.
One way is to call .CreateAlias for each iteration, give it a unique alias then add expression "aliasX.Id"
```
foreach (var id in idCollection)
{
query = query.CreateAlias("MyFeatureValue", "feature" + id)
.Add(Expression.Eq("feature" + id + ".Id",id);
}
```
Doesnt really recall how the syntax goes, wrote this out of my head, not sure if you need to redeclare query either :)
However, I think this will get you started.
EDIT: Since a bug in the Criteria API restrain you from associating a collection multiple times using CreateAlias or CreateCriteria, you need to resort to HQL.
<http://derek-says.blogspot.com/2008/06/duplicate-association-path-bug-in.html>
(Hibernate suffers from the same issue aswell)
```
select e
FROM Estate AS e
INNER JOIN e.MyFeatureValue AS fv1
INNER JOIN e.MyFeatureValue AS fv2
WHERE fv1.Id = 3
AND fv2.Id = 13
```
you will need to build the HQL dynamically so that your aliases becomes unique (fv1, fv2, fvX ...) | If I understand correctly I think something like this might work
```
CreateCriteria(typeof(Estate))
.CreateAlias("EstateFeatures", "estatefeature")
.Add(Restrictions.In("estatefeature.MyFeatureValue.Id", ids))
.List<Estate>();
``` | Querying on Collection with Nhibernate Criteria Api? | [
"",
"c#",
".net",
"nhibernate",
"criteria",
"icriteria",
""
] |
I haven't found a good reference for declaring my own functions inside the
```
jquery.ready(function(){});
```
I want to declare them so they are inside the same scope of the ready closure. I don't want to clutter the global js namespace so I don't want them declared outside of the ready closure because they will be specific to just the code inside.
So how does one declare such a function...and I'm not referring to a custom jquery extension method/function...just a regular 'ol function that does something trivial say like:
```
function multiple( a, b ){
return a * b;
}
```
I want to follow the jquery recommendation and function declaration syntax. I can get it to work by just declaring a function like the multiply one above...but it doesn't look correct to me for some reason so I guess I just need some guidance. | I believe that you would be okay just declaring the function inside the ready() closure, but here you can be a bit more explicit about the local scoping:
```
jQuery.ready(function() {
var myFunc = function() {
// do some stuff here
};
myFunc();
});
``` | It might sound simple but you just ... declare the function. Javascript allows functions to have inner functions.
```
$(document).ready( function() {
alert("hello! document is ready!");
function multiply(a, b) {
return a * b;
}
alert("3 times 5 is " + multiply(3, 5));
});
``` | Best practices for declaring functions inside jquery ready function | [
"",
"javascript",
"jquery",
""
] |
In templates, where and why do I have to put `typename` and `template` on dependent names?
What exactly are dependent names anyway?
I have the following code:
```
template <typename T, typename Tail> // Tail will be a UnionNode too.
struct UnionNode : public Tail {
// ...
template<typename U> struct inUnion {
// Q: where to add typename/template here?
typedef Tail::inUnion<U> dummy;
};
template< > struct inUnion<T> { };
};
template <typename T> // For the last node Tn.
struct UnionNode<T, void> {
// ...
template<typename U> struct inUnion; // intentionally not defined
template< > struct inUnion<T> { }; // specialization only for T
};
```
The problem I have is in the `typedef Tail::inUnion<U> dummy` line. I'm fairly certain that `inUnion` is a dependent name, and VC++ is quite right in choking on it.
I also know that I should be able to add `template` somewhere to tell the compiler that `inUnion` is a *template-id*, but where exactly? Should it then assume that `inUnion` is a class template, i.e. `inUnion<U>` names a type and not a function? | (See [here also for my C++11 answer](https://stackoverflow.com/a/17579889/4561887))
In order to parse a C++ program, the compiler needs to know whether certain names are types or not. The following example demonstrates that:
```
t * f;
```
How should this be parsed? For many languages a compiler doesn't need to know the meaning of a name in order to parse and basically know what action a line of code does. In C++, the above however can yield vastly different interpretations depending on what `t` means. If it's a type, then it will be a declaration of a pointer `f`. However if it's not a type, it will be a multiplication. So the C++ Standard says at paragraph (3/7):
> Some names denote types or templates. In general, whenever a name is encountered it is necessary to determine whether that name denotes one of these entities before continuing to parse the program that contains it. The process that determines this is called name lookup.
How will the compiler find out what a name `t::x` refers to, if `t` refers to a template type parameter? `x` could be a static int data member that could be multiplied or could equally well be a nested class or typedef that could yield to a declaration. **If a name has this property - that it can't be looked up until the actual template arguments are known - then it's called a *dependent name* (it "depends" on the template parameters).**
You might recommend to just wait till the user instantiates the template:
> *Let's wait until the user instantiates the template, and then later find out the real meaning of `t::x * f;`.*
This will work and actually is allowed by the Standard as a possible implementation approach. These compilers basically copy the template's text into an internal buffer, and only when an instantiation is needed, they parse the template and possibly detect errors in the definition. But instead of bothering the template's users (poor colleagues!) with errors made by a template's author, other implementations choose to check templates early on and give errors in the definition as soon as possible, before an instantiation even takes place.
So there has to be a way to tell the compiler that certain names are types and that certain names aren't.
## The "typename" keyword
The answer is: *We* decide how the compiler should parse this. If `t::x` is a dependent name, then we need to prefix it by `typename` to tell the compiler to parse it in a certain way. The Standard says at (14.6/2):
> A name used in a template declaration or definition and that is dependent on a template-parameter is
> assumed not to name a type unless the applicable name lookup finds a type name or the name is qualified
> by the keyword typename.
There are many names for which `typename` is not necessary, because the compiler can, with the applicable name lookup in the template definition, figure out how to parse a construct itself - for example with `T *f;`, when `T` is a type template parameter. But for `t::x * f;` to be a declaration, it must be written as `typename t::x *f;`. If you omit the keyword and the name is taken to be a non-type, but when instantiation finds it denotes a type, the usual error messages are emitted by the compiler. Sometimes, the error consequently is given at definition time:
```
// t::x is taken as non-type, but as an expression the following misses an
// operator between the two names or a semicolon separating them.
t::x f;
```
*The syntax allows `typename` only before qualified names* - it is therefor taken as granted that unqualified names are always known to refer to types if they do so.
A similar gotcha exists for names that denote templates, as hinted at by the introductory text.
## The "template" keyword
Remember the initial quote above and how the Standard requires special handling for templates as well? Let's take the following innocent-looking example:
```
boost::function< int() > f;
```
It might look obvious to a human reader. Not so for the compiler. Imagine the following arbitrary definition of `boost::function` and `f`:
```
namespace boost { int function = 0; }
int main() {
int f = 0;
boost::function< int() > f;
}
```
That's actually a valid *expression*! It uses the less-than operator to compare `boost::function` against zero (`int()`), and then uses the greater-than operator to compare the resulting `bool` against `f`. However as you might well know, `boost::function` [in real life](http://www.boost.org/doc/libs/1_54_0/doc/html/function.html) is a template, so the compiler knows (14.2/3):
> After name lookup (3.4) finds that a name is a template-name, if this name is followed by a <, the < is
> always taken as the beginning of a template-argument-list and never as a name followed by the less-than
> operator.
Now we are back to the same problem as with `typename`. What if we can't know yet whether the name is a template when parsing the code? We will need to insert `template` immediately before the template name, as specified by `14.2/4`. This looks like:
```
t::template f<int>(); // call a function template
```
Template names can not only occur after a `::` but also after a `->` or `.` in a class member access. You need to insert the keyword there too:
```
this->template f<int>(); // call a function template
```
---
## Dependencies
For the people that have thick Standardese books on their shelf and that want to know what exactly I was talking about, I'll talk a bit about how this is specified in the Standard.
In template declarations some constructs have different meanings depending on what template arguments you use to instantiate the template: Expressions may have different types or values, variables may have different types or function calls might end up calling different functions. Such constructs are generally said to *depend* on template parameters.
The Standard defines precisely the rules by whether a construct is dependent or not. It separates them into logically different groups: One catches types, another catches expressions. Expressions may depend by their value and/or their type. So we have, with typical examples appended:
* Dependent types (e.g: a type template parameter `T`)
* Value-dependent expressions (e.g: a non-type template parameter `N`)
* Type-dependent expressions (e.g: a cast to a type template parameter `(T)0`)
Most of the rules are intuitive and are built up recursively: For example, a type constructed as `T[N]` is a dependent type if `N` is a value-dependent expression or `T` is a dependent type. The details of this can be read in section `(14.6.2/1`) for dependent types, `(14.6.2.2)` for type-dependent expressions and `(14.6.2.3)` for value-dependent expressions.
### Dependent names
The Standard is a bit unclear about what *exactly* is a *dependent name*. On a simple read (you know, the principle of least surprise), all it defines as a *dependent name* is the special case for function names below. But since clearly `T::x` also needs to be looked up in the instantiation context, it also needs to be a dependent name (fortunately, as of mid C++14 the committee has started to look into how to fix this confusing definition).
To avoid this problem, I have resorted to a simple interpretation of the Standard text. Of all the constructs that denote dependent types or expressions, a subset of them represent names. Those names are therefore "dependent names". A name can take different forms - the Standard says:
> A name is a use of an identifier (2.11), operator-function-id (13.5), conversion-function-id (12.3.2), or template-id (14.2) that denotes an entity or label (6.6.4, 6.1)
An identifier is just a plain sequence of characters / digits, while the next two are the `operator +` and `operator type` form. The last form is `template-name <argument list>`. All these are names, and by conventional use in the Standard, a name can also include qualifiers that say what namespace or class a name should be looked up in.
A value dependent expression `1 + N` is not a name, but `N` is. The subset of all dependent constructs that are names is called *dependent name*. Function names, however, may have different meaning in different instantiations of a template, but unfortunately are not caught by this general rule.
### Dependent function names
Not primarily a concern of this article, but still worth mentioning: Function names are an exception that are handled separately. An identifier function name is dependent not by itself, but by the type dependent argument expressions used in a call. In the example `f((T)0)`, `f` is a dependent name. In the Standard, this is specified at `(14.6.2/1)`.
## Additional notes and examples
In enough cases we need both of `typename` and `template`. Your code should look like the following
```
template <typename T, typename Tail>
struct UnionNode : public Tail {
// ...
template<typename U> struct inUnion {
typedef typename Tail::template inUnion<U> dummy;
};
// ...
};
```
The keyword `template` doesn't always have to appear in the last part of a name. It can appear in the middle before a class name that's used as a scope, like in the following example
```
typename t::template iterator<int>::value_type v;
```
In some cases, the keywords are forbidden, as detailed below
* On the name of a dependent base class you are not allowed to write `typename`. It's assumed that the name given is a class type name. This is true for both names in the base-class list and the constructor initializer list:
```
template <typename T>
struct derive_from_Has_type : /* typename */ SomeBase<T>::type
{ };
```
* In using-declarations it's not possible to use `template` after the last `::`, and the C++ committee [said](http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_closed.html#109) not to work on a solution.
```
template <typename T>
struct derive_from_Has_type : SomeBase<T> {
using SomeBase<T>::template type; // error
using typename SomeBase<T>::type; // typename *is* allowed
};
``` | ## C++11
### Problem
While the rules in C++03 about when you need `typename` and `template` are largely reasonable, there is one annoying disadvantage of its formulation
```
template<typename T>
struct A {
typedef int result_type;
void f() {
// error, "this" is dependent, "template" keyword needed
this->g<float>();
// OK
g<float>();
// error, "A<T>" is dependent, "typename" keyword needed
A<T>::result_type n1;
// OK
result_type n2;
}
template<typename U>
void g();
};
```
As can be seen, we need the disambiguation keyword even if the compiler could perfectly figure out itself that `A::result_type` can only be `int` (and is hence a type), and `this->g` can only be the member template `g` declared later (even if `A` is explicitly specialized somewhere, that would not affect the code within that template, so its meaning cannot be affected by a later specialization of `A`!).
### Current instantiation
To improve the situation, in C++11 the language tracks when a type refers to the enclosing template. To know that, the type must have been formed by using a certain form of name, which is its own name (in the above, `A`, `A<T>`, `::A<T>`). A type referenced by such a name is known to be the *current instantiation*. There may be multiple types that are all the current instantiation if the type from which the name is formed is a member/nested class (then, `A::NestedClass` and `A` are both current instantiations).
Based on this notion, the language says that `CurrentInstantiation::Foo`, `Foo` and `CurrentInstantiationTyped->Foo` (such as `A *a = this; a->Foo`) are all *member of the current instantiation* **if** they are found to be members of a class that is the current instantiation or one of its non-dependent base classes (by just doing the name lookup immediately).
The keywords `typename` and `template` are now not required anymore if the qualifier is a member of the current instantiation. A keypoint here to remember is that `A<T>` is *still* a type-dependent name (after all `T` is also type dependent). But `A<T>::result_type` is known to be a type - the compiler will "magically" look into this kind of dependent types to figure this out.
```
struct B {
typedef int result_type;
};
template<typename T>
struct C { }; // could be specialized!
template<typename T>
struct D : B, C<T> {
void f() {
// OK, member of current instantiation!
// A::result_type is not dependent: int
D::result_type r1;
// error, not a member of the current instantiation
D::questionable_type r2;
// OK for now - relying on C<T> to provide it
// But not a member of the current instantiation
typename D::questionable_type r3;
}
};
```
That's impressive, but can we do better? The language even goes further and *requires* that an implementation again looks up `D::result_type` when instantiating `D::f` (even if it found its meaning already at definition time). When now the lookup result differs or results in ambiguity, the program is ill-formed and a diagnostic must be given. Imagine what happens if we defined `C` like this
```
template<>
struct C<int> {
typedef bool result_type;
typedef int questionable_type;
};
```
A compiler is required to catch the error when instantiating `D<int>::f`. So you get the best of the two worlds: "Delayed" lookup protecting you if you could get in trouble with dependent base classes, and also "Immediate" lookup that frees you from `typename` and `template`.
### Unknown specializations
In the code of `D`, the name `typename D::questionable_type` is not a member of the current instantiation. Instead the language marks it as a *member of an unknown specialization*. In particular, this is always the case when you are doing `DependentTypeName::Foo` or `DependentTypedName->Foo` and either the dependent type is *not* the current instantiation (in which case the compiler can give up and say "we will look later what `Foo` is) or it *is* the current instantiation and the name was not found in it or its non-dependent base classes and there are also dependent base classes.
Imagine what happens if we had a member function `h` within the above defined `A` class template
```
void h() {
typename A<T>::questionable_type x;
}
```
In C++03, the language allowed to catch this error because there could never be a valid way to instantiate `A<T>::h` (whatever argument you give to `T`). In C++11, the language now has a further check to give more reason for compilers to implement this rule. Since `A` has no dependent base classes, and `A` declares no member `questionable_type`, the name `A<T>::questionable_type` is *neither* a member of the current instantiation *nor* a member of an unknown specialization. In that case, there should be no way that that code could validly compile at instantiation time, so the language forbids a name where the qualifier is the current instantiation to be neither a member of an unknown specialization nor a member of the current instantiation (however, this violation is still not required to be diagnosed).
### Examples and trivia
You can try this knowledge on [this answer](https://stackoverflow.com/a/14005063/34509) and see whether the above definitions make sense for you on a real-world example (they are repeated slightly less detailed in that answer).
The C++11 rules make the following valid C++03 code ill-formed (which was not intended by the C++ committee, but will probably not be fixed)
```
struct B { void f(); };
struct A : virtual B { void f(); };
template<typename T>
struct C : virtual B, T {
void g() { this->f(); }
};
int main() {
C<A> c; c.g();
}
```
This valid C++03 code would bind `this->f` to `A::f` at instantiation time and everything is fine. C++11 however immediately binds it to `B::f` and requires a double-check when instantiating, checking whether the lookup still matches. However when instantiating `C<A>::g`, the [Dominance Rule](http://en.wikipedia.org/wiki/Dominance_(C%2B%2B)) applies and lookup will find `A::f` instead. | Where and why do I have to put the "template" and "typename" keywords? | [
"",
"c++",
"templates",
"typename",
"c++-faq",
"dependent-name",
""
] |
I'm wondering what techniques and/or library to use to implement the functionality of the linux command "tail -f ". I'm essentially looking for a drop in add-on/replacement for `java.io.FileReader`. Client code could look something like this:
```
TailFileReader lft = new TailFileReader("application.log");
BufferedReader br = new BufferedReader(lft);
String line;
try {
while (true) {
line= br.readLine();
// do something interesting with line
}
} catch (IOException e) {
// barf
}
```
The missing piece is a reasonable implementation of `TailFileReader`. It should be able to read parts of the file that exist before the file is opened as well as the lines that are added. | The ability to continue to read a file, and wait around until the file has some more updates for you shouldn't be that hard to accomplish in code yourself. Here's some pseudo-code:
```
BufferedReader br = new BufferedReader(...);
String line;
while (keepReading) {
line = reader.readLine();
if (line == null) {
//wait until there is more of the file for us to read
Thread.sleep(1000);
}
else {
//do something interesting with the line
}
}
```
I would assume that you would want to put this type of functionality in its own Thread, so that you can sleep it and not affect any other areas of your application. You would want to expose `keepReading` in a setter so that your main class / other parts of the application can safely shut the thread down without any other headaches, simply by calling `stopReading()` or something similar. | Take a look at Apache Commons implementation of [Tailer](https://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/input/Tailer.html) class. It does seem to handle log rotation as well. | Java IO implementation of unix/linux "tail -f" | [
"",
"java",
"file",
"file-io",
"iostream",
"tail",
""
] |
```
$pages = array("grac", "zamknij", "dolaczyc");
$pagesid = array("showNews", "showThread", "showProfile");
foreach ($pagesid as $page) {
if (isset($_GET[$page])) {
include('sobra/'.$page.'.php');
}
}
// just pages
elseif (in_array($_GET['page'], $pages)) {
include("$_GET[page].php");
}
// error
else include('error.php');
```
gives:
*Parse error: syntax error, unexpected T\_ELSEIF in C:\WAMP\www\sdgag\index.php on line 33*
This should work i think.. what the problem can be?
Thanks | Perhaps another approach. Do your logic, and determine what page you want to include ultimately. After all of the logic has been done, include your determined page.
*The following is untested, and may contain errors. Let me know, and I'll update the code.*
```
<?php
// Predefined list of acceptable pages
$pages = array("one","two","three");
$pagesid = array("four","five","six");
// Gather any user-defined page request
$desPage = trim($_GET["page"]);
// Assume they are wrong, and need to see error.php
$pageToLoad = "error.php";
// If the user request is not empty
if (!empty($desPage)) {
if (in_array($desPage,$pages)) {
$pageToLoad = $desPage . ".php";
}
} else {
// User request is empty, check other variables
foreach ($pagesid as $pageid) {
if (isset($_GET[$pageid])) {
$pageToLoad = $pageid . ".php";
}
}
}
// Show output page
include($pageToLoad);
?>
``` | The elseif and the else aren't attached to the if, you've put them outside of the foreach loop block. | unexpected T_ELSEIF | [
"",
"php",
"foreach",
""
] |
I've recently started working with JSON and the ExtJs framework and I've come across the following code in an example.
we retrieve the information from the frontend using this:
```
object updatedConfig = JavaScriptConvert.DeserializeObject(Request["dataForm"]);
```
Then in the example they do the following:
```
JavaScriptObject jsObj = updatedConfig as JavaScriptObject;
```
I've never seen the "as" keyword used like that before. Is this just another form of explicitly boxing the updatedConfig variable as a JavaScriptObject or is there something I'm not understanding about this?
Thanks | This is known as a safe cast. What is does is it attempts to cast from one type to another and if the cast fails it returns `null` instead of throwing an `InvalidCastException`.
There are actually two separate IL instructions to handle the difference between "`as`" casting and normal static casting. The following C# code contains both types of casting:
```
using System;
class Program
{
static void Main()
{
Object o = null;
String s0 = (String)o;
String s1 = o as String;
}
}
```
The first cast uses the `castclass` IL instruction and the second cast uses the `isinst` instruction.
Please see [Casting vs using the 'as' keyword in the CLR](https://stackoverflow.com/questions/496096/casting-vs-using-the-as-keyword-in-the-clr) for a more detailed explanation. | The [as keyword](http://msdn.microsoft.com/en-us/library/cscsdfbt(VS.71).aspx) is a safer way to cast objects in C#.
```
SomeType a = obj as SomeType;
```
Means that if `obj` is of type `SomeType`, `obj` will be cast into that type. If `obj` is null or is not of type `SomeType`, a will be null. | Instantiate "AS" keyword | [
"",
"c#",
"json",
"keyword",
"boxing",
"unboxing",
""
] |
Surely there has to be many ways to optimize the following code, where I basically have to make sure that a lot of textboxes aren't empty and then read their values:
```
if (foo1.Text.Length != 0 & bar1.Text.Length != 0)
{
output.Text += myStrings[i] + " / " + foo1.Text + " / " + bar1.Text;
}
if (foo2.Text.Length != 0 & bar2.Text.Length != 0)
{
output.Text += myStrings[i] + " / " + foo2.Text + " / " + bar2.Text;
}
if (foo3.Text.Length != 0 & bar3.Text.Length != 0)
{
output.Text += myStrings[i] + " / " + foo3.Text + " / " + bar3.Text;
}
if (foo4.Text.Length != 0 & bar4.Text.Length != 0)
{
output.Text += myStrings[i] + " / " + foo4.Text + " / " + bar4.Text;
}
if (foo5.Text.Length != 0 & bar5.Text.Length != 0)
{
output.Text += myStrings[i] + " / " + foo5.Text + " / " + bar5.Text;
}
if (foo6.Text.Length != 0 & bar6.Text.Length != 0)
output.Text += myStrings[i] + " / " + foo6.Text + " / " + bar6.Text;
if (foo7.Text.Length != 0 & bar7.Text.Length != 0)
{
output.Text += myStrings[i] + " / " + foo7.Text + " / " + bar7.Text;
}
if (foo8.Text.Length != 0 & bar8.Text.Length != 0)
{
output.Text += myStrings[i] + " / " + foo8.Text + " / " + bar8.Text;
}
if (foo9.Text.Length != 0 & bar9.Text.Length != 0)
{
output.Text += myStrings[i] + " / " + foo9.Text + " / " + bar9.Text;
}
if (foo10.Text.Length != 0 & bar10.Text.Length != 0)
{
output.Text += myStrings[i] + " / " + foo10.Text + " / " + bar10.Text;
}
``` | I would put the repeated elements in arrays and then loop over them.
```
TextBox[] foos = new TextBox[] { foo1, foo2, foo3, /* etc */ };
TextBox[] bars = new TextBox[] { bar1, bar2, bar3, /* etc */ };
for (int i = 0; i <= 10; i++)
if (foos[i].Text.Length != 0 && bars[i].Text.Length != 0)
output.Text += myStrings[i] + "/" + foos[i].Text + bars[i].Text;
```
Of course, if the elements are really named sequentially you can fill the arrays by looking up the controls from the form's Controls collection, with the name "foo" + number.ToString(). | I would just loop over the Controls collection on which these TextBoxes reside, then filter on TextBox only and do you checks and concat.
I also strongly advice to use a StringBuilder instead of +=. | How to optimize this code? | [
"",
"c#",
"optimization",
""
] |
Most OO languages prefix their interface names with a capital I, why does Java not do this? What was the rationale for not following this convention?
To demonstrate what I mean, if I wanted to have a User interface and a User implementation I'd have two choices in Java:
> 1. Class = User, Interface = UserInterface
> 2. Class = UserImpl, Interface = User
Where in most languages:
> Class = User, Interface = IUser
Now, you might argue that you could always pick a most descriptive name for the user implementation and the problem goes away, but Java's pushing a POJO approach to things and most IOC containers use DynamicProxies extensively. These two things together mean that you'll have lots of interfaces with a single POJO implementation.
So, I guess my question boils down to: **"Is it worth following the broader Interface naming convention especially in light of where Java Frameworks seem to be heading?"** | I prefer not to use a prefix on interfaces:
* The prefix hurts readability.
* Using interfaces in clients is the standard best way to program, so interfaces names should be as short and pleasant as possible. Implementing classes should be uglier to discourage their use.
* When changing from an abstract class to an interface a coding convention with prefix I implies renaming all the occurrences of the class --- not good! | Is there really a difference between:
```
class User implements IUser
```
and
```
class UserImpl implements User
```
if all we're talking about is naming conventions?
Personally I prefer NOT preceding the interface with `I` as I want to be coding to the interface and I consider *that* to be more important in terms of the naming convention. If you call the interface `IUser` then every consumer of that class needs to know its an `IUser`. If you call the class `UserImpl` then only the class and your DI container know about the `Impl` part and the consumers just know they're working with a `User`.
Then again, the times I've been forced to use `Impl` because a better name doesn't present itself have been few and far between because the implementation gets named *according* to the implementation because that's where it's important, e.g.
```
class DbBasedAccountDAO implements AccountDAO
class InMemoryAccountDAO implements AccountDAO
``` | Interface naming in Java | [
"",
"java",
"interface",
"naming-conventions",
""
] |
I have a small code example I want to include in the Javadoc comment for a method.
```
/**
* -- ex: looping through List of Map objects --
* <code>
* for (int i = 0; i < list.size(); i++) {
* Map map = (Map)list.get(i);
* System.out.println(map.get("wordID"));
* System.out.println(map.get("word"));
* }
* </code>
*
* @param query - select statement
* @return List of Map objects
*/
```
The problem is the code example shows up in the Javadoc with no line breaks making it hard to read.
```
-- ex: looping through List of Map objects -- for (int i = 0; i list.size(); i++) { Map map = (Map)list.get(i); System.out.println(map.get("wordID")); System.out.println(map.get("word")); }
Parameters
query - - select statement
Returns:
List of Map objects
```
I guess I am wrong in assuming the code tag would handle line breaks. What is the best way to format code examples in Javadoc comments ? | In addition to the already mentioned `<pre>` tags, you should also use the `@code` JavaDoc annotation, which will make life much easier when it comes to HTML entities issues (in particular with Generics), e.g.:
```
* <pre>
* {@code
* Set<String> s;
* System.out.println(s);
* }
* </pre>
```
Will give correct HTML output:
```
Set<String> s;
System.out.println(s);
```
While omitting the `@code` block (or using a `<code>` tag) will result in HTML like this:
```
Set s;
System.out.println(s);
```
For reference, a full list of tag descriptions available in Java SE 8 can be found [here](https://docs.oracle.com/javase/8/docs/technotes/tools/unix/javadoc.html#CHDJGIJB). | I had a really tough time with including a specific code example in a javadoc comment. I'd like to share this one.
Please note the following:
* usage of old `<code>` - tag to prevent the curly brackets from being interpreted
* usage of "new" `{@code ...}` - tag to get the generics included in the output
* escaping of the @ sign in `@Override` via "`{@literal @}Override`" because javadoc generator "tilts" there due to the fact that the @ goes directly after an opening curly bracket
* remove one space in front of `{@code` and `{@literal`, to compensate inner spaces and keep the alignment
javadoc code:
```
/** this methods adds a specific translator from one type to another type. `
* i.e.
* <pre>
* <code>new BeanTranslator.Builder()
* .translate(
* new{@code Translator<String, Integer>}(String.class, Integer.class){
* {@literal @}Override
* public Integer translate(String instance) {
* return Integer.valueOf(instance);
* }})
* .build();
* </code>
* </pre>
* @param translator
*/
```
gets printed as
```
new BeanTranslator.Builder()
.translate(
new Translator<String, Integer>(String.class, Integer.class){
@Override
public Integer translate(String instance) {
return Integer.valueOf(instance);
}})
.build();
``` | Multiple line code example in Javadoc comment | [
"",
"java",
"html",
"javadoc",
""
] |
In many languages (and places) there is a nice practice of creating local scopes by creating a block like [this](https://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c).
```
void foo()
{
... Do some stuff ...
if(TRUE)
{
char a;
int b;
... Do some more stuff ...
}
... Do even more stuff ...
}
```
How can I implement this in python without getting the unexpected indent error and without using some sort of [*if True:*](https://stackoverflow.com/questions/541705/is-iftrue-a-good-idea-in-c) tricks | In Python, scoping is of three types : global, local and class. You can create specialized 'scope' dictionaries to pass to exec / eval(). In addition you can use nested scopes
(defining a function within another). I found these to be sufficient in all my code.
As Douglas Leeder said already, the main reason to use it in other languages is variable scoping and that doesn't really happen in Python. In addition, Python is the most readable language I have ever used. It would go against the grain of readability to do something like if-true tricks (Which you say you want to avoid). In that case, I think the best bet is to refactor your code into multiple functions, or use a single scope. I think that the available scopes in Python are sufficient to cover every eventuality, so local scoping shouldn't really be necessary. | If you just want to create temp variables and let them be garbage collected right after using them, you can use
```
del varname
```
when you don't want them anymore.
If its just for aesthetics, you could use comments or extra newlines, no extra indentation, though. | How can one create new scopes in python | [
"",
"python",
"scope",
""
] |
I'm trying to retrieve a specific image from a html document, using html agility pack and this xpath:
```
//div[@id='topslot']/a/img/@src
```
As far as I can see, it finds the src-attribute, but it returns the img-tag. Why is that?
I would expect the InnerHtml/InnerText or something to be set, but both are empty strings. OuterHtml is set to the complete img-tag.
Are there any documentation for Html Agility Pack? | Html Agility Pack [does not support](http://www.codeplex.com/htmlagilitypack/Thread/View.aspx?ThreadId=1720) attribute selection. | You can directly grab the attribute if you use the `HtmlNavigator` instead.
```
//Load document from some html string
HtmlDocument hdoc = new HtmlDocument();
hdoc.LoadHtml(htmlContent);
//Load navigator for current document
HtmlNodeNavigator navigator = (HtmlNodeNavigator)hdoc.CreateNavigator();
//Get value from given xpath
string xpath = "//div[@id='topslot']/a/img/@src";
string val = navigator.SelectSingleNode(xpath).Value;
``` | Selecting attribute values with html Agility Pack | [
"",
"c#",
".net",
"xpath",
"html-agility-pack",
""
] |
I want to count how many `/`s I could find in a string. There are several ways to do it, but I couldn't decide on what the best (or easiest) is.
At the moment I'm going with something like:
```
string source = "/once/upon/a/time/";
int count = source.Length - source.Replace("/", "").Length;
```
Or for strings where length > 1:
```
string haystack = "/once/upon/a/time";
string needle = "/";
int needleCount = ( haystack.Length - haystack.Replace(needle,"").Length ) / needle.Length;
``` | If you're using .NET 3.5 you can do this in a one-liner with LINQ:
```
int count = source.Count(f => f == '/');
```
If you don't want to use LINQ you can do it with:
```
int count = source.Split('/').Length - 1;
```
---
You might be surprised to learn that your original technique seems to be about 30% faster than either of these! I've just done a quick benchmark with "/once/upon/a/time/" and the results are as follows:
> Your original = 12s
> source.Count = 19s
> source.Split = 17s
> foreach ([from bobwienholt's answer](https://stackoverflow.com/a/541976/662581)) = 10s
(The times are for 50,000,000 iterations so you're unlikely to notice much difference in the real world.) | ```
string source = "/once/upon/a/time/";
int count = 0;
foreach (char c in source)
if (c == '/') count++;
```
Has to be faster than the `source.Replace()` by itself. | How to count occurrences of a char\string within a string? | [
"",
"c#",
"string",
""
] |
I'm trying to find a way to replace all instances of a string token in a file with another string.
How can I do this in C++ with the win32 API?
In other languages this is an easy thing to do, but in C++ I am just lost.
EDIT: For some context, this is for a WiX custom action. So portability is not a main priority, just the most simplest solution. | If the file fits in memory – it's simpler. Call OpenFile() to open file, GetFileSize() to determine file size, allocate enough memory, call ReadFile() to read file, then CloseFile. Do replacement in memory (use strstr() or similar function), then again OpenFile(), WriteFile(), CloseFile().
If the file is large - create a temporary file and read the source file in chunks and write filtered text to the temporary file, then call DeleteFile() to delete the original file and MoveFile() to move the filtered file. | You could use the [Boost.Regex](http://www.boost.org/doc/libs/1_38_0/libs/regex/doc/html/index.html) Library which should resemble most of the functionality you find on other platforms.
It would work like this:
In this [example](http://flavio.castelli.name/regexp-with-boost) you’ll find how you can replace a string matching a pattern.
```
#include <boost/regex.hpp>
#include <string>
int main()
{
boost::regex pattern ("b.lug",boost::regex_constants::icase|boost::regex_constants::perl);
std::string stringa ("Searching for bolug");
std::string replace ("BgLug");
std::string newString;
newString = boost::regex_replace (stringa, pattern, replace);
printf("The new string is: |%s|\n",newString.c_str());
return 0;
}
```
but you would have of course to add the file reading/writing. | Finding and replacing string tokens in a file in C++ using win32 API | [
"",
"c++",
"winapi",
"string",
""
] |
I can use GetHashCode() to identify an object but is there any way to identify the actual sql connection obtained by a SqlConnection object?
I'm (still) trying to debug a problem involving pooled connections and application roles and if I could reliably identify the underlying sql connection it could help a lot.
Here's some code that might illustrate the question
```
SqlConnection c = new SqlConnection(myConnString);
c.Open(); // GetHashCode == "X"
c.Close(); // returns connection to pool
c.Open; // GetHashCode() == "X" but possibly different pooled connection?
```
As I write this question it occurs to me that what I probably want is the SPID of the connection. Sadly, SPID isn't available when the connection is dropped by SQL due to the bug I'm trying to resolve (so at the point I'm most interested in I can't run a command on that connection to obtain the SPID).
Any other bright ideas? | Not to say that this is impossible, but I've not yet found any way to do it. | @Ed Guiness,
(I know this is an old thread but for the benefit of those who might need this in future)
;tldr answer: Not without some code changes ( mostly Non-Breaking and reasonable changes IMHO ).
Its very Strange that Microsoft does not expose the SPID once the connection object has been opened. I can see for example the SQL Version name and other SQL Server specific properties that I can get from the SqlConnection Object but not the SPID.
Details:
Every SQLConnection is assigned one SPID. This is obtained using the T-SQL Command @@SPID but this executes on the SQL Server side. Trick is to pass that along with the main work that is being done on SQL Server side and read it on the C# side.
Four possible scenarios for which SPID is needed.
1. You Are executing a Stored Procedure that Returns a resultset (minus the spid)
2. You are doing INS/UPD/DEL a Stored Procedure.
3. You are running Prepared SQL stms On the fly (inline) from ADO.Net (yikes!!) to do CRUD operations ( i.e Scenarios 1 and 2 without Stored Procedures )
4. You are inserting Data directly to a Table using SqlBulkCopy
**1. Stored Procedure that Returns a resultset**
Let say you have a SP (USP\_GetDBDetails) that returns Rows from master db. We need to add a line of code to the Existing SQL Stmt to return the SPID and Get it on the C# Side using Paramter type for retrieving ReturnValue. The main Resultsets can also be read.
Stored Procedures are a beautiful thing. **They can simultaneously return a return value AND a resultset AND a OutPut Parameter.** In this case on the SP Side we only need to add the additional return value at the end of the SP that is being executed by ADO.Net using SqlConnection.We do this as shown in the T-SQL code below:
```
CREATE Procedure [dbo].[USP_GetDBDetails]
AS
BEGIN
SELECT
database_id,
name,
create_date
FROM [sys].[databases]
Return @@SPID -- Line of Code that needs to be added to return the SPID
END
```
Now to capture the SPID on the C# side (modify connection string as needed) :
```
using (SqlConnection conn = new SqlConnection(@"Data Source=(local);Initial Catalog=master;Persist Security Info=True;Integrated Security =SSPI;"))
{
string strSql = "USP_GetDBDetails";
SqlCommand sqlcomm = new SqlCommand();
sqlcomm.CommandText = strSql;
sqlcomm.CommandType = CommandType.StoredProcedure;
sqlcomm.Connection = conn;
SqlParameter returnValueParam = sqlcomm.Parameters.Add("@ReturnValue", SqlDbType.Int);
returnValueParam.Direction = ParameterDirection.ReturnValue;
conn.Open();
**// Reader Section**
SqlDataReader rdr = sqlcomm.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(rdr); // Get the Reultset into a DataTable so we can use it !
rdr.Close(); // Important to close the reader object before reading the return value.
// Lets get the return value which in this case will be the SPID for this connection.
string spid_str = returnValueParam.Value.ToString();
int spid = (int)sqlcomm.Parameters["@ReturnValue"].Value; // Another Way to get the return value.
Console.WriteLine("SPID For this Conn = {0} ", spid);
// To use the Reult Sets that was returned by the SP:
foreach (DataRow dr in dt.Rows)
{
string dbName = dr["Name"].ToString();
// Code to use the Other Columns goes here
}
}
```
Output :
```
SPID For this Conn = 66
```
---
**2. If the Connection object is executing A SP that handles INS/UPS/DEL**
Add the RETURN @@SPID at the end of the SP that is responsible for INS/UPD/DEL just as we did for Scenario 1.
And on the C# Side to get the SPID .. everything remains same as in Scenario 1 except the **reader section**. Delete the 4 lines under the Reader Section and replace with this line below. (and obviously the foreach loop to iterate the DataTable dt wont be necessary)
```
sqlcomm.ExecuteNonQuery();
```
---
**3. INS/UPD/DEL Using Inline SQL**
Move these stmts into a Stored Procedure and follow Steps for Scenario 2 . There might be ways to do some T-SQL acrobatics to inject the @@SPID and return it by perhaps utilizing MultipleActiveResultSets option but not very Elegant IMO.
---
**4. SqlBulkCopy**.
This will require querying the table to get the spid. Since there is no Stored procedure to return the SPID from SqlServer that can be captured.
We need to add an extra column of type INT to hold the SPID value like so:
```
ALTER TABLE dbo.TBL_NAME ADD
SPID int NOT NULL Default( @@SPID )
GO
```
By doing this SQL Server will automatically insert the SPID value into the newly added column. No Code change will be necessary on C# ADO side that handles the BulkCopy. A typical Bulkcopy ADO code looks like below and it should continue to work after the ALTER TABLE Stmt above.
```
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection))
{
DataTable dt = new DataTable();
dt.Columns.Add("Col1");
dt.Columns.Add("Col2");
string[] row = { "Col1Value", "Col2Value" };
dt.Rows.Add(row);
bulkCopy.DestinationTableName = "TBL_NAME_GOES_HERE"; //TBL_NAME
try
{
// Write from the source to the destination.
bulkCopy.WriteToServer(dt);
}
catch (SqlException ex)
{
// Handle Exception
}
}
}
```
So to check the output do a Select distinct SPID from dbo.TBL\_NAME
Thats it . Hope that helps somebody. | Identifying underlying sql connection of SqlConnection object | [
"",
"c#",
"sql-server",
"sqlconnection",
"spid",
""
] |
In the context of SQL, what does a ***runaway query*** mean?
Does it mean any query that runs wild when it takes too long?
Or does it mean when it has some side-effects due to triggers? | A runaway query is a query whose execution time is taking longer than the execution time estimated by the optimizer. Runaway queries can lead to using up all of your processor cycles or other resources during its execution. | It's a query that starts running and never comes back (for some value of "never").
Usually it means that the query isn't using an index it's supposed to, or using a bad join method, or a bad join order, or doing a bunch of string conversion/comparison.
It is possible to write SQL queries that take weeks/years to perform. | What is "runaway query"? | [
"",
"sql",
"terminology",
"definition",
""
] |
I have an application that has a main form and uses an event handler to process incoming data and reflect the changes in various controls on the main form. This works fine.
I also have another form in the application. There can be multiple instances of this second form running at any given time.
What I'd like to do is have each instance of this second form listen to the event handler in the main form and update controls on its instance of the second form.
How would I do this?
Here's some sample code. I want to information from the\_timer\_Tick event handler to update each instance of SecondaryForm.
```
public partial class Form1 : Form
{
Timer the_timer = new Timer();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
the_timer.Tick += new EventHandler(the_timer_Tick);
the_timer.Interval = 2000;
the_timer.Enabled = true;
}
void the_timer_Tick(object sender, EventArgs e)
{
// I would like code in here to update all instances of SecondaryForm
// that happen to be open now.
MessageBox.Show("Timer ticked");
}
private void stop_timer_button_Click(object sender, EventArgs e)
{
the_timer.Enabled = false;
}
private void start_form_button_Click(object sender, EventArgs e)
{
SecondaryForm new_form = new SecondaryForm();
new_form.Show();
}
}
``` | ```
class SecondForm
{
private FirstForm firstForm;
public SecondForm()
{
InitializeComponent();
// this means unregistering on form closing, uncomment if is necessary (anonymous delegate)
//this.Form_Closing += delegate { firstForm.SomeEvent -= SecondForm_SomeMethod; };
}
public SecondaryForm(FirstForm form) : this()
{
this.firstForm = form;
firstForm.Timer.Tick += new EventHandler(Timer_Tick);
}
// make it public in case of external event handlers registration
private void Timer_Tick(object sender, EventArgs e)
{
// now you can access firstForm or it's timer here
}
}
class FirstForm
{
public Timer Timer
{
get
{
return this.the_timerl
}
}
public FirstForm()
{
InitializeComponent();
}
private void Button_Click(object sender, EventArgs e)
{
new SecondForm(this).ShowDialog(); // in case of internal event handlers registration (in constructor)
// or
SecondForm secondForm = new SecondForm(this);
the_timer.Tick += new EventHandler(secondForm.Timer_tick); // that method must be public
}
``` | Consider using loosely coupled events. This will allow you to couple the classes in such a way that they never have to be directly aware of each other. The Unity application block comes with an extension called [EventBroker](http://msdn.microsoft.com/en-us/library/ff650784.aspx) that makes this very simple.
Here's a little lick of the sugar:
```
public static class EVENTS
{
public const string UPDATE_TICKED = "event://Form1/Ticked";
}
public partial class Form1 : Form
{
[Publishes(EVENTS.UPDATE_TICKED)]
public event EventHandler Ticked;
void the_timer_Tick(object sender, EventArgs e)
{
// I would like code in here to update all instances of SecondaryForm
// that happen to be open now.
MessageBox.Show("Timer ticked");
OnTicked();
}
protected virtual void OnTicked()
{
if (Ticked == null) return;
Ticked(this, e);
}
}
public partial class SecondaryForm : Form
{
[SubscribesTo(EVENTS.UPDATE_TICKED)]
private void Form1_Ticked(object sender, EventHandler e)
{
// code to handle tick in SecondaryForm
}
}
```
Now if you construct both of these classes using Unity, they will automatically be wired together.
**Update**
Newer solutions use message bus to handle loosely coupled events. See <http://masstransit-project.com/> or <http://nimbusapi.github.io/> as examples. | Listening to Events in Main Form from Another Form in C# | [
"",
"c#",
".net",
"winforms",
"event-handling",
""
] |
Why is the following forbidden?
```
Nullable<Nullable<int>>
```
whereas
```
struct MyNullable <T>
{
}
MyNullable<Nullable<int>>
```
is NOT | This is because the struct constraint actually means ['not nullable'](http://msdn.microsoft.com/en-us/library/fsdhc71f(VS.80).aspx) since Nullable, despite being a struct, is nullable (can accept the value null) the `Nullable<int>` is not a valid type parameter to the outer Nullable.
This is made explicit in [the constraints documentation](http://msdn.microsoft.com/en-us/library/d5x73970.aspx)
> where T: struct
> The type argument must be a value type. Any value type except Nullable can be specified.
> See Using Nullable Types (C# Programming Guide) for more information.
If you want the rationale for that you would need the actual language designer's comments on it which I can't find. However I would postulate that:
1. the compiler and platform changes required to achieve Nullable in it's current form are quite extensive (and were a relatively last minute addition to the 2.0 release).
2. They have several potentially confusing edge cases.
Allowing the equivalent of int?? would only confuse that since the language provides no way of distinguishing Nullable`<Nullable<null>>` and Nullable`<null>` nor any obvious solution to the following.
```
Nullable<Nullable<int>> x = null;
Nullable<int> y = null;
Console.WriteLine(x == null); // true
Console.WriteLine(y == null); // true
Console.WriteLine(x == y); // false or a compile time error!
```
Making that return true would be **very** complex and significant overhead on many operations involving the Nullable type.
Some types in the CLR are 'special', examples are strings and primitives in that the compiler and runtime know a lot about the implementation used by each other. Nullable is special in this way as well. Since it is already special cased in other areas special casing the `where T : struct` aspect is not such a big deal. The benefit of this is in dealing with structs in generic classes because none of them, apart from Nullable, can be compared against null. This means the jit can safely consider `t == null` to be false always.
Where languages are designed to allow two very different concepts to interact you tend to get weird, confusing or down right dangerous edge cases. As an example consider Nullable and the equality operators
```
int? x = null;
int? y = null;
Console.WriteLine(x == y); // true
Console.WriteLine(x >= y); // false!
```
By preventing Nullables when using struct generic constraint many nasty (and unclear) edge cases can be avoided.
As to the exact part of the specification that mandates this [from section 25.7](http://en.csharp-online.net/ECMA-334:_25.7_Constraints) (emphasis mine):
> The value type constraint specifies that a type argument used for the type parameter
> must be a value type (§25.7.1). Any non-nullable struct type, enum type, or type
> parameter having the value type constraint satisfies this constraint. A type parameter
> having the value type constraint shall not also have the constructor-constraint.
> The System.Nullable type specifies the non-nullable value type constraint for T.
> **Thus, recursively constructed types of the forms T?? and Nullable`<`Nullable`<`T`>>` are prohibited.** | I believe you can only use non-nullable value types in `Nullable`s. Since `Nullable` itself is nullable, nesting this way is prohibited.
From <http://msdn.microsoft.com/en-us/library/kwxxazwb.aspx>
> ```
> public Nullable(
> T value
> )
> ```
>
> Type: T A value type. | Nullable<T> confusion | [
"",
"c#",
"generics",
"nullable",
""
] |
How could I go about detecting (returning true/false) whether an ArrayList contains more than one of the same element in Java?
I am not looking to compare "Blocks" with each other but their integer values. Each "block" has an int and this is what makes them different. I find the int of a particular Block by calling a method named "getNum" (e.g. table1[0][2].getNum()). | Simplest: dump the whole collection into a Set (using the Set(Collection) constructor or Set.addAll), then see if the Set has the same size as the ArrayList.
```
List<Integer> list = ...;
Set<Integer> set = new HashSet<Integer>(list);
if(set.size() < list.size()){
/* There are duplicates */
}
```
Update: If I'm understanding your question correctly, you have a 2d array of Block, as in
Block table[][];
and you want to detect if any row of them has duplicates?
In that case, I could do the following, assuming that Block implements "equals" and "hashCode" correctly:
```
for (Block[] row : table) {
Set set = new HashSet<Block>();
for (Block cell : row) {
set.add(cell);
}
if (set.size() < 6) { //has duplicate
}
}
```
I'm not 100% sure of that for syntax, so it might be safer to write it as
```
for (int i = 0; i < 6; i++) {
Set set = new HashSet<Block>();
for (int j = 0; j < 6; j++)
set.add(table[i][j]);
...
```
`Set.add` returns a boolean false if the item being added is already in the set, so you could even short circuit and bale out on any add that returns `false` if all you want to know is whether there are any duplicates. | Improved code, using return value of `Set#add` instead of comparing the size of list and set.
```
public static <T> boolean hasDuplicate(Iterable<T> all) {
Set<T> set = new HashSet<T>();
// Set#add returns false if the set does not change, which
// indicates that a duplicate element has been added.
for (T each: all) if (!set.add(each)) return true;
return false;
}
``` | Detect duplicates in ArrayList | [
"",
"java",
"arrays",
"arraylist",
"duplicates",
""
] |
I have a Django my\_forms.py like this:
```
class CarSearchForm(forms.Form):
# lots of fields like this
bodystyle = forms.ChoiceField(choices=bodystyle_choices())
```
Each choice is e.g. ("Saloon", "Saloon (15 cars)"). So the choices are computed by this function.
```
def bodystyle_choices():
return [(bodystyle.bodystyle_name, '%s (%s cars)' %
(bodystyle.bodystyle_name, bodystyle.car_set.count()))
for bodystyle in Bodystyle.objects.all()]
```
My problem is the choices functions are getting executed every time I merely import my\_forms.py. I think this is due to the way Django declares its fields: in the class but not in a class method. Which is fine but my views.py imports my\_forms.py so the choices lookups are done on every request no matter which view is used.
I thought that maybe putting choices=bodystyle\_choices with no bracket would work, but I get:
```
'function' object is not iterable
```
Obviously I can use caching and put the "import my\_forms" just in the view functions required but that doesn't change the main point: my choices need to be lazy! | You can use the "lazy" function :)
```
from django.utils.functional import lazy
class CarSearchForm(forms.Form):
# lots of fields like this
bodystyle = forms.ChoiceField(choices=lazy(bodystyle_choices, tuple)())
```
very nice util function ! | Try using a ModelChoiceField instead of a simple ChoiceField. I think you will be able to achieve what you want by tweaking your models a bit. Take a look at the [docs](http://docs.djangoproject.com/en/dev/ref/forms/fields/#modelchoicefield) for more.
I would also add that ModelChoiceFields are `lazy` by default :) | Lazy choices in Django form | [
"",
"python",
"django",
"forms",
"lazy-evaluation",
""
] |
I was recently watching a webcast about [how to create a fluent DSL](http://www.dimecasts.net/Casts/CastFeedDetails/84) and I have to admit, I don't understand the reasons why one would use such an approach (at least for the given example).
The webcast presented an image resizing class, that allows you to specify an input-image, resize it and save it to an output-file using the following syntax (using C#):
```
Sizer sizer = new Sizer();
sizer.FromImage(inputImage)
.ToLocation(outputImage)
.ReduceByPercent(50)
.OutputImageFormat(ImageFormat.Jpeg)
.Save();
```
I don't understand how this is better than a "conventional" method that takes some parameters:
```
sizer.ResizeImage(inputImage, outputImage, 0.5, ImageFormat.Jpeg);
```
From a usability point of view, this seems a lot easier to use, since it clearly tells you what the method expects as input. In contrast, with the fluent interface, nothing stops you from omitting/forgetting a parameter/method-call, for example:
```
sizer.ToLocation(outputImage).Save();
```
So on to my questions:
**1 -** Is there some way to improve the usability of a fluent interface (i.e. tell the user what he is expected to do)?
**2 -** Is this fluent interface approach just a replacement for the non existing named method parameters in C#? Would named parameters make fluent interfaces obsolete, e.g. something similar objective-C offers:
```
sizer.Resize(from:input, to:output, resizeBy:0.5, ..)
```
**3 -** Are fluent interfaces over-used simply because they are currently popular?
**4 -** Or was it just a bad example that was chosen for the webcast? In that case, tell me what the advantages of such an approach are, where does it make sense to use it.
BTW: I know about jquery, and see how easy it makes things, so I'm not looking for comments about that or other existing examples.
I'm more looking for some (general) comments to help me understand (for example) when to implement a fluent interface (instead of a classical class-library), and what to watch out for when implementing one. | > 2 - Is this fluent interface approach
> just a replacement for the non
> existing named method parameters in
> C#? Would named parameters make fluent
> interfaces obsolete, e.g. something
> similar objective-C offers:
Well yes and no. The fluent interface gives you a larger amount of flexibility. Something that could not be achieved with named params is:
```
sizer.FromImage(i)
.ReduceByPercent(x)
.Pixalize()
.ReduceByPercent(x)
.OutputImageFormat(ImageFormat.Jpeg)
.ToLocation(o)
.Save();
```
The FromImage, ToLocation and OutputImageFormat in the fluid interface, smell a bit to me. Instead I would have done something along these lines, which I think is much clearer.
```
new Sizer("bob.jpeg")
.ReduceByPercent(x)
.Pixalize()
.ReduceByPercent(x)
.Save("file.jpeg",ImageFormat.Jpeg);
```
Fluent interfaces have the same problems many programming techniques have, they can be misused, overused or underused. I think that when this technique is used effectively it can create a richer and more concise programming model. Even StringBuilder supports it.
```
var sb = new StringBuilder();
sb.AppendLine("Hello")
.AppendLine("World");
``` | I would say that fluent interfaces are slightly overdone and I would think that you have picked just one such example.
I find fluent interfaces particularly strong when you are constructing a complex model with it. With model I mean e.g. a complex relationship of instantiated objects. The fluent interface is then a way to guide the developer to correctly construct instances of the semantic model. Such a fluent interface is then an excellent way to separate the mechanics and relationships of a model from the "grammar" that you use to construct the model, essentially shielding details from the end user and reducing the available verbs to maybe just those relevant in a particular scenario.
Your example seems a bit like overkill.
I have lately done some fluent interface on top of the SplitterContainer from Windows Forms. Arguably, the semantic model of a hierarchy of controls is somewhat complex to correctly construct. By providing a small fluent API a developer can now declaratively express how his SplitterContainer should work. Usage goes like
```
var s = new SplitBoxSetup();
s.AddVerticalSplit()
.PanelOne().PlaceControl(()=> new Label())
.PanelTwo()
.AddHorizontalSplit()
.PanelOne().PlaceControl(()=> new Label())
.PanelTwo().PlaceControl(()=> new Panel());
form.Controls.Add(s.TopControl);
```
I have now reduced the complex mechanics of the control hierarchy to a couple of verbs that are relevant for the issue at hand.
Hope this helps | What's the point of DSLs / fluent interfaces | [
"",
"c#",
"dsl",
"fluent-interface",
"api-design",
""
] |
For instance. I have some structure:
```
s_Some{
std::string lable;
s_some_junk some_junk;
};
```
And a vector:
```
std::vector<s_Some> mSome;
```
And then I fill this vector with a lot of s\_Somes.
I need to find an iterator for a single s\_Some in this vector, which has a specific lable. So far I just iterate through all of this junk and match every lable with the one wanted. This looks a little bit stupid to me. Is there a better way to do so? | Option 1)
If you are compelled to use the std::vector, but once the vector is filled it stays unchanged, then you could sort the vector and use the binary search. The only cost would be the sorting then and there will be no additional overhead. Searching time is logarithmic O(logN).
Option 2)
If you have the freedom and can choose different data structure, then consider using the map (also logarithmic) or unordered\_map ( expected O(1), worst O(n) ).
I have just noticed that you said you wanted to match every label with the one being looked for. So I conclude you can have duplicate labels. Then for point 2 use corresponding multi\_map containers, while for point 1 things get a bit messier. | If you are to search only a few times or if your vector is likely to have different content every time you search, there's unfortunately no alternative; you will have to iterate through the whole vector.
If however your vector is not going to change once created and you have to run a large number of searches, do this:
1. Sort the vector in the ascending order of strings (the way they lie in the dictionary, that is).
2. Once thus sorted, use [binary search algorithm](http://en.wikipedia.org/wiki/Binary_search) for all searches.
This will be far quicker. | What is the nicest way to find a specific string in vector? | [
"",
"c++",
"string",
"stl",
"vector",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.