Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a .Net 2.0 app that is used internally and we want to use the WebBrowser control to access some Web resources. We want to add encryption to these sites using SSL using self signed certificates.
My question is if there is way to disable all the warnings about the SSL keys coming from an untrusted source? I would... | I do not believe there is a work around for this, you will always get the warning when accessing the above mentioned web resources via the WebBrowser control (or Internet Explorer for that matter) You could however distribute the **root** cert via Group Policy. | You can do this by hooking dialogs (as someone above send the link) but then implementing SSL will be pointless. Because when an attack does the MITM attack you'll ignore the warnings and continue anyway. Better potion your installer might install the certificate in the first place. | Access Intranet via SSL using WebBrowser Winforms Control | [
"",
"c#",
".net",
"user-interface",
"browser",
""
] |
I'm using the 'using' declaration in C++ to add std::string and std::vector to the local namespace (to save typing unnecessary 'std::'s).
```
using std::string;
using std::vector;
class Foo { /*...*/ };
```
What is the scope on this declaration? If I do this in a header, will it inject these 'using' declarations int... | When you #include a header file in C++, it places the whole contents of the header file into the spot that you included it in the source file. So including a file that has a `using` declaration has the exact same effect of placing the `using` declaration at the top of each file that includes that header file. | There's nothing special about header files that would keep the `using` declaration out. It's a simple text substitution before the compilation even starts.
You can limit a `using` declaration to a scope:
```
void myFunction()
{
using namespace std; // only applies to the function's scope
vector<int> myVector;
}... | What's the scope of the "using" declaration in C++? | [
"",
"c++",
""
] |
Some of my data are 64-bit integers. I would like to send these to a JavaScript program running on a page.
However, as far as I can tell, integers in most JavaScript implementations are 32-bit signed quantities.
My two options seem to be:
1. Send the values as strings
2. Send the values as 64-bit floating point numb... | This seems to be less a problem with JSON and more a problem with Javascript itself. What are you planning to do with these numbers? If it's just a magic token that you need to pass back to the website later on, by all means simply use a string containing the value. If you actually have to do arithmetic on the value, y... | There is in fact a limitation at JavaScript/ECMAScript level of precision to 53-bit for integers (they are stored in the mantissa of a "double-like" 8 bytes memory buffer). So transmitting big numbers as JSON won't be unserialized as expected by the JavaScript client, which would truncate them to its 53-bit resolution.... | What is the accepted way to send 64-bit values over JSON? | [
"",
"javascript",
"json",
"64-bit",
""
] |
At work one of our target platforms is a resource constrained mini-server running Linux (kernel 2.6.13, custom distribution based on an old Fedora Core). The application is written in Java (Sun JDK 1.6\_04). The Linux OOM killer is configured to kill processes when memory usage exceeds 160MB. Even during high load our ... | This is pretty much the way \*nix (and linux) have worked since the dawn of time(or atleat the dawn of mmus).
To create a new process on \*nixes you call fork(). fork() creates a copy of the calling process with all its memory mappings, file descriptors, etc. The memory mappings are done copy-on-write so (in optimal c... | Well, I personally doubt that this is true, since Linux's fork() is done via copy-on-write since God knows when (at least, 2.2.x kernels had it, and it was somewhere in the 199x).
Since OOM killer is believed to be a rather crude instrument which is known to misfire (f.e., it does not necessary kills the process that ... | From what Linux kernel/libc version is Java Runtime.exec() safe with regards to memory? | [
"",
"java",
"linux",
"memory",
"out-of-memory",
""
] |
Python 3.0 is in beta with a final release coming shortly. Obviously it will take some significant time for general adoption and for it to eventually replace 2.x.
I am writing a tutorial about certain aspects of programming Python. I'm wondering if I should do it in Python 2.x or 3.0? (not that the difference is huge)... | Start with 2.x. Most existing libraries will be on 2.x for a long time. Last year, [Guido himself said that it would be "two years"](http://www.artima.com/weblogs/viewpost.jsp?thread=211200) until you needed to learn 3.0; there's still another year left. Personally, I think it will be longer. People writing code on 2.x... | Van Rossum (creator of python) explains that "if you're starting a brand new thing, you should use 3.0." So most people looking to get started should even START with 3.0. It will be useful especially since there are probably very few out there now.
the [article](http://www.linux.com/feature/150399) | Tutorial for Python - Should I use 2.x or 3.0? | [
"",
"python",
"python-3.x",
"python-2.x",
""
] |
What's the best way for constructing headers, and footers? Should you call it all from the controller, or include it from the view file? I'm using CodeIgniter, and I'm wanting to know what's the best practice for this. Loading all the included view files from the controller, like this?
```
class Page extends Controlle... | You could also try it this way -- define a default view template, which then pulls in the content based on a variable ('content' in my example) passed by the controller.
In your controller:
```
$data['content'] = 'your_controller/index';
// more code...
$this->load->vars($data);
$this->load->view('layouts/default')... | Actually, after researching this quite a bit myself, I came to the conclusion that the best practice for including headers and footers in MVC is a third option - namely extending a base controller. That will give you a little more flexibility than the text's suggestion, particularly if you're building a very modular la... | Best Practices: What's the Best Way for Constructing Headers and Footers? | [
"",
"php",
"codeigniter",
"templates",
""
] |
I have an application that launches a webpage in the "current" browser when the user selects it. This part of my app works fine in the Windows version but I can't figure out how to do this in Linux build.
Right now the Linux version is hardcoded for Firefox in a specific directory and runs a new instance of it each ti... | If you're writing this for modern distros, you can use `xdg-open`:
```
$ xdg-open http://google.com/
```
If you're on an older version you'll have to use a desktop-specific command like `gnome-open` or `exo-open`. | xdg-open is the new standard, and you should use it when possible. However, if the distro is more than a few years old, it may not exist, and alternative mechanisms include $BROWSER (older attempted standard), gnome-open (Gnome), kfmclient exec (KDE), exo-open (Xfce), or parsing mailcap yourself (the text/html handler ... | Launch web page from my application in Linux | [
"",
"c++",
"c",
"linux",
"browser",
""
] |
I'm working on a sparse matrix class that **needs** to use an array of `LinkedList` to store the values of a matrix. Each element of the array (i.e. each `LinkedList`) represents a row of the matrix. And, each element in the `LinkedList` array represents a column and the stored value.
In my class, I have a declaration... | You can't use generic array creation. It's a flaw/ feature of java generics.
The ways without warnings are:
1. Using List of Lists instead of Array of Lists:
```
List< List<IntegerNode>> nodeLists = new LinkedList< List< IntegerNode >>();
```
2. Declaring the special class for Array of Lists:
```
cla... | For some reason you have to cast the type and make the declaration like this:
```
myMatrix = (LinkedList<IntegerNode>[]) new LinkedList<?>[numRows];
``` | Cannot create an array of LinkedLists in Java...? | [
"",
"java",
"arrays",
"generics",
""
] |
Using Apache's commons-httpclient for Java, what's the best way to add query parameters to a GetMethod instance? If I'm using PostMethod, it's very straightforward:
```
PostMethod method = new PostMethod();
method.addParameter("key", "value");
```
GetMethod doesn't have an "addParameter" method, though. I've discover... | Post methods have post parameters, but [get methods do not](http://www.cs.tut.fi/~jkorpela/forms/methods.html).
Query parameters are embedded in the URL. The current version of HttpClient accepts a string in the constructor. If you wanted to add the key, value pair above, you could use:
```
String url = "http://www.e... | It's not just a matter of personal preference. The pertinent issue here is URL-encoding your parameter values, so that the values won't get corrupted or misinterpreted as extra delimiters, etc.
As always, it is best to read the API documentation in detail:
[HttpClient API Documentation](http://hc.apache.org/httpclient... | How do I add query parameters to a GetMethod (using Java commons-httpclient)? | [
"",
"java",
"httpclient",
"getmethod",
""
] |
I often need to design a dialog in Delphi/C++Builder that allows various properties of an object to be modified, and the code to use it typically looks like this.
```
Dialog.Edit1.Text := MyObject.Username;
Dialog.Edit2.Text := MyObject.Password;
// ... many more of the same
if (Dialog.ShowModal = mrOk)
begin
MyOb... | well, something that I feel completely invaluable is the [GExperts](http://www.gexperts.org) plugin wizard "Reverse Statement" which is invoked after installing GExperts by pressing Shift + ALT + R
What it does is automatically switch the assignments around for the highlighted block. For example:
```
edit1.text := db... | Here's my variation on this. What I did, having got fed up with the same repetitive code, was to name all the edit boxes according to the XML node names I wanted, then iterate around the components and output their values. The XML code should be obvious, and I only have an edit and checkbox, but you should be able to s... | Avoiding Dialog Boilerplate in Delphi and /or C++ | [
"",
"c++",
"delphi",
"modal-dialog",
"boilerplate",
""
] |
I have a class with both a static and a non-static interface in C#. Is it possible to have a static and a non-static method in a class with the same name and signature?
I get a compiler error when I try to do this, but for some reason I thought there was a way to do this. Am I wrong or is there no way to have both sta... | No you can't. The reason for the limitation is that static methods can also be called from non-static contexts without needing to prepend the class name (so MyStaticMethod() instead of MyClass.MyStaticMethod()). The compiler can't tell which you're looking for if you have both.
You can have static and non-static metho... | Actually, there kind of is a way to accomplish this by explicitly implementing an interface. It is not a perfect solution but it can work in some cases.
```
interface IFoo
{
void Bar();
}
class Foo : IFoo
{
static void Bar()
{
}
void IFoo.Bar()
{
Bar();
}
}
```
I sometimes run in... | Static and Instance methods with the same name? | [
"",
"c#",
".net",
"oop",
""
] |
In `.NET` (at least in the 2008 version, and maybe in 2005 as well), changing the `BackColor` property of a `DateTimePicker` has absolutely no affect on the appearance. How do I change the background color of the text area, not of the drop-down calendar?
***Edit:*** I was talking about Windows forms, not ASP. | According to [MSDN](http://msdn.microsoft.com/en-us/library/0625h0ta.aspx) :
> Setting the `BackColor` has no effect on
> the appearance of the `DateTimePicker`.
You need to write a custom control that extends `DateTimePicker`. Override the `BackColor` property and the `WndProc` method.
Whenever you change the `Back... | There is a free implementation derived from `DateTimePicker` that allows you to change `BackColor` property on change.
See the CodeProject website: [`DateTimePicker` with working `BackColor`](http://www.codeproject.com/KB/selection/DateTimePicker_With_BackC.aspx) | Changing the background color of a DateTimePicker in .NET | [
"",
"c#",
".net",
"vb.net",
"winforms",
""
] |
I'm using the following code to loop through a directory to print out the names of the files. However, not all of the files are displayed. I have tried using **clearstatcache** with no effect.
```
$str = '';
$ignore = array('.', '..');
$dh = @opendir( $path );
if ($dh === FALSE)
{
// error... | Your `break` keywords messes up your code:
Your loop very likely first encounters the '.' directory and than breaks out of your while loop.
try replacing it with a `continue` and you should be fine. | Continue won't work either, because you will skip the line that reads the next file.
You could get rid of the first `$file = readdir( $dh );` and then do
```
while (false !== ($file = readdir($dh))) {
if (in_array($file, $ignore, TRUE)) { continue; }
$str .= $file."\n";
}
``` | PHP readdir is not reading some files | [
"",
"php",
""
] |
Is there any advantage of using
[**java.util.concurrent.CountdownLatch**](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html)
instead of
[**java.util.concurrent.Semaphore**](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Semaphore.html)?
As far as I can tell the follo... | `CountDownLatch` is frequently used for the exact opposite of your example. Generally, you would have many threads blocking on `await()` that would all start simultaneously when the countown reached zero.
```
final CountDownLatch countdown = new CountDownLatch(1);
for (int i = 0; i < 10; ++ i) {
Thread racecar = n... | [CountDownLatch](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/CountDownLatch.html) is used to start a series of threads and then wait until all of them are complete (or until they call `countDown()` a given number of times.
Semaphore is used to control the number of concurrent threads that are using ... | CountDownLatch vs. Semaphore | [
"",
"java",
"multithreading",
"concurrency",
"semaphore",
"countdownlatch",
""
] |
***Imagine*** a base class with many constructors and a virtual method
```
public class Foo
{
...
public Foo() {...}
public Foo(int i) {...}
...
public virtual void SomethingElse() {...}
...
}
```
and now i want to create a descendant class that overrides the virtual method:
```
public class Bar : ... | Yes, you will have to implement the constructors that make sense for each derivation and then use the `base` keyword to direct that constructor to the appropriate base class or the `this` keyword to direct a constructor to another constructor in the same class.
If the compiler made assumptions about inheriting constru... | 387 constructors?? That's your main problem. How about this instead?
```
public Foo(params int[] list) {...}
``` | How to inherit constructors? | [
"",
"c#",
"inheritance",
"constructor",
""
] |
Is there a `Python` module for converting `wiki markup` to other languages (e.g. `HTML`)?
A similar question was asked here, [What's the easiest way to convert wiki markup to html](https://stackoverflow.com/questions/45991/whats-the-easiest-way-to-convert-wiki-markup-to-html), but no `Python` modules are mentioned.
J... | Django uses the following libraries for markup:
* [Markdown](http://www.freewisdom.org/projects/python-markdown/)
* [Textile](http://pypi.python.org/pypi/textile)
* [reStructuredText](http://docutils.sourceforge.net/rst.html)
You can see [how they're used in Django](http://code.djangoproject.com/browser/django/trunk/... | [mwlib](https://github.com/pediapress/mwlib) provides ways of converting MediaWiki formatted text into HTML, PDF, DocBook and OpenOffice formats. | Python module for wiki markup | [
"",
"python",
"wiki",
"markup",
""
] |
Note, I realize that this has been addressed [here](https://stackoverflow.com/questions/944/unhandled-exception-handler-in-net-11). That post discusses exception handling in .NET 1.1 while implying that there is a better solution for >.NET 2.0 so this question is specifically about the more recent .NET versions.
I hav... | For Windows Forms threads (which call Application.Run()), assign a ThreadException handler at the beginning of Main(). Also, I found it was necessary to call SetUnhandledExceptionMode:
```
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.Automatic);
Application.ThreadException += ShowUnhandledException;
Ap... | caveat: not familiar with 3.5 yet, there may be a better answer ...
...but my understanding is that by the time the event gets to the unhandled exception handler, the app is probably going to die - and if it doesn't die, it may be so corrupted that it should die anyway
if you are already handling a db-not-there case ... | Is there a way to define an action for unhandled exceptions in a WinForms .NET 3.5 app? | [
"",
"c#",
".net",
"exception",
""
] |
Suppose I have a base class B, and a derived class D. I wish to have a method foo() within my base class that returns a new object of whatever type the instance is. So, for example, if I call B.foo() it returns an object of type B, while if I call D.foo() it returns an object of type D; meanwhile, the implementation re... | Don't. Make the "foo" method abstract.
```
abstract class B {
public abstract B foo();
}
```
Or receive an abstract factory through the base class constructor:
```
abstract class B {
private final BFactory factory;
protected B(BFactory factory) {
this.factory = factory;
}
public B foo() {... | As long as each class has a default constructor:
```
public B instance() throws Exception {
return getClass().newInstance();
}
``` | Java: Newbie-ish inheritance question | [
"",
"java",
"inheritance",
"types",
"derived-class",
"base-class",
""
] |
I have an application running in tomcat that has a bunch of configuration files that are different for each environment it runs in (dev, testing, and production). But not every line in a config file will be different between environments so there's invariably duplicated information that doesn't get updated if something... | 1. Assign reasonable default values for all properties in the properties files distributed within your .war file.
2. Assign environment-specific values for the appropriate properties in webapp context (e.g. conf/server.xml or conf/Catalina/localhost/yourapp.xml)
3. Have your application check the context first (for the... | A Properties file is what I've always used. It's editable by hand as well as in in your software and the Properties object can read itself in and write itself out to the filesystem. Here's the javadoc page:
<http://java.sun.com/j2se/1.4.2/docs/api/java/util/Properties.html> | What is the best way to deal with environment specific configuration in java? | [
"",
"java",
"configuration",
"tomcat",
""
] |
I'd like to sprinkle some print statements in my code to show where I am and print important values to a console window.
How do I do that, but then be able to turn it off for the release version? | All calls to [`System.Diagnostics.Debug.Print()`](http://msdn.microsoft.com/en-us/library/system.diagnostics.debug.print.aspx) will be removed when you switch to a release version. | Use [Log4net](http://logging.apache.org/log4net/index.html) with logging at debug level in release and warn or error level in production.
Benefit to this is that you can turn logging back on in the release environment if you have problems there that you can't recreate in development.
[EDIT] FWIW, I find that I do a *... | Disable Debugging Output | [
"",
"c#",
".net",
"debugging",
"console",
""
] |
A prospective client wants to have a calendar feature on their website. They want the option to go edit this calendar to update the events. Does Word Press offer something like this? | I've seen people use Google Calendar for this. Then you can easily embed google cal in your web pages. Also, if others use Google Cal they can add evens to their calendars.
<http://www.google.com/support/calendar/bin/answer.py?hl=en&answer=41207>
Update: Looks like this plugin will help with getting google cal into W... | Sounds like you might be searching for [this](http://wordpress.org/extend/plugins/event-calendar/). | Creating a client editable events calendar in html or php | [
"",
"php",
"html",
"wordpress",
"calendar",
""
] |
Say you have a web form with some fields that you want to validate to be only some subset of alphanumeric, a minimum or maximum length etc.
You can validate in the client with javascript, you can post the data back to the server and report back to the user, either via ajax or not. You could have the validation rules i... | all of the above:
1. client-side validation is more convenient for the user
2. but you can't trust the client so the code-behind should also validate
3. similarly the database can't trust that you validated so validate there too
EDIT: i see that you've edited the question to ask for a single point of specification fo... | To answer the actual question:
First of all it isn't allways the case that the databse restriction matches client side restrictions. So it would probably be a bad idea to limit yourself to only validate based on database constraints.
But then again, you do want the databse constraints to be reflected in your datamode... | Where do you record validation rules for form data in a web application? | [
"",
"javascript",
"design-patterns",
"validation",
""
] |
Is it possible to see the return value of a method after the line has been run and before the instruction pointer returns to the calling function?
I am debugging code I can't modify *(read: don't want to re-compile a third party library)*, and sometimes it jumps to code I don't have source to or the return expression ... | This feature was added to Eclipse version 4.7 M2 under [Eclipse bug 40912](https://bugs.eclipse.org/bugs/show_bug.cgi?id=40912).
To use it:
* step over the `return` statement (using "Step Over" or "Step Return")
* now the first line in the variable view will show the result of the return statement, as "[statement xxx... | Found a really good shortcut for this.
Select the expression which returns the value and press
```
Ctrl + Shift + D
```
This will display the value of the return statement. This is really helpful in cases where you can't or don't want to change just for debugging purpose.
Hope this helps.
Note: Have not tested this... | Can I find out the return value before returning while debugging in Eclipse? | [
"",
"java",
"eclipse",
"debugging",
"return-value",
""
] |
Having difficulty articulating this correlated subquery. I have two tables fictitious tables, foo and bar. foo has two fields of foo\_id and total\_count. bar has two fields, seconds and id.
I need to aggregate the seconds in bar for each individual id and update the total\_count in foo. id is a foreign key in bar for... | ```
UPDATE foo f1
SET total_count = (SELECT SUM(seconds)
FROM bar b1 WHERE b1.id = f1.foo_id)
```
You should have access to the appropriate foo id within the sub-query, so there is no need to join in the table. | In larger data sets, correlated subqueries can be very resource-intensive. Joining to a derived table containing the appropriate aggregates can be much more efficient:
```
create table foo ( foo_id int identity, total_count int default 0 )
create table bar ( foo_id int, seconds int )
insert into foo default values
in... | MySQL correlated subquery | [
"",
"mysql",
"sql",
"inner-join",
""
] |
What is the best way for converting phone numbers into international format (E.164) using Java?
Given a 'phone number' and a country id (let's say an ISO country code), I would like to convert it into a standard E.164 international format phone number.
I am sure I can do it by hand quite easily - but I would not be s... | Google provides a library for working with phone numbers. The same one they use for Android
<http://code.google.com/p/libphonenumber/>
```
String swissNumberStr = "044 668 18 00"
PhoneNumberUtil phoneUtil = PhoneNumberUtil.getInstance();
try {
PhoneNumber swissNumberProto = phoneUtil.parse(swissNumberStr, "CH");
} ... | Speaking from experience at writing this kind of thing, it's really difficult to do with 100% reliability. I've written some Java code to do this that is reasonably good at processing the data we have but won't be applicable in every country. Questions you need to ask are:
Are the character to number mappings consiste... | What is the best way for converting phone numbers into international format (E.164) using Java? | [
"",
"java",
"validation",
"formatting",
"phone-number",
""
] |
Can anyone recommend any good resources for learning C++ Templates?
Many thanks. | I've found [cplusplus.com](http://www.cplusplus.com/) to be helpful on numerous occasions. Looks like they've got a pretty good intro to [templates.](http://www.cplusplus.com/doc/tutorial/templates.html)
If its an actual book you're looking for, [Effective C++](https://rads.stackoverflow.com/amzn/click/com/0321334876)... | I recomned that you get [C++ Templates - The Complete Guide](http://www.josuttis.com/tmplbook/) it's an excellent resource and reference. | Learning C++ Templates | [
"",
"c++",
"templates",
""
] |
I want to call `ShowDialog()` when a keyboard hook event is triggered, but I'm having some difficulties:
* ShowDialog() blocks, so I can't call it from the hook triggered event, because it will block the OS.
* I can start a new thread and call `ShowDialog()` from there, but I get some nasty exception. I guess I can't ... | The problem may be that you are trying to put UI in a non-UI thread. Make your event fire from another thread and invoke the method that runs `ShowDialog()` from your UI thread.
Essentially, you want to keep your UI on the UI thread and move anything else to a back ground thread.
Check out [Gekki Software](http://www... | I'm not sure about ShowDialog, but whenever you get an exception when trying to do something with the UI in a background thread, it means you should use the UI dispatcher.
Try calling the BeginInvoke method (if you are on Windows Forms) of any UI object you control with a delegate that calls the showdialog.
Also, mak... | ShowDialog() from keyboard hook event in C# | [
"",
"c#",
"keyboard-hook",
""
] |
I would like to know how long it's been since the user last hit a key or moved the mouse - not just in my application, but on the whole "computer" (i.e. display), in order to guess whether they're still at the computer and able to observe notifications that pop up on the screen.
I'd like to do this purely from (Py)GTK... | [Gajim](http://www.gajim.org/) does it this way on Windows, OS X and GNU/Linux (and other \*nixes):
1. [Python wrapper module](https://dev.gajim.org/gajim/gajim/blob/89c7eb6e6ab3f61a188c6cee063a000526df522c/gajim/common/sleepy.py) (also includes Windows idle time detection code, using `GetTickCount` with `ctypes`);
2.... | If you use PyGTK and X11 on Linux, you can do something like this, which is based on what Pidgin does:
```
import ctypes
import ctypes.util
import platform
class XScreenSaverInfo(ctypes.Structure):
_fields_ = [('window', ctypes.c_long),
('state', ctypes.c_int),
('kind', ctypes.c_in... | How can I determine the display idle time from Python in Windows, Linux, and MacOS? | [
"",
"python",
"winapi",
"gtk",
"pygtk",
"pywin32",
""
] |
I found this:
<http://www.evolt.org/failover-database-connection-with-php-mysql>
and similar examples. But is there a better way?
I am thinking along the lines of the [Automatic Failover Client](http://www.microsoft.com/technet/prodtechnol/sql/bestpractice/implappfailover.mspx#EMD) in the MS SQL Native Client. | It's traditional to handle failover strategies at the system level; that way all applications can enjoy a robust environment.
I'd like to refer to [MySQL failover strategy](http://dev.mysql.com/tech-resources/articles/failover-strategy-part1.html) and [MySQL proxy](http://forge.mysql.com/wiki/MySQL_Proxy). The latter ... | There's nothing built in to handle that in PHP. You have to write the code yourself.
The best approach would be to abstract your database access and create a class that can encapsulate the failover logic.
Here's some code, off the cuff:
```
interface MySQL_Interface {
public function query($sql);
}
class MySQL_... | Does PHP have a built in mechanism to failover from one database server to another? | [
"",
"php",
"mysql",
"database",
"failover",
""
] |
How do I pull out the filename from a full path using regular expressions in C#?
Say I have the full path `C:\CoolDirectory\CoolSubdirectory\CoolFile.txt`.
How do I get out CoolFile.txt using the .NET flavor of regular expressions? I'm not really good with regular expressions, and my RegEx buddy and me couldn't figur... | ```
// using System.Text.RegularExpressions;
/// <summary>
/// Regular expression built for C# on: Tue, Oct 21, 2008, 02:34:30 PM
/// Using Expresso Version: 3.0.2766, http://www.ultrapico.com
///
/// A description of the regular expression:
///
/// Any character that is NOT in this class: [\\], any number of... | Why must you use regular expressions? .NET has the built-in `Path.GetFileName()` method specifically for this which works across platforms and filesystems. | Parse filename from full path using regular expressions in C# | [
"",
"c#",
".net",
"regex",
""
] |
Is it ever appropriate to abandon the "getMyValue()" and "setMyValue()" pattern of getters and setters if alternative function names make the API more obvious?
For example, imagine I have this class in C++:
```
public class SomeClass {
private:
bool mIsVisible;
public:
void draw();
void erase();
}
```
I... | Have a read of the article "[Tell, Don't Ask](http://www.pragprog.com/articles/tell-dont-ask)" over at the Pragmatic Programmers web site and I think you'll see that the second example is the way to go.
Basically, you shouldn't be spreading the logic out through your code which is implied with your first example, name... | In the example you gave, `show()` and `hide()` make a lot of sense, at least to me.
On the other hand, if you had a property `skinPigment` and you decided to make functions called `tanMe()` and `makeAlbino()` that would be a really poor, non-obvious choice.
It is subjective, you have to try to think the way your user... | Which is more appropriate: getters and setters or functions? | [
"",
"c++",
"coding-style",
"setter",
"getter",
""
] |
I'm trying to determine the best way of having a PHP script determine which server the script/site is currently running on.
At the moment I have a `switch()` that uses `$_SERVER['SERVER_NAME'] . ':' . $_SERVER['SERVER_PORT']` to determine which server it's on. It then sets a few paths, db connection parameters, SMTP p... | How about using **$\_SERVER['SERVER\_ADDR']** and base your identity off the IP address of the server.
UPDATE: In a virtual host situation, you might also like to concatenate the IP with the document root path like so:
```
$id = $_SERVER['SERVER_ADDR'] . $_SERVER['DOCUMENT_ROOT'];
``` | We use the $\_SERVER['HTTP\_HOST'] variable to create the filename of a PHP include file which contains all the vhost-specific information (we deploy the same software to a lot of vhosts)
I like this technique, as you can get clever with it to build hierarchies of configurations, e.g. for www.foo.com,
* try to load *... | What is the best way to determine which server the script is on and therefore the configuration in PHP? | [
"",
"php",
"configuration",
""
] |
I have a third-party editor that basically comprises a textbox and a button (the DevExpress ButtonEdit control). I want to make a particular keystroke (`Alt` + `Down`) emulate clicking the button. In order to avoid writing this over and over, I want to make a generic KeyUp event handler that will raise the ButtonClick ... | Here's a demo using generics (error checks omitted):
```
using System;
using System.Reflection;
static class Program {
private class Sub {
public event EventHandler<EventArgs> SomethingHappening;
}
internal static void Raise<TEventArgs>(this object source, string eventName, TEventArgs eventArgs) where TEvent... | In general, you can't. Think of events as basically pairs of `AddHandler`/`RemoveHandler` methods (as that's basically what what they are). How they're implemented is up to the class. Most WinForms controls use [`EventHandlerList`](http://msdn.microsoft.com/en-us/library/system.componentmodel.eventhandlerlist.aspx) as ... | How do I raise an event via reflection in .NET/C#? | [
"",
"c#",
".net",
"event-handling",
"devexpress",
""
] |
I want to read all items of a feed in C#. The solutions I've found are only for the latest items like just the last 10 days.
Anybody has a good solution for this? | If you can tie into something like Google Reader, which archives old feed items (although I'm not sure it's a permanent archive or not), then perhaps you can accomplish this. | Libraries for reading feeds typically read all the data in the feed, but feeds typically only contain recent data - you need a source of data that includes older items, not a better library for reading the data you have.
Most entities publish feeds to allow people to track when new content is published, not to make al... | How do I read all feed items? | [
"",
"c#",
""
] |
The following code executes a simple insert command. If it is called 2,000 times consecutively (to insert 2,000 rows) an OleDbException with message = "System Resources Exceeded" is thrown. Is there something else I should be doing to free up resources?
```
using (OleDbConnection conn = new OleDbConnection(connectionS... | The system resources exceeded error is not coming from the managed code, its coming from you killing your database (JET?)
You are opening way too many connections, way too fast...
Some tips:
* Avoid round trips by not opening a new connection for every single command, and perform the inserts using a single connectio... | I tested this code out with an Access 2007 database with no exceptions (I went as high as 13000 inserts).
However, what I noticed is that it is terribly slow as you are creating a connection every time. If you put the "using(connection)" outside the loop, it goes much faster. | OleDbException System Resources Exceeded | [
"",
"c#",
"oledbexception",
""
] |
Does anyone know of crossbrowser equivalent of explicitOriginalTarget event parameter? This parameter is Mozilla specific and it gives me the element that caused the blur. Let's say i have a text input and a link on my page. Text input has the focus. If I click on the link, text input's blur event gives me the link ele... | There is no equivalent to explicitOriginalTarget in any of the other than Gecko-based browsers. In Gecko this is an internal property and it is not supposed to be used by an application developer (maybe by XBL binding writers). | The rough equivalent for Mozilla's .explicitOriginalTarget in IE is document.activeElement. I say rough equivalent because it will sometimes return a slightly different level in the DOM node tree depending on your circumstance, but it's still a useful tool. Unfortunately I'm still looking for a Google Chrome equivalent... | Crossbrowser equivalent of explicitOriginalTarget event parameter | [
"",
"javascript",
"events",
"cross-browser",
"scriptaculous",
""
] |
I have multiple layers in an application and i find myself having to bubble up events to the GUI layer for doing status bar changes, etc . . I find myself having to write repeated coded where each layer simply subscribes to events from the lower layer and then in the call back simply raise an event up the chain. Is the... | If all you're doing is firing an event handler from another event handler, you can cut out the middle man and hook the event handlers directly in the add/remove blocks for the event.
For example, if you have a UserControl with a "SaveButtonClick" event, and all you want to do when is call the event handler when the "S... | Have a read of Jeremy Miller's blog "The Shade Tree Developer", especially his [*Write Your Own CAB* series](http://codebetter.com/jeremymiller/2007/07/26/the-build-your-own-cab-series-table-of-contents/) - the command pattern stuff he talks about there is probably what you need. | Bubbling up events . | [
"",
"c#",
"winforms",
"events",
""
] |
Basically, I'm trying to selectively copy a table from one database to another. I have two different [Oracle] databases (e.g., running on different hosts) with the same schema. I'm interested in a efficient way to load Table A in DB1 with the result of running a select on Table A in DB2. I'm using JDBC, if that's relev... | Use a database link, and use create table as select.
```
create database link other_db connect to remote_user identified by remote_passwd using remote_tnsname;
create table a as select * from a@other_db;
``` | If the databases are from the same vendor they usually provide a native way to make a view
of a table in another database. in which case, a "select into" query will do it no problem
Oracle, for example, has the database link which works pretty well.
Outside of that you are going to have to make a connection to each d... | Bulk Row Transfer between Oracle Databases with a Select Filter | [
"",
"java",
"database",
"oracle",
"html-select",
""
] |
Here are the requirements:
Must be alphanumeric, 8-10 characters so that it is user friendly. These will be stored as unique keys in database. I am using Guids as primary keys so an option to use GUids to generate these unique Ids would be preferable.
I am thinking on the lines of a base-n converter that takes a Guid... | You might consider [base 36.](http://en.wikipedia.org/wiki/Base_36) in that it can do letters and numbers.
Consider removing I (eye) and O (Oh) from your set so they don't get mixed up with 1 (one) and 0 (zero). Some people might complain about 2 and Z as well. | ```
8 characters - perfectly random - 36^8 = 2,821,109,907,456 combinations
10 characters - perfectly random - 36^10 = 3,656,158,440,062,976 combinations
GUID's - statistically unique* - 2^128 = 340,000,000,000,000,000,000,000,000,000,000,000,000 combinations
```
\* [Is a GUID unique 100% of the time? [stackoverflow]]... | What are the options for generating user friendly alpha numeric IDs (like business id, SKU) | [
"",
"c#",
".net",
"algorithm",
"guid",
""
] |
I want to sort members by name in the source code. Is there any easy way to do it?
I'm using NetBeans, but if there is another editor that can do that, just tell me the name of it. | In Netbeans 8.0.1:
```
Tools -> Options -> Editor -> Formatting -> Category: Ordering
```

Then:
```
Source -> Organize Members
```
 | Eclipse can do it. | How can I sort class members by name in NetBeans, or another Java IDE? | [
"",
"java",
"sorting",
"netbeans",
"methods",
""
] |
Let's say that you have overridden an object's equals() and hashCode() methods, so that they use the object's fields.
How you do you check if two references are to the same object, ala the stock equals() method? | Use `==` on objects to perform identity comparison.
That is what the default implementation of `equals()` does, but one normally overrides `equals()` to serve as an "equivalent content" check. | That's what the == operator does. | Comparing references in Java | [
"",
"java",
""
] |
Often, programmers write code that generates other code.
(The technical term is [metaprogramming](http://en.wikipedia.org/wiki/Metaprogramming "Wikipedia article on metaprogramming"), but it is more common than merely cross-compilers; think about every PHP web-page that generates HTML or every XSLT file.)
One area I ... | In the more general case, I have written XSLT code that generates C++ database interface code. Although at first I tried to output correctly indented code from the XSLT, this quickly became untenable. My solution was to completely ignore formatting in the XSLT output, and then run the resulting very long line of code t... | A technique that I use when the generating code dominates over the generated code is to pass an indent parameter around.
e.g., in Python, generating more Python.
```
def generateWhileLoop(condition, block, indentPrefix = ""):
print indentPrefix + "while " + condition + ":"
generateBlock(block, indentPrefix + ... | Indenting for code-generation | [
"",
"php",
"code-generation",
"metaprogramming",
""
] |
If the C++ runtime msvcr80.dll is missing from a compiled library, is there any way to determine which version was used to create the library or to get it to run on a later version of msvcr80.dll? | The VC80 SP1 CRT redistributable package will install both the RTM and SP1 versions of the C runtime into `%SystemRoot%\WinSxS` (assuming you're using Windows XP or Vista; Windows 2000 doesn't support side-by-side assemblies). If you have VC8 installed, the CRT redistributable package is in `%ProgramFiles%\Microsoft Vi... | [Dependency Walker](http://www.dependencywalker.com/) will help you answer this question. | Missing msvcr80.dll | [
"",
"c++",
"windows",
"dll",
"dependencies",
""
] |
Is there any libraries that would allow me to use the same known notation as we use in BeanUtils for extracting POJO parameters, but for easily replacing placeholders in a string?
I know it would be possible to roll my own, using BeanUtils itself or other libraries with similar features, but I didn't want to reinvent ... | Rolling your own using BeanUtils wouldn't take too much wheel reinvention (assuming you want it to be as basic as asked for). This implementation takes a Map for replacement context, where the map key should correspond to the first portion of the variable lookup paths given for replacement.
```
import java.lang.reflec... | Spring Framework should have a feature that does this (see Spring JDBC example below). If you can use groovy (just add the groovy.jar file) you can use Groovy's GString feature to do this quite nicely.
Groovy example
```
foxtype = 'quick'
foxcolor = ['b', 'r', 'o', 'w', 'n']
println "The $foxtype ${foxcolor.join()} f... | Simplest way to use "BeanUtils alike" replace | [
"",
"java",
"string",
"replace",
"placeholder",
""
] |
I am looking get to grips with functional programming concepts.
I've used Javascript for many years for client side scripting in web applications and apart from using prototypes it was all simple DOM manipulation, input validation etc.
Of late, I have [often read](http://eloquentjavascript.net/chapter6.html) that Jav... | JavaScript supports first class functions. See *[Use functional programming techniques to write elegant JavaScript](http://www.ibm.com/developerworks/library/wa-javascript.html)*. | [Higher Order Javascript](http://interglacial.com/hoj/hoj.html) is a *great* way to get familiar with the functional aspects of javascript. It's also a relatively short read in case you want to get your feet wet without diving into a larger book. | Javascript as a functional language | [
"",
"javascript",
"functional-programming",
"language-features",
""
] |
What is the PHP preg\_replace in C#?
I have an array of string that I would like to replace by an other array of string. Here is an example in PHP. How can I do something like that in C# without using .Replace("old","new").
```
$patterns[0] = '/=C0/';
$patterns[1] = '/=E9/';
$patterns[2] = '/=C9/';
$replacements[0]... | ```
public static class StringManipulation
{
public static string PregReplace(string input, string[] pattern, string[] replacements)
{
if (replacements.Length != pattern.Length)
throw new ArgumentException("Replacement and Pattern Arrays must be balanced");
for (int i = 0; i < patte... | Real men use regular expressions, but here is an extension method that adds it to String if you wanted it:
```
public static class ExtensionMethods
{
public static String PregReplace(this String input, string[] pattern, string[] replacements)
{
if (replacements.Length != pattern.Length)
thr... | C# preg_replace? | [
"",
"c#",
".net",
".net-2.0",
"preg-replace",
""
] |
Here's a curious one. I have a class A. It has an item of class B, which I want to initialize in the constructor of A using an initializer list, like so:
```
class A {
public:
A(const B& b): mB(b) { };
private:
B mB;
};
```
Is there a way to catch exceptions that might be thrown by mB's copy-construc... | Have a read of <http://weseetips.wordpress.com/tag/exception-from-constructor-initializer-list/>)
Edit: After more digging, these are called "Function try blocks".
I confess I didn't know this either until I went looking. You learn something every day! I don't know if this is an indictment of how little I get to use ... | It's not particularly pretty:
```
A::A(const B& b) try : mB(b)
{
// constructor stuff
}
catch (/* exception type */)
{
// handle the exception
}
``` | Catching exceptions from a constructor's initializer list | [
"",
"c++",
"exception",
""
] |
If I have two variables:
```
Object obj;
String methodName = "getName";
```
Without knowing the class of `obj`, how can I call the method identified by `methodName` on it?
The method being called has no parameters, and a `String` return value. It's *a getter for a Java bean*. | Coding from the hip, it would be something like:
```
java.lang.reflect.Method method;
try {
method = obj.getClass().getMethod(methodName, param1.class, param2.class, ..);
} catch (SecurityException e) { ... }
catch (NoSuchMethodException e) { ... }
```
The parameters identify the very specific method you need (if... | Use [method invocation](http://java.sun.com/docs/books/tutorial/reflect/member/methodInvocation.html) from reflection:
```
Class<?> c = Class.forName("class name");
Method method = c.getDeclaredMethod("method name", parameterTypes);
method.invoke(objectToInvokeOn, params);
```
Where:
* `"class name"` is the name of ... | How do I invoke a Java method when given the method name as a string? | [
"",
"java",
"reflection",
"invoke",
""
] |
I use RegexBuddy while working with regular expressions. From its library I copied the regular expression to match URLs. I tested successfully within RegexBuddy. However, when I copied it as Java `String` flavor and pasted it into Java code, it does not work. The following class prints `false`:
```
public class RegexF... | Try the following regex string instead. Your test was probably done in a case-sensitive manner. I have added the lowercase alphas as well as a proper string beginning placeholder.
```
String regex = "^(https?|ftp|file)://[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]";
```
This works too:
```
String regex = "\\... | The best way to do it now is:
```
android.util.Patterns.WEB_URL.matcher(linkUrl).matches();
```
EDIT: Code of `Patterns` from <https://github.com/android/platform_frameworks_base/blob/master/core/java/android/util/Patterns.java> :
```
/*
* Copyright (C) 2007 The Android Open Source Project
*
* Licensed under the ... | Regular expression to match URLs in Java | [
"",
"java",
"regex",
"regexbuddy",
""
] |
I am using pseudo-code here, but this is in JavaScript. With the most efficient algorithm possible I am trying to find the high and low given an array of positive whole numbers. This is what I came up with, but I don't think it is probably best, and was just wondering if anyone has any other suggestions.
```
var low =... | initialise the high and low to be the first element. makes a lot more sense than picking an arbitrarily "high" or "low" number.
```
var myArray = [...],
low = myArray[0],
high = myArray[0]
;
// start looping at index 1
for (var i = 1, l = myArray.length; i < l; ++i) {
if (myArray[i] > high) {
high ... | You have to do it in `O(n)` time because you need to loop through all (`n`) of the elements to check them because any one of the elements may be the min or max. (Unless they are already sorted.)
In other words you need to loop through all elements and do the max and min check like you have.
Sorting is usually at best... | Best algorithm for determining the high and low in an array of numbers? | [
"",
"javascript",
"algorithm",
""
] |
Basically I have the following class:
```
class StateMachine {
...
StateMethod stateA();
StateMethod stateB();
...
};
```
The methods stateA() and stateB() should be able return pointers to stateA() and stateB().
How to typedef the StateMethod? | [GotW #57](http://www.gotw.ca/gotw/057.htm) says to use a proxy class with an implicit conversion for this very purpose.
```
struct StateMethod;
typedef StateMethod (StateMachine:: *FuncPtr)();
struct StateMethod
{
StateMethod( FuncPtr pp ) : p( pp ) { }
operator FuncPtr() { return p; }
FuncPtr p;
};
class Sta... | Using just typedef:
```
class StateMachine {
public:
class StateMethod;
typedef StateMethod (StateMachine::*statemethod)();
class StateMethod {
statemethod method;
StateMachine& obj;
public:
StateMethod(statemethod method_, StateMachine *obj_)
: method(method_), ... | How to typedef a pointer to method which returns a pointer the method? | [
"",
"c++",
"pointer-to-member",
""
] |
Let's say that for some reason you need to write a macro: `MACRO(X,Y)`. **(Let's assume there's a good reason you can't use an inline function.)** You want this macro to emulate a call to a function with no return value.
---
### Example 1: This should work as expected.
```
if (x > y)
MACRO(x, y);
do_something();
`... | Macros should generally be avoided; prefer inline functions to them at all times. Any compiler worth its salt should be capable of inlining a small function as if it were a macro, and an inline function will respect namespaces and other scopes, as well as evaluating all the arguments once.
If it must be a macro, a whi... | There is a rather clever solution:
```
#define MACRO(X,Y) \
do { \
cout << "1st arg is:" << (X) << endl; \
cout << "2nd arg is:" << (Y) << endl; \
cout << "Sum is:" << ((X)+(Y)) << endl; \
} while (0)
```
Now you have a single block-level stat... | How do I make a C++ macro behave like a function? | [
"",
"c++",
"c-preprocessor",
""
] |
I've seen a fair share of ungainly XML->JSON code on the web, and having interacted with Stack's users for a bit, I'm convinced that this crowd can help more than the first few pages of Google results can.
So, we're parsing a weather feed, and we need to populate weather widgets on a multitude of web sites. We're look... | There is no "one-to-one" mapping between XML and JSON, so converting one to the other necessarily requires some understanding of what you want to *do* with the results.
That being said, Python's standard library has [several modules for parsing XML](http://docs.python.org/2/library/xml.html) (including DOM, SAX, and E... | [xmltodict](https://github.com/martinblech/xmltodict) (full disclosure: I wrote it) can help you convert your XML to a dict+list+string structure, following this ["standard"](http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html). It is [Expat](http://docs.python.org/library/pyexpat.html)-based, so i... | Converting XML to JSON using Python? | [
"",
"python",
"json",
"xml",
"converters",
""
] |
At a previous employer, we were writing binary messages that had to go "over the wire" to other computers. Each message had a standard header something like:
```
class Header
{
int type;
int payloadLength;
};
```
All of the data was contiguous (header, immediately followed by data). We wanted to get to the pa... | I'd go for crime against coding.
Both methods will generate the exact same object code. The first makes it's intention clear. The second is very confusing, with the only advantage that it saves a couple keystrokes. (Just learn to freakin' type).
Also, note that NEITHER method is guaranteed to work. The sizeof() an ob... | Personally I think that if there's a crime, it's asking the header for the payload.
But as long as you're going to do it that way, 'this+1' is as good a way as any.
Justification: '&this[1]' is a general-purpose piece of code that doesn't require you to go digging through class-definitions to fully comprehend, and do... | C++ example of Coding Horror or Brilliant Idea? | [
"",
"c++",
"optimization",
"syntax",
""
] |
Something that has always bugged me is how unpredictable the `setTimeout()` method in Javascript is.
In my experience, the timer is horribly inaccurate in a lot of situations. By inaccurate, I mean the actual delay time seems to vary by 250-500ms more or less. Although this isn't a huge amount of time, when using it t... | > Are there any tricks that can be done
> to ensure that `setTimeout()` performs
> accurately (without resorting to an
> external API) or is this a lost cause?
No and no. You're not going to get anything close to a perfectly accurate timer with `setTimeout()` - browsers aren't set up for that. **However**, you don't n... | .
REF; <http://www.sitepoint.com/creating-accurate-timers-in-javascript/>
This site bailed me out on a major scale.
You can use the system clock to compensate for timer inaccuracy. If you run a timing function as a series of setTimeout calls — each instance calling the next — then all you have to do to keep it accur... | Is there a more accurate way to create a Javascript timer than setTimeout? | [
"",
"javascript",
"timer",
""
] |
I have a PHP script that initialises an image gallery. It loops through all images, checks if they are thumbnailed and watermarks them.
My shared hosting account only lets me have 30 seconds of execution per script, as set in the php.ini settings. I can't change that.
What can I do to get round this? Currently I refr... | three ideas:
1. you could offload this to a script that runs on the server (PHP CLI perhaps?) and have your current script check the progress (still running! check back later!).
2. if javascript is ok in your environment, perhaps you could make ajax calls to handle this as well. the first solution allows the user to k... | get a list of images and then loop through them
for example you get a total of 500 imgs you can take 5 at a time and after you're finished with them output a meta refresh tag that will reload the script in 2 seconds for example with the image number you're currently at as a parameter .
```
<meta http-equiv="refresh" c... | How can I split a PHP script that takes a long time to run into smaller chunks? | [
"",
"php",
""
] |
I work in an Oracle shop. There's a toolset that consists of roughly 1000 Oracle Forms (using the Forms builder from 6i, early 90's software) with Oracle 10g on the back end. It's serving roughly 500 unique people a month, with 200 concurrent connections at any given time during the work day.
Obviously this is somethi... | That's exactly what I am currently doing using...
[Oracle Application Express](http://apex.oracle.com/i/index.html)
The learning curve is much smaller than most web-based alternatives for Forms developers, as all the code is in PL/SQL (unless you start getting fancy with Javascript, which you can). Also, in the lates... | I'll +1 for Oracle Application Express -- I think that there are some significant advantages in your situation.
1. Free licensing
2. It may bean attractive option to the current staff, if they are Oracle bigots like me.
3. It's 100% web, and in 11g doesn't even require a web tier. | Best solution for migration from Oracle Forms 6i to the web? | [
"",
"java",
"oracle",
"migration",
"oracleforms",
""
] |
I've been trying to figure out how to retrieve the text selected by the user in my webbrowser control and have had no luck after digging through msdn and other resources, So I was wondering if there is a way to actually do this. Maybe I simply missed something.
I appreciate any help or resources regarding this.
Thank... | You need to use the Document.DomDocument property of the WebBrowser control and cast this to the IHtmlDocument2 interface provided in the Microsoft.mshtml interop assembly. This gives you access to the full DOM as is available to Javascript actually running in IE.
To do this you first need to add a reference to your p... | Just in case anybody is interested in solution that doesn't require adding a reference to mshtml.dll:
```
private string GetSelectedText()
{
dynamic document = webBrowser.Document.DomDocument;
dynamic selection = document.selection;
dynamic text = selection.createRange().text;
return (string)text;
}
``... | Retrieving Selected Text from Webbrowser control in .net(C#) | [
"",
"c#",
"winforms",
"webbrowser-control",
""
] |
What kind of collection I should use to convert NameValue collection to be bindable to GridView?
When doing directly it didn't work.
**Code in aspx.cs**
```
private void BindList(NameValueCollection nvpList)
{
resultGV.DataSource = list;
resultGV.DataBind();
}
```
**Code in aspx**
```
<asp:GridView ... | Can you use Dictionary<string,string> instead of NameValueCollection. Since Dictionary<T,T> implements IEnumerable you could use LINQ as so:
```
resultGV.DataSource = from item in nvpDictionary
select new { Key = item.Key, Value = item.Value };
resultGV.DataBind();
```
[EDIT] Actually you may be... | It's a little tricky, because the [enumerator](http://msdn.microsoft.com/en-us/library/system.collections.specialized.nameobjectcollectionbase.getenumerator.aspx) returns only the Keys. But, you can get the Key value with Container.DataItem, and then look up into the NameValueCollection to get the value:
```
<asp:Grid... | Bind NameValueCollection to GridView? | [
"",
"c#",
"asp.net",
"data-binding",
"namevaluecollection",
""
] |
I fill a collection one single time when my J2EE webapp starts.
Then, several thread may access it at same time but only to read it.
I know using a synchronized collection is mandatory for parallels write but do I still need it for parallels read ? | Normally no because you are not changing the internal state of the collection in this case. When you iterate over the collection a new instance of the iterator is created and the state of the iteration is per iterator instance.
---
**Aside note:** Remember that by keeping a read-only collection you are only preventin... | It depends on if the threads that are reading your collection are started before or after you're filling it. If they're started before you fill it, you have no guarantees (without synchronizing), that these threads will ever see the updated values.
The reason for this is the Java Memory Model, if you wanna know more r... | In Java, do I need to declare my collection synchronized if it's read-only? | [
"",
"java",
"multithreading",
"synchronization",
"web-applications",
""
] |
It seems that the
* [`System.Diagnostics.Debug`](https://msdn.microsoft.com/en-us/library/system.diagnostics.debug(v=vs.110).aspx), and
* [`System.Diagnostics.Trace`](https://msdn.microsoft.com/en-us/library/system.diagnostics.trace(v=vs.110).aspx)
are largely the same, with the notable exception that **Debug** usage... | The main difference is the one you indicate: Debug is not included in release, while Trace is.
The intended difference, as I understand it, is that development teams might use Debug to emit rich, descriptive messages that might prove too detailed (or revealing) for the consumer(s) of a product, while Trace is intended... | The only difference between trace and debug is that trace statements are included by default in the program when it is compiled into a release build, whereas debug statement are not.
Thus, the debug class is principally used for debugging in the development phase, while trace can be used for **testing and optimization... | Trace vs Debug in .NET BCL | [
"",
"c#",
".net",
"debugging",
"instrumentation",
""
] |
In Visual Studio, two files are created when you create a new Windows Form in your solution (e.g. if you create MyForm.cs, MyForm.Designer.cs and MyForm.resx are also created). These second two files are displayed as a subtree in the Solution Explorer.
**Is there any way to add files to the sub-tree or group for a Win... | Open .csproj in edit mode, look for the file you want to be under another one, and add the DependentUpon element, like this:
```
<Compile Include="AlertDialog.xaml.cs">
<DependentUpon>AlertDialog.xaml</DependentUpon>
</Compile>
``` | You need to edit the csproj directly. There is a DependentUpon tag that you have to add as a child tag of the file you want to place under MyForm.cs.
Example:
```
<Compile Include="MyForm.MyCoolSubFile.cs">
<DependentUpon>MyForm.cs</DependentUpon>
</Compile>
``` | Can I create a file that sits next to a .Designer.cs file in Visual Studio? | [
"",
"c#",
".net",
"visual-studio-2008",
""
] |
I have the following code that won't compile and although there is a way to make it compile I want to understand why it isn't compiling. Can someone enlighten me as to specifically why I get the error message I will post at the end please?
```
public class Test {
public static void main(String args[]) {
Te... | The reason is that Test.class is of the type Class<Test>. You cannot assign a reference of type Class<Test> to a variable of type Class<T> as they are not the same thing. This, however, works:
```
Class<? extends Test> testType = type == null ? Test.class : type;
```
The wildcard allows both Class<T> and Class<Test> ... | Suppose I extend Test:
```
public class SubTest extends Test {
public static void main(String args[]) {
Test t = new Test();
t.testT(new SubTest());
}
}
```
Now, when I invoked `testT`, the type parameter `<T>` is `SubTest`, which means the variable `testType` is a `Class<SubTest>`. `Test.class` is of typ... | Type mismatch for Class Generics | [
"",
"java",
"generics",
""
] |
I'm working on a C# program, and right now I have one `Form` and a couple of classes. I would like to be able to access some of the `Form` controls (such as a `TextBox`) from my class. When I try to change the text in the `TextBox` from my class I get the following error:
> An object reference is required for the non-... | You are trying to access the class as opposed to the object. That statement can be confusing to beginners, but you are effectively trying to open your house door by picking up the door on your house plans.
If you actually wanted to access the form components directly from a class (which you don't) you would use the va... | Another solution would be to pass the textbox (or control you want to modify) into the method that will manipulate it as a parameter.
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
TestClass... | How to access form methods and controls from a class in C#? | [
"",
"c#",
"winforms",
""
] |
I have a bit of code that basically reads an XML document using the XMLDocument.Load(uri) method which works fine, but doesn't work so well if the call is made through a proxy.
I was wondering if anyone knew of a way to make this call (or achieve the same effect) through a proxy? | Do you have to provide credentials to the proxy?
If so, this should help:
"Supplying Authentication Credentials to XmlResolver when Reading from a File"
<http://msdn.microsoft.com/en-us/library/aa720674.aspx>
Basically, you...
1. Create an XmlTextReader using the URL
2. Set the Credentials property of the reader's X... | This is the code that I ended up using:
```
WebProxy wp = new WebProxy(Settings.Default.ProxyAddress);
wp.Credentials = new NetworkCredential(Settings.Default.ProxyUsername, Settings.Default.ProxyPassword);
WebClient wc = new WebClient();
wc.Proxy = wp;
MemoryStream ms = new MemoryStream(wc.DownloadData(url));
XmlTex... | XMLDocument.Load(url) through a proxy | [
"",
"c#",
"xml",
"proxy",
""
] |
In order to improve performance reading from a file, I'm trying to read the entire content of a big (several MB) file into memory and then use a istringstream to access the information.
My question is, which is the best way to read this information and "import it" into the string stream? A problem with this approach (... | `std::ifstream` has a method `rdbuf()`, that returns a pointer to a `filebuf`. You can then "push" this `filebuf` into your `stringstream`:
```
#include <fstream>
#include <sstream>
int main()
{
std::ifstream file( "myFile" );
if ( file )
{
std::stringstream buffer;
buffer << file.rdbuf(... | OK. I am not saying this will be quicker than reading from the file
But this is a method where you create the buffer once and after the data is read into the buffer use it directly as the source for stringstream.
**N.B.**It is worth mentioning that the std::ifstream is buffered. It reads data from the file in (relati... | How to read file content into istringstream? | [
"",
"c++",
"optimization",
"memory",
"stream",
"stringstream",
""
] |
Does MS Access 2007 support internal foreign keys within the same table? | Yes. Create the table with the hierarchy.
id - autonumber - primary key
parent\_id - number
value
Go to the relationships screen. Add the hierarchy table twice. Connect the id and the parent\_id fields. Enforce referential integrity. | Yes it does and unlike many more capable SQLs (e.g. SQL Server) you can also use CASCADE referential actions on FKs within the same table, which is nice. | Microsoft Access - SQL - Internal Foreign Key | [
"",
"sql",
"ms-access",
""
] |
I'm working on an upgrade for an existing database that was designed without any of the code to implement the design being considered. Now I've hit a brick wall in terms of implementing the database design in code. I'm certain whether its a problem with the design of the database or if I'm simply not seeing the correct... | What you're looking for is [relational division](http://www.dbazine.com/ofinterest/oi-articles/celko1)
Not implemented directly in SQL, but it can be done. Search google for other examples. | UPDATE:
I have considering this issue further and have considered whether it would allow things to work better to simply remove the user\_seat\_rtab table and then use the equivalent certification\_rtab table (probably renamed) to hold all of the information regarding the status of a user's seat. This way there is a d... | Database Design Issues with relationships | [
"",
"php",
"mysql",
"database-design",
"foreign-keys",
"relational-database",
""
] |
C++ was the first programming language I really got into, but the majority of my work on it was academic or for game programming. Most of the programming jobs where I live require Java or .NET programmers and I have a fairly good idea of what technologies they require aside from the basic language. For example, a Java ... | As for every language, I believe there are three interconnected levels of knowledge :
1. Master your language. Every programmer should (do what it takes to) master the syntax. Good references to achieve this are :
* [The C++ Programming Language](http://www.research.att.com/~bs/3rd.html) by Bjarne Stroustrup.
* ... | C++ developer have to grok [std](http://en.wikipedia.org/wiki/C%2B%2B_standard_library) and [boost](http://www.boost.org) libraries.
List of other technologies largely depends on project type. For sure you will have some interaction with SO, so you will need to know API of your environment.
As for data-access and oth... | What technologies do C++ programmers need to know? | [
"",
"c++",
""
] |
How to get the path of the current csproject?
Let's say I have a csproject name `MyProj.csproj`, inside there is a class that wants to know what is the file path of this csproj, any idea on how to do this? thanks. | If you really must do this, I would consider meta-programming. Create another project in your solution that builds a command line exe which takes one argument. The command line exe project should output a cs file that contains a class with a static property returning the value passed at the command line.
Then, as a pr... | Unless you are talking about creating a plugin for Visual Studio, the CsProj file no longer exists (as far as your code is concerned) once your program compiles and is running.
The CsProj is actually used to instruct the compiler how to compile your C# code into an assembly. After that point the CsProj is left on the ... | Get CSproj path in code | [
"",
"c#",
""
] |
I would like to specify a constraint which is another type with a generic argument.
```
class KeyFrame<T>
{
public float Time;
public T Value;
}
// I want any kind of Keyframe to be accepted
class Timeline<T> where T : Keyframe<*>
{
}
```
But this cannot be done in c# as of yet, (and I really doubt it will e... | Read about this from [Eric Lippert's blog](http://blogs.msdn.com/ericlippert/archive/2008/05/19/a-generic-constraint-question.aspx)
Basically, you have to find a way to refer to the type you want without specifying the secondary type parameter.
In his post, he shows this example as a possible solution:
```
public abs... | As TimeLine is most likely an aggregation of KeyFrames, wouldn't something like:
```
class TimeLine<T>
{
private IList<KeyFrame<T>> keyFrameList;
...
}
```
fulfill your requirements nicely? | How can I use a type with generic arguments as a constraint? | [
"",
"c#",
"generics",
"constraints",
""
] |
I use a 3rd party tool that outputs a file in Unicode format. However, I prefer it to be in ASCII. The tool does not have settings to change the file format.
What is the best way to convert the entire file format using Python? | You can convert the file easily enough just using the `unicode` function, but you'll run into problems with Unicode characters without a straight ASCII equivalent.
[This blog](http://www.peterbe.com/plog/unicode-to-ascii) recommends the `unicodedata` module, which seems to take care of roughly converting characters w... | *I think this is a deeper issue than you realize*. Simply changing the file from Unicode into ASCII is easy, however, getting all of the Unicode characters to translate into reasonable ASCII counterparts (many letters are not available in both encodings) is another.
This Python Unicode tutorial may give you a better i... | How do I convert a file's format from Unicode to ASCII using Python? | [
"",
"python",
"unicode",
"encoding",
"file",
"ascii",
""
] |
I'm looking for very simple obfuscation (like encrypt and decrypt but not necessarily secure) functionality for some data. It's not mission critical. I need something to keep honest people honest, but something a little stronger than [ROT13](http://en.wikipedia.org/wiki/ROT13) or [Base64](http://en.wikipedia.org/wiki/B... | Other answers here work fine, but AES is a more secure and up-to-date encryption algorithm. This is a class that I obtained a few years ago to perform AES encryption that I have modified over time to be more friendly for web applications (e,g. I've built Encrypt/Decrypt methods that work with URL-friendly string). It a... | I cleaned up SimpleAES (above) for my use. Fixed convoluted encrypt/decrypt methods; separated methods for encoding byte buffers, strings, and URL-friendly strings; made use of existing libraries for URL encoding.
The code is small, simpler, faster and the output is more concise. For instance, `johnsmith@gmail.com` pr... | Simple insecure two-way data "obfuscation"? | [
"",
"c#",
"obfuscation",
""
] |
I want to do some benchmarking of a C# process, but I don't want to use time as my vector - I want to count the number of IL instructions that get executed in a particular method call. Is this possible?
**Edit** I don't mean static analysis of a method body - I'm referring to the actual number of instructions that are... | I don't think it's possible to do what you want. This is because the IL is only used during JIT (Just-In-Time) compilation. By the time the method is running the IL has been translated into native machine code. So, while it might be possible to count the number of IL instructions in a given method/type/assembly statica... | Well, it won't be easy. I *think* you could instrument your assembly post-compile with performance counter code that executed after blocks of IL. For example, if you had a section of a method that loaded an int onto the stack then executed a static method using that int under optimized code, you could record a count of... | Is there a way to count the number of IL instructions executed? | [
"",
"c#",
".net",
"benchmarking",
"cil",
""
] |
I want to run a psychological study for which participants have to look at large images.
The experiment is done on the web and therefore in a browser window. Is it possible to tell the browser to go into fullscreen, for example on button press?
I know there is the possibility to open a fixed-size popup window. Do you... | I have found some code after searching.
```
function fullscreen() {
var element = document.getElementById("content");
if (element.requestFullScreen) {
if (!document.fullScreen) {
element.requestFullscreen();
$(".fullscreen").attr('src',"img/icons/panel_resize_actual.png");
... | You could just tell the user to press F11. Next to it, put a 'why?' link and explain why you feel like they need to be in fullscreen mode.
I don't think you can force a browser to go full screen and, in fact, if you were able to do that I'd be furious at my browser. It's too invasive. Even Flash has security so that f... | Could a website force the browser to go into fullscreen mode? | [
"",
"javascript",
"html",
"browser",
"window",
""
] |
Im trying to find out a good JavaScript library that can create a nice "inner-window" popup within a page on my site.
I would like to not have to worry about screen positioning (i.e. dont have to calcuate if the size of the window will be off screen, etc...), but just make a new pop-up that has content in it.
I'll be... | **Floating containers, panels and dialogs:**
For dialog boxes and windows, perhaps a [**YUI module**](http://developer.yahoo.com/yui/container/module/) would be a **good solution**.
**Modal Boxes**
If you **aren't a javascript programmer**, and you're interested in a more-elaborate modal box, there are jQuery **plug... | I have used one called [iBox](http://www.ibegin.com/labs/ibox/) and it has worked well.
If you are already using jQuery then you might want to check out these [two](http://leandrovieira.com/projects/jquery/lightbox/) [options](http://jquery.com/demo/thickbox/). | JavaScript library to create div-style window within page | [
"",
".net",
"javascript",
"dhtml",
""
] |
Is there a way to change the color of the background for a MDIParent windows in MFC (2005)?
I have tried intercepting ON\_WM\_CTLCOLOR AND ON\_WM\_ERASEBKGND but neither work. OnEraseBkgnd does work, but then it gets overwritten by the standard WM\_CTL color.
Cheers | The CMDIFrameWnd is actually covered up by another window called the MDIClient window. Here is a Microsoft article on how to subclass this MDIClient window and change the background colour. I just tried it myself and it works great.
<http://support.microsoft.com/kb/129471> | Create a class deriving CWnd (CClientWnd for example)
In your CWnd-derived class handle
```
afx_msg BOOL OnEraseBkgnd(CDC* pDC);
afx_msg void OnPaint(void);
afx_msg void OnSize(UINT nType, int cx, int cy);
```
You need the following message map entries:
```
ON_WM_ERASEBKGND()
ON_WM_PAINT()
ON_WM_SIZE()
```
In OnEr... | Setting Background Color CMDIFrameWnd | [
"",
"c++",
"user-interface",
"mfc",
"colors",
""
] |
I'm writing in second-person just because its easy, for you.
You are working with a game engine and really wish a particular engine class had a new method that does 'bla'. But you'd rather not spread your 'game' code into the 'engine' code.
So you could derive a new class from it with your one new method and put that... | My only question to you is, "does your added functionality need to be a member function, or can it be a free function?" If what you want to do can be solved using the class's existing interface, then the only difference is the syntax, and you should use a free function (if you think that's "ugly", then... suck it up an... | Sounds like a 'acts upon' relationship, which would not fit in an inheritance (use sparingly!).
One option would be a composition utility class that acts upon a certain instance of the 'Engine' by being instantiated with a pointer to it. | Extending an existing class like a namespace (C++)? | [
"",
"c++",
"code-organization",
""
] |
I would like to write some scripts in python that do some automated changes to source code. If the script determines it needs to change the file I would like to first check it out of perforce. I don't care about checking in because I will always want to build and test first. | Perforce has Python wrappers around their C/C++ tools, available in binary form for Windows, and source for other platforms:
<http://www.perforce.com/perforce/loadsupp.html#api>
You will find their documentation of the scripting API to be helpful:
<http://www.perforce.com/perforce/doc.current/manuals/p4script/p4scri... | Here's what I came up with:
```
import os
def CreateNewChangeList(description):
"Create a new changelist and returns the changelist number as a string"
p4in, p4out = os.popen2("p4 changelist -i")
p4in.write("change: new\n")
p4in.write("description: " + description)
p4in.close()
changelist = p4... | How do I check out a file from perforce in python? | [
"",
"python",
"scripting",
"perforce",
""
] |
I have the following query:
```
SELECT c.*
FROM companies AS c
JOIN users AS u USING(companyid)
JOIN jobs AS j USING(userid)
JOIN useraccounts AS us USING(userid)
WHERE j.jobid = 123;
```
I have the following questions:
1. Is the USING syntax synonymous with ON syntax?
2. Are these joins evaluated left to right? In ... | 1. USING (fieldname) is a shorthand way of saying ON table1.fieldname = table2.fieldname.
2. SQL doesn't define the 'order' in which JOINS are done because it is not the nature of the language. Obviously an order has to be specified in the statement, but an INNER JOIN can be considered commutative: you can list them in... | I can't answer the bit about the USING syntax. That's weird. I've never seen it before, having always used an ON clause instead.
But what I *can* tell you is that the order of JOIN operations is determined dynamically by the query optimizer when it constructs its query plan, based on a system of optimization heuristic... | In what order are MySQL JOINs evaluated? | [
"",
"mysql",
"sql",
"join",
""
] |
Is there any advantage to using `__construct()` instead of the class's name for a constructor in PHP?
Example (`__construct`):
```
class Foo {
function __construct(){
//do stuff
}
}
```
Example (named):
```
class Foo {
function Foo(){
//do stuff
}
}
```
Having the `__construct` meth... | The advantage is that you don't have to rename it if you rename your class. DRY.
Similarly, if you have a child class, you can call the parent constructor:
```
parent::__construct()
```
If further down the track you change the class the child class inherits from, you don't have to change the construct call to the pa... | `__construct` was introduced in PHP5. It is the way you are supposed to do it now. I am not aware of any *advantages* per se, though.
From the PHP manual:
> For backwards compatibility, if PHP 5 cannot find a \_\_construct() function for a given class, it will search for the old-style constructor function, by the nam... | __construct() vs SameAsClassName() for constructor in PHP | [
"",
"php",
"constructor",
""
] |
I tried this XAML:
```
<Slider Width="250" Height="25" Minimum="0" Maximum="1" MouseLeftButtonDown="slider_MouseLeftButtonDown" MouseLeftButtonUp="slider_MouseLeftButtonUp" />
```
And this C#:
```
private void slider_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
sliderMouseDown = true;
}
private void... | Sliders swallow the MouseDown Events (similar to the button).
You can register for the PreviewMouseDown and PreviewMouseUp events which get fired before the slider has a chance to handle them. | Another way to do it (and possibly better depending on your scenario) is to register an event handler in procedural code like the following:
```
this.AddHandler
(
Slider.MouseLeftButtonDownEvent,
new MouseButtonEventHandler(slider_MouseLeftButtonDown),
true
);
```
Please note the true argument. **It basic... | WPF: Slider doesnt raise MouseLeftButtonDown or MouseLeftButtonUp | [
"",
"c#",
"wpf",
"slider",
"mouseevent",
""
] |
I've got build server running CruiseControl.NET and recently it started throwing this error on one of my projects (.NET 2.0, C#):
> MSB3176: Specified minimum required version is greater than the current publish version. Please specify a version less than or equal to the current publish version. in Microsoft.Common.ta... | Check the properties of your project. The version numbers are on the 'publish' tab. You should compare the publish version with the minimum version ('Updates' button). | The project properties have a publish version (on the Publish tab), and an (optional) minimum version (on the Updates button on the Publish tab). Neither is related to any assembly version, and is just used for ClickOnce. If a minimum version is specified, it must be logical (i.e. not higher than the main version).
In... | Error "MSB3176: Specified minimum required version is greater than the current publish version" | [
"",
"c#",
"msbuild",
".net-2.0",
"cruisecontrol.net",
""
] |
Is there a way to print all methods of an object in JavaScript? | Sure:
```
function getMethods(obj) {
var result = [];
for (var id in obj) {
try {
if (typeof(obj[id]) == "function") {
result.push(id + ": " + obj[id].toString());
}
} catch (err) {
result.push(id + ": inaccessible");
}
}
return result;
}
```
Using it:
```
alert(getMetho... | If you just want to look what is inside an object, you can print all object's keys. Some of them can be variables, some - methods.
The method is not very accurate, however it's really quick:
```
console.log(Object.keys(obj));
``` | Is there a way to print all methods of an object? | [
"",
"javascript",
""
] |
I would like to determine the operating system of the host that my Java program is running programmatically (for example: I would like to be able to load different properties based on whether I am on a Windows or Unix platform). What is the safest way to do this with 100% reliability? | You can use:
```
System.getProperty("os.name")
```
P.S. You may find this code useful:
```
class ShowProperties {
public static void main(String[] args) {
System.getProperties().list(System.out);
}
}
```
All it does is print out all the properties provided by your Java implementations. It'll give yo... | As indicated in other answers, System.getProperty provides the raw data. However, the [Apache Commons Lang component](http://commons.apache.org/lang/) provides a [wrapper for java.lang.System](http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/SystemUtils.html) with handy proper... | How do I programmatically determine operating system in Java? | [
"",
"java",
"operating-system",
""
] |
Personally, I find the range of functionality provided by java.util.Iterator to be fairly pathetic. At a minimum, I'd like to have methods such as:
* peek() returns next element without moving the iterator forward
* previous() returns the previous element
Though there are lots of other possibilities such as first() a... | [Apache Commons Collections](https://commons.apache.org/proper/commons-collections/javadocs/api-release/org/apache/commons/collections4/iterators/package-summary.html)
[Google Collections](https://google.github.io/guava/releases/21.0/api/docs/com/google/common/collect/package-summary.html) | You can get `previous()` easily by just using a `java.util.ListIterator`.
Peek at that point is easily implemented by doing a
```
public <T> T peek(ListIterator<T> iter) throws NoSuchElementException {
T obj = iter.next();
iter.previous();
return obj;
}
```
Unfortunately it will be easier to have it as a... | improved collection Iterator | [
"",
"java",
"collections",
"iterator",
"decorator",
""
] |
I'm working on a simple 2D game engine in Java, and having no trouble with FSEM, buffer strategies, and so on; my issue is with the mouse cursor. In windowed mode, I can hide the mouse cursor, no problem, by using setCursor() from my JFrame to set a wholly-transparent cursor. However, after a call to device.setFullScre... | I think I've finally found the solution:
```
System.setProperty("apple.awt.fullscreenhidecursor","true");
```
This is an Apple-proprietary system property that hides the mouse cursor when an application is in full-screen mode. It's the only way I've found to fix it. | Try Creating a custom invisible cursor:
```
Toolkit toolkit = Toolkit.getDefaultToolkit();
Point hotSpot = new Point(0,0);
BufferedImage cursorImage = new BufferedImage(1, 1, BufferedImage.TRANSLUCENT);
Cursor invisibleCursor = toolkit.createCustomCursor(cursorImage, hotSpot, "InvisibleCursor"); ... | How do I get rid of the mouse cursor in full-screen exclusive mode? | [
"",
"java",
"mouse",
"fullscreen",
"mouse-cursor",
""
] |
I am taking a class in C++ programming and the professor told us that there is no need to learn C because C++ contains everything in C plus object-oriented features. However, some others have told me that this is not necessarily true. Can anyone shed some light on this? | **Overview:**
It is almost true that C++ is a superset of C, and your professor is correct in that there is no need to learn C separately.
C++ adds the whole object oriented aspect, generic programming aspect, as well as having less strict rules (like variables needing to be declared at the top of each function). C++... | While it's true that C++ was designed to maintain a large degree of compatibility with C and a subset of what you learn in C++ will apply to C the mindset is completely different. Programming C++ with Boost or STL is a very different experience than programming in C.
There was a term of art called using C++ as a bette... | Is it true that there is no need to learn C because C++ contains everything? | [
"",
"c++",
"c",
""
] |
I'm working with jQuery for the first time and need some help. I have html that looks like the following:
```
<div id='comment-8' class='comment'>
<p>Blah blah</p>
<div class='tools'></div>
</div>
<div id='comment-9' class='comment'>
<p>Blah blah something else</p>
<div class='tools'></div>
</div>
```... | Event callbacks are called with an event object as the first argument, you can't pass something else in that way. This event object has a `target` property that references the element it was called for, and the `this` variable is a reference to the element the event handler was attached to. So you could do the followin... | To get from the span up to the surrounding divs, you can use `<tt>parent()</tt>` (if you know the exact relationship), like this: `<tt>$(this).parent().attr('id')</tt>;` or if the structure might be more deeply nested, you can use parents() to search up the DOM tree, like this: `<tt>$(this).parents('div:eq(0)').attr('i... | Passing in parameter from html element with jQuery | [
"",
"javascript",
"jquery",
""
] |
Is there a way to use Enum values inside a JSP without using scriptlets.
e.g.
```
package com.example;
public enum Direction {
ASC,
DESC
}
```
so in the JSP I want to do something like this
```
<c:if test="${foo.direction ==<% com.example.Direction.ASC %>}">...
``` | You could implement the web-friendly text for a direction within the enum as a field:
```
<%@ page import="com.example.Direction" %>
...
<p>Direction is <%=foo.direction.getFriendlyName()%></p>
<% if (foo.direction == Direction.ASC) { %>
<p>That means you're going to heaven!</p>
<% } %>
```
but that mixes the view an... | It can be done like this I guess
```
<c:set var="ASC" value="<%=Direction.ASC%>"/>
<c:if test="${foo.direction == ASC}"></c:if>
```
the advantage is when we refactor it will reflect here too | Enum inside a JSP | [
"",
"java",
"jsp",
"jstl",
""
] |
I'm trying to do a domain lookup in vba with something like this:
```
DLookup("island", "villages", "village = '" & txtVillage & "'")
```
This works fine until txtVillage is something like Dillon's Bay, when the apostrophe is taken to be a single quote, and I get a run-time error.
I've written a trivial function tha... | The "Replace" function should do the trick. Based on your code above:
```
DLookup("island", "villages", "village = '" & Replace(txtVillage, "'", "''") & "'")
``` | It's worse than you think. Think about what would happen if someone entered a value like this, and you haven't escaped anything:
```
'); DROP TABLE [YourTable]
```
Not pretty.
The reason there's no built in function to simply escape an apostrophe is because the correct way to handle this is to use query parameters. ... | Escaping ' in Access SQL | [
"",
"sql",
"vba",
"ms-access",
"escaping",
""
] |
I need to add the ability for users of my software to select records by character ranges.
How can I write a query that returns all widgets from a table whose name falls in the range Ba-Bi for example?
Currently I'm using greater than and less than operators, so the above example would become:
```
select * from widg... | Let's skip directly to localization. Would you say "aa" >= "ba" ? Probably not, but that is where it sorts in Sweden. Also, you simply can't assume that you can ignore casing in any language. Casing is explicitly language-dependent, with the most common example being Turkish: uppercase i is İ. Lowercase I is ı.
Now, y... | For MSSQL see this thread: <http://bytes.com/forum/thread483570.html> .
For Oracle, it depends on your Oracle version, as Oracle 10 now supports regex(p) like queries: <http://www.psoug.org/reference/regexp.html> (search for regexp\_like ) and see this article: <http://www.oracle.com/technology/oramag/webcolumns/2003/... | What is the best way to select string fields based on character ranges? | [
"",
"sql",
"sql-server",
"oracle",
"localization",
"collation",
""
] |
I have a stored procedure that looks like:
```
CREATE PROCEDURE dbo.usp_TestFilter
@AdditionalFilter BIT = 1
AS
SELECT *
FROM dbo.SomeTable T
WHERE
T.Column1 IS NOT NULL
AND CASE WHEN @AdditionalFilter = 1 THEN
T.Column2 IS NOT NULL
```
Needless to say, this doesn't work. How can I activate the ... | ```
CREATE PROCEDURE dbo.usp_TestFilter
@AdditionalFilter BIT = 1
AS
SELECT *
FROM dbo.SomeTable T
WHERE
T.Column1 IS NOT NULL
AND (@AdditionalFilter = 0 OR
T.Column2 IS NOT NULL)
```
If @AdditionalFilter is 0, the column won't be evaluated since it can't affect the outcome of the part between br... | This practice tends to confuse the query optimizer. I've seen SQL Server 2000 build the execution plan exactly the opposite way round and use an index on Column1 when the flag was set and vice-versa. SQL Server 2005 seemed to at least get the execution plan right on first compilation, but you then have a new problem. T... | Stored procedure bit parameter activating additional where clause to check for null | [
"",
"sql",
"stored-procedures",
""
] |
I know there is built-in Internet explorer, but what I'm looking for is to open Firefox/Mozilla window (run the application) with specified URL. Anyone can tell me how to do that in C# (.nET) ? | This will launch the system defined default browser:
```
string url = "http://stackoverflow.com/";
System.Diagnostics.Process.Start(url);
```
Remember that Process.Start(url) might throw exceptions if the browser is not configured correctly. | You can do this:
```
System.Diagnostics.Process.Start("firefox.exe", "http://www.google.com");
``` | How do I open alternative webbrowser (Mozilla or Firefox) and show the specific url? | [
"",
"c#",
".net",
"browser",
""
] |
Is there any real practical difference between "java -server" and "java -client"?
All I can find on Sun's site is a vague
> "-server starts slower but should run faster".
What are the real differences? (Using JDK 1.6.0\_07 currently.) | This is really linked to *HotSpot* and the default *option values* ([Java HotSpot VM Options](http://www.oracle.com/technetwork/java/javase/tech/vmoptions-jsp-140102.html)) which differ between client and server configuration.
From [Chapter 2](http://www.oracle.com/technetwork/java/whitepaper-135217.html#2) of the whi... | The most visible immediate difference in older versions of Java would be the memory allocated to a `-client` as opposed to a `-server` application. For instance, on my Linux system, I get:
```
$ java -XX:+PrintFlagsFinal -version 2>&1 | grep -i -E 'heapsize|permsize|version'
uintx AdaptivePermSizeWeight ... | Real differences between "java -server" and "java -client"? | [
"",
"java",
"jvm",
"jvm-hotspot",
""
] |
Following on from [this question](https://stackoverflow.com/questions/223832/check-a-string-to-see-if-all-characters-are-hexadecimal-values) what would be the best way to write a Char.IsHex() function in C#. So far I've got this but don't like it:
```
bool CharIsHex(char c) {
c = Char.ToLower(c);
return (Char.... | From [my answer](https://stackoverflow.com/questions/223832/check-a-string-to-see-if-all-characters-are-hexadecimal-values#223854) to the question you linked to:
```
bool is_hex_char = (c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F');
``` | You can write it as an extension method:
```
public static class Extensions
{
public static bool IsHex(this char c)
{
return (c >= '0' && c <= '9') ||
(c >= 'a' && c <= 'f') ||
(c >= 'A' && c <= 'F');
}
}
```
This means you can then call it as though it were a member of ... | Char.IsHex() in C# | [
"",
"c#",
"algorithm",
""
] |
I've always used a `*.h` file for my class definitions, but after reading some boost library code, I realised they all use `*.hpp`. I've always had an aversion to that file extension, I think mainly because I'm not used to it.
What are the advantages and disadvantages of using `*.hpp` over `*.h`? | Here are a couple of reasons for having different naming of C vs C++ headers:
* Automatic code formatting, you might have different guidelines for formatting C and C++ code. If the headers are separated by extension you can set your editor to apply the appropriate formatting automatically
* Naming, I've been on projec... | I use .hpp because I want the user to differentiate what headers are C++ headers, and what headers are C headers.
This can be important when your project is using both C and C++ modules: Like someone else explained before me, you should do it very carefully, and its starts by the "contract" you offer through the exten... | *.h or *.hpp for your class definitions | [
"",
"c++",
"header",
""
] |
What's the difference between `Char.IsDigit()` and `Char.IsNumber()` in C#? | `Char.IsDigit()` is a subset of `Char.IsNumber()`.
Some of the characters that are 'numeric' but not digits include 0x00b2 and 0x00b3 which are superscripted 2 and 3 ('²' and '³') and the glyphs that are fractions such as '¼', '½', and '¾'.
Note that there are quite a few characters that `IsDigit()` returns `true` fo... | I found the answer:
> Char.IsNumber() determines if a Char
> is of any numeric Unicode category.
> This contrasts with IsDigit, which
> determines if a Char is a radix-10
> digit.
>
> Valid numbers are members of the
> following categories in
> [UnicodeCategory](http://msdn.microsoft.com/en-us/library/system.globaliza... | Difference between Char.IsDigit() and Char.IsNumber() in C# | [
"",
"c#",
".net",
"unicode",
""
] |
I'm programming an online game for two reasons, one to familiarize myself with server/client requests in a realtime environment (as opposed to something like a typical web browser, which is not realtime) and to actually get my hands wet in that area, so I can proceed to actually properly design one.
Anywho, I'm doing ... | **The easiest thing**
for you to do, would be to simply invoke the windows API **QueueUserWorkItem**. All you have to specify is the function that the thread will execute and the input passed to it. A thread pool will be automatically created for you and the jobs executed in it. New threads will be created as and when... | BlodBath's suggestion of non-blocking sockets is potentially the right approach.
If you're trying to avoid using a multithreaded approach, then you could investigate the use of setting up overlapped I/O on your sockets. They will not block when you do a transmit or receive, but have the added bonus of giving you the o... | Network Multithreading | [
"",
"c++",
"multithreading",
"networking",
""
] |
I'm writing a WinForms application and one of the tabs in my TabControl has a SplitContainer. I'm saving the SplitterDistance in the user's application settings, but the restore is inconsistent. If the tab page with the splitter is visible, then the restore works and the splitter distance is as I left it. If some other... | I found the problem. Each tab page doesn't get resized to match the tab control until it gets selected. For example, if the tab control is 100 pixels wide in the designer, and you've just set it to 500 pixels during load, then setting the splitter distance to 50 on a hidden tab page will get resized to a splitter dista... | There`s a more easy solution. If Panel1 is set as the fixed panel in SplitContainer.FixedPanel property it all behaves as expected. | Restoring SplitterDistance inside TabControl is inconsistent | [
"",
"c#",
".net",
"winforms",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.