Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I would like to throw an exception when my C++ methods encounter something weird and can't recover. Is it OK to throw a `std::string` pointer?
Here's what I was looking forward to doing:
```
void Foo::Bar() {
if(!QueryPerformanceTimer(&m_baz)) {
throw new std::string("it's the end of the world!");
}
}... | Yes. [`std::exception`](http://en.cppreference.com/w/cpp/error/exception) is the base exception class in the C++ standard library. You may want to avoid using strings as exception classes because they themselves can throw an exception during use. If that happens, then where will you be?
boost has an excellent [documen... | A few principles:
1. you have a std::exception base class, you should have your exceptions derive from it. That way general exception handler still have some information.
2. Don't throw pointers but object, that way memory is handled for you.
Example:
```
struct MyException : public std::exception
{
std::string s... | c++ exception : throwing std::string | [
"",
"c++",
"exception",
"stl",
""
] |
I've opened a new window with window.open() and I want to use the reference from the window.open() call to then write content to the new window. I've tried copying HTML from the old window to the new window by using myWindow.document.body.innerHTML = oldWindowDiv.innerHTML; but that's doesn't work. Any ideas? | The reference returned by `window.open()` is to the child window's `window` object. So you can do anything you would normally do, here's an example:
```
var myWindow = window.open('...')
myWindow.document.getElementById('foo').style.backgroundColor = 'red'
```
Bear in mind that this will only work if the parent and c... | I think this will do the trick.
```
function popUp(){
var newWindow = window.open("","Test","width=300,height=300,scrollbars=1,resizable=1")
//read text from textbox placed in parent window
var text = document.form.input.value
var html = "<html><head></head><body>Hello, <b>"+ text +"</b>."
ht... | How do I write content to another browser window using Javascript? | [
"",
"javascript",
"dom",
""
] |
I have a large collection of data in an excel file (and csv files). The data needs to be placed into a database (mysql). However, before it goes into the database it needs to be processed..for example if columns 1 is less than column 3 add 4 to column 2. There are quite a few rules that must be followed before the info... | If I didn't care to do this in 1 step (as Oli mentions), I'd probably use a [pipe and filters](http://www.eaipatterns.com/PipesAndFilters.html) design. Since your rules are relatively simple, I'd probably do a couple delegate based classes. For instance (C# code, but Java should be pretty similar...perhaps someone coul... | I think your method is OK. Especially if you use the same interface on every processor.
You could also look to somethink called Drules, currently Jboss-rules. I used that some time ago for a rule-heavy part of my app and what I liked about it is that the business logic can be expressed in for instance a spreadsheet or... | Application design for processing data prior to database | [
"",
"java",
"design-patterns",
"chain-of-responsibility",
""
] |
I've got the following JavaScript on my web page...
```
64 var description = new Array();
65 description[0] = "..."
66 description[1] = "..."
...
78 function init() {
79 document.getElementById('somedivid').innerHTML = description[0];
80 }
81
82 window.onload = init();
```
In Microsoft Intern... | Shouldn't line 82 read:
```
window.onload = init;
```
When you do "init()" it's a call to a function that returns void. You end up calling that function before the page loads. | To preserve any previously set onload functions try this
```
var prevload = window.onload;
window.onload = function(){
prevload();
init();
}
``` | Why am I getting this Javascript runtime error? | [
"",
"javascript",
"html",
"internet-explorer",
""
] |
While simple, interface-driven event notification frameworks in Java have been around since pre-Cambrian times (e.g. java.beans.PropertyChangeSupport), it is becoming increasingly popular for frameworks to use annotation-driven event notification instead.
For an example, see [JBossCache 2.2](http://www.jboss.org/file-... | You can already do this today with [EventBus](http://eventbus.org "EventBus").
Following example is from [EventBus Getting Started guide](http://eventbus.org/confluence/display/EventBus/Getting+Started). Statusbar that updates based on published events, and no need to register statusbar control/widget as listener of p... | I've made <http://neoevents.googlecode.com> to handle this kind of annotation based event handler.
```
@actionPerformed
private void onClick() {
//do something
}
protected void initComponents() {
JButton button = new JButton("Click me!!!");
button.addActionListener(new ActionListener(this) );
}
```
It lo... | Generic, annotation-driven event notification frameworks | [
"",
"java",
"events",
"annotations",
"notifications",
""
] |
I'm not sure if this is a strange thing to do or not, or if it is some how code smell...but I was wondering if there was a way (some sort of oop pattern would be nice) to "cast" a base type to a form of its derived type. I know this makes little sense as the derived type will have additional functionality that the pare... | Not soundly, in "managed" languages. This is *downcasting*, and there is no sane down way to handle it, for exactly the reason you described (subclasses provide more than base classes - where does this "more" come from?). If you really want a similar behaviour for a particular hierarchy, you could use constructors for ... | Try composition instead of inheritance!
It seems to me like you'd be better off passing an instance of SomeBaseClass to the SomeDerivedClass (which will no longer derive base class, and should be renamed as such)
```
public class BooleanHolder{
public bool BooleanEvaluator {get;set;}
}
public class Databa... | A way of casting a base type to a derived type | [
"",
"c#",
"oop",
"inheritance",
"design-patterns",
""
] |
This seems like a pretty softball question, but I always have a hard time looking up this function because there seem there are so many variations regarding the referencing of char and tchar. | [MultiByteToWideChar](http://msdn.microsoft.com/en-us/library/dd319072(v=vs.85).aspx) but also see ["A few of the gotchas of MultiByteToWideChar"](http://archives.miloush.net/michkap/archive/2005/04/19/409566.html). | The simplest way is to use the conversion macros:
* CW2A
* CA2W
* etc...
[MSDN](http://msdn.microsoft.com/en-us/library/87zae4a3(VS.71).aspx) | What is the simplest way to convert char[] to/from tchar[] in C/C++(ms)? | [
"",
"c++",
"c",
"string",
"char",
"tchar",
""
] |
How would you describe and promote WCF as a technology to a non-technical client/manager/CEO/etc?
What are competing solutions or ideas that they might bring up(such as those they read about in their magazines touting new technology)?
What is WCF *not* good for that you've seen people try to shoehorn it into?
-Adam | Comparing with .asmx: WCF is the next generation of Microsoft's Web service development platform, which addresses many of the issues with older versions, specifically:
* better interoperation, so you can interoperate with Web services that aren't from Microsoft or that are published on the Internet
* much more flexibl... | Tell them it'll let you do your job easier which translates into less time and less money. | How to promote WCF to a non-techie? | [
"",
"c#",
".net",
"wcf",
"web-services",
"soa",
""
] |
I wrote a SQL function to convert a datetime value in SQL to a friendlier "n Hours Ago" or "n Days Ago" etc type of message. And I was wondering if there was a better way to do it.
(Yes I know "don't do it in SQL" but for design reasons I have to do it this way).
Here is the function I've written:
```
CREATE FUNCTIO... | As you say, I probably wouldn't do it in SQL, but as a thought exercise have a MySQL implementation:
```
CASE
WHEN compare_date between date_sub(now(), INTERVAL 60 minute) and now()
THEN concat(minute(TIMEDIFF(now(), compare_date)), ' minutes ago')
WHEN datediff(now(), compare_date) = 1
THEN... | In Oracle:
```
select
CC.MOD_DATETIME,
'Last modified ' ||
case when (sysdate - cc.mod_datetime) < 1
then round((sysdate - CC.MOD_DATETIME)*24) || ' hours ago'
when (sysdate - CC.MOD_DATETIME) between 1 and 7
then round(sysdate-CC.MOD_DATETIME) || ' days ago'
when (sysdate - CC.MOD_DA... | Best way to convert DateTime to "n Hours Ago" in SQL | [
"",
"sql",
"datetime",
"function",
""
] |
I've got a siluation where i need to access a SOAP web service with WSE 2.0 security. I've got all the generated c# proxies (which are derived from Microsoft.Web.Services2.WebServicesClientProtocol), i'm applying the certificate but when i call a method i get an error:
```
System.Net.WebException : The request failed ... | Ok, found what the problem was. I was trying to call a .wsdl url instead of .asmx url.
Doh! | I found this was due to WCF not being installed on IIS. The main thing is that the .svc extension has to be mapped in IIS [See MSDN here.](http://msdn.microsoft.com/en-us/library/ms752252%28v=vs.90%29.aspx) Use the ServiceModelReg tool to complete the installation. You'll always want to verify that WCF is installed and... | How to solve HTTP status 405 "Method Not Allowed" when calling Web Services | [
"",
"c#",
".net",
"web-services",
"wse2.0",
""
] |
I have a 2 dimensional array, like so:
```
char[,] str = new char[2,50];
```
Now, after I've stored contents in both str[0] and str[1], how do I store it in a
```
string[] s = new string[2];
```
?
I tried
```
s[0] = str[0].ToString();
```
but that seems to be an error: VC# expects 'two' indices within the braces... | A jagged array is almost always the best solution for a variety of reasons, and this is one good example. There is so much more flexibility available with an array of arrays than with a multi-dimensional array. In this case, once you have the values in an array of chars, then a constructor on the string class can be us... | Assuming the dimensions are fixed as 2x50:
```
char[,] str = new char[2,50];
// populate str somehow
// chose which of the strings we want (the 'row' index)
int strIndex = 0;
// create a temporary array (faster and less wasteful than using a StringBuilder)
char[] chars = new chars[50];
for (int i = 0; i < 50; i++)
... | How do I create a string from one row of a two dimensional rectangular character array in C#? | [
"",
"c#",
"arrays",
"string",
"character",
"multidimensional-array",
""
] |
I just played with Java file system API, and came down with the following function, used to copy binary files. The original source came from the Web, but I added try/catch/finally clauses to be sure that, should something wrong happen, the Buffer Streams would be closed (and thus, my OS ressources freed) before quiting... | The try/finally pattern is the correct way to handle streams in most cases for Java 6 and lower.
*Some are advocating silently closing streams. Be careful doing this for these reasons: [Java: how not to make a mess of stream handling](http://illegalargumentexception.blogspot.com/2008/10/java-how-not-to-make-mess-of-st... | Unfortunately, this type of code tends to get a bit bloated in Java.
By the way, if one of the calls to oSBuffer.read or oDBuffer.write throws an exception, then you probably want to let that exception permeate up the call hierarchy.
Having an unguarded call to close() inside a finally-clause will cause the original ... | RAII in Java... is resource disposal always so ugly? | [
"",
"java",
"design-patterns",
"raii",
"resource-management",
""
] |
Here is the directory layout that was installed with Leopard. What is the "A" directory and why the "Current" directory in addition to the "CurrentJDK"?
It seems like you can easily switch the current JDK by move the CurrentJDK link, but then the contents under Current and A will be out of sync.
```
lrwxr-xr-x 1 roo... | The (`A`, `Current` symbolic-linked to `A`) is part of the structure of a Mac OS X framework, which `JavaVM.framework` is. This framework may have C or Objective-C code in it, in addition to the actual JVM installations. Thus it could potentially be linked against from some C or Objective-C code in addition to containi... | You should use the Java Preferences command to change the jvm version.
If you have spotlight on your Harddisk, you can just spotlight "Java Preferences" | Explain the JVM Directory Layout on Mac OSX Leopard | [
"",
"java",
"macos",
"jvm",
""
] |
I have a function pointer defined by:
```
typedef void (*EventFunction)(int nEvent);
```
Is there a way to handle that function with a specific instance of a C++ object?
```
class A
{
private:
EventFunction handler;
public:
void SetEvent(EventFunction func) { handler = func; }
void EventOne() { handler... | I highly recommend Don Clugston's excellent FastDelegate library. It provides all the things you'd expect of a real delegate and compiles down to a few ASM instructions in most cases. The accompanying article is a good read on member function pointers as well.
<http://www.codeproject.com/KB/cpp/FastDelegate.aspx> | You can use function pointers to index into the vtable of a given object instance. This is called a [member function pointer](http://www.parashift.com/c++-faq-lite/pointers-to-members.html). Your syntax would need to change to use the ".\*" and the "&::" operators:
```
class A;
class B;
typedef void (B::*EventFunction... | Calling a C++ function pointer on a specific object instance | [
"",
"c++",
"pointers",
"function",
""
] |
What are some practical uses for the "[Curiously Recurring Template Pattern](http://en.wikipedia.org/wiki/Curiously_Recurring_Template_Pattern)"? The "[counted class](http://en.wikipedia.org/wiki/Curiously_Recurring_Template_Pattern#Object_counter)" example commonly shown just isn't a convincing example to me. | [Simulated dynamic binding](http://c2.com/cgi/wiki?SimulatedDynamicBinding).
Avoiding the cost of virtual function calls while retaining some of the hierarchical benefits is an enormous win for the subsystems where it can be done in the project I am currently working on. | It's also especially useful for **mixins** (by which I mean classes you inherit from to provide functionality) which themselves need to know what type they are operating on (and hence need to be templates).
In *Effective C++*, Scott Meyers provides as an example a class template NewHandlerSupport<T>. This contains a s... | Practical Uses for the "Curiously Recurring Template Pattern" | [
"",
"c++",
"templates",
"design-patterns",
"crtp",
"f-bounded-polymorphism",
""
] |
I have to lock user accounts in Active Directory programmatically in C#.
Unfortunately it doesn't work via the userAccountControl attribute. Every time I set userAccountControl to 528 (=normal account w/ lockout flag), Active Directory won't accept the value and resets it without further notice to 512 (=normal account... | Make sure the account you're using to disable the account has sufficient privileges to disable accounts. See [this example](http://msdn.microsoft.com/en-us/library/ms696026(VS.85).aspx) from Microsoft. | This code will work to lock a user in AD
```
/// <summary>
/// Locks a user account
/// </summary>
/// <param name="userName">The name of the user whose account you want to unlock</param>
/// <remarks>
/// This actually trys to log the user in with a wrong password.
/// This in turn will lock the user out
/// </remar... | Lock Active Directory accounts programmatically | [
"",
"c#",
"active-directory",
""
] |
Trying to use an excpetion class which could provide location reference for XML parsing, found an interesting behavior - compiler could not choose between overload which consumes an interface and one which needs System.Exception when I trying to pass XmlReader as a parameter.
Detais are following:
```
//exception ove... | The line:
```
//fails
throw new FilterXmlParseException("<Filter> element expected", reader);
```
because XmlReader doesn't implement IXmlLineInfo. I am not sure if your cast works, but the casts are not checked statically. If it actually works, it is because the concrete class (that inherits from XmlReader) implemen... | It couldn't choose an overload for the XmlReader call because *neither* overload is acceptable. XmlReader does not inherit from Exception, so the first call is invalid. XmlReader also does not Implement IXmlLineInfo.
The reason why it works in the second case is that you are forcing the cast. However, I believe that i... | Compiler could not choose an overload between interface and exception | [
"",
"c#",
".net",
"compiler-construction",
""
] |
I'm looking for books or online resources that go in detail over programming techniques for high performance computing using C++. | practically all HPC code I've heard of is either for solving sytems of linear equations or FFT's. Heres some links to start you off at least in the libraries used:
* [BLAS](http://en.wikipedia.org/wiki/Blas) - standard set of routines for linear algebra - stuff like matrix multiplication
* [LAPACK](http://en.wikipedia... | Even though not FOSS, the Intel [IPP](http://www.intel.com/cd/software/products/asmo-na/eng/302910.htm) and [MKL](http://www.intel.com/cd/software/products/asmo-na/eng/307757.htm) libraries can really save you a lot of time (both in development and at runtime) if you need to perform any of the operations supported by t... | Resources for high performance computing in C++ | [
"",
"c++",
"performance",
""
] |
I'm trying to think of clever, clear, and simple ways to write code that describes the sequence of integers in a given range.
Here's an example:
```
IEnumerable<int> EnumerateIntegerRange(int from, int to)
{
for (int i = from; i <= to; i++)
{
yield return i;
}
}
``` | This is already in the framework: [Enumerable.Range](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.range.aspx).
For other types, you might be interested in the range classes in my [MiscUtil](http://pobox.com/~skeet/csharp/miscutil) library. | Alternately, a fluent interface from extension methods:
```
public static IEnumerable<int> To(this int start, int end)
{
return start.To(end, i => i + 1);
}
public static IEnumerable<int> To(this int start, int end, Func<int, int> next)
{
int current = start;
while (current < end)
{
yield retu... | What's the best way to write [0..100] in C#? | [
"",
"c#",
"linq",
"optimization",
"sequences",
""
] |
What is the best way to divide a 32 bit integer into four (unsigned) chars in C#. | Quick'n'dirty:
```
int value = 0x48454C4F;
Console.WriteLine(Encoding.ASCII.GetString(
BitConverter.GetBytes(value).Reverse().ToArray()
));
```
Converting the int to bytes, reversing the byte-array for the correct order and then getting the ASCII character representation from it.
EDIT: The `Reverse` method is an e... | Char? Maybe you are looking for this handy little helper function?
```
Byte[] b = BitConverter.GetBytes(i);
Char c = (Char)b[0];
[...]
``` | Conversion from 32 bit integer to 4 chars | [
"",
"c#",
"encoding",
""
] |
I have seen arguments for using explicit interfaces as a method of locking a classes usage to that interface. The argument seems to be that by forcing others to program to the interface you can ensure better decoupling of the classes and allow easier testing.
Example:
```
public interface ICut
{
void Cut();
}
pub... | To quote GoF chapter 1:
* "Program to an interface, not an implementation".
* "Favor object composition over class inheritance".
As C# does not have multiple inheritance, object composition and programming to interfaces are the way to go.
ETA: And you should never use multiple inheritance anyway but that's another t... | I've only used it in scenarios where I want to restrict access to certain methods.
```
public interface IWriter
{
void Write(string message);
}
public interface IReader
{
string Read();
}
public class MessageLog : IReader, IWriter
{
public string Read()
{
// Implementation
r... | Using explicit interfaces to ensure programming against an interface | [
"",
"c#",
"design-patterns",
"interface",
""
] |
Where do you store *user-specific* and *machine-specific* **runtime** configuration data for J2SE application?
(For example, *C:\Users\USERNAME\AppData\Roaming</em> on Windows and /home/username* on Unix)
How do you get these locations in the filesystem in platform-independent way? | That depends on your kind of J2SE Application:
* J2SE executable JAR file (very simple): use [user.home System property](http://www.mindspring.com/~mgrand/java-system-properties.htm) to find home-dir. Then make a subdir accordingly (like e.g. PGP, SVN, ... do)
* Java Web Start provides very nice included methods to sa... | First on the format:
1. Java [property files](http://java.sun.com/j2se/1.5.0/docs/api/java/util/Properties.html#load(java.io.InputStream)) are good for key/value pairs (also automatically handle the newline chars). A degree of structure is possible by using 'dot notation'. Drawback is that the structure does not allow... | What is the proper way to store app's conf data in Java? | [
"",
"java",
"configuration",
""
] |
Recently thanks to rails' popularity, many people start using activerecord as model. however, before I heard of rails (my peer group was not a fan of open source stuff, we were taught in a .NET school...) and while I was doing my final year project, i found this definition for a model
> The model represents enterprise... | Martin Fowler described this pattern in Patterns of Enterprise Application Architecture together with two other patterns or architectures. These patterns are good for different situations and different amounts of complexity.
If you want to so only simple stuff you can use Transaction Script. This is an architecture yo... | I've said many times that using Active Record (or ORM which is almost the same) as Business Models is not a good idea. Let me explain:
The fact that PHP is Open Source, Free (and all that long story...) provides it with a vast community of developers pouring code into forums, sites like GitHub, Google code and so on. ... | activerecord as model, is this a good idea? | [
"",
"php",
"model-view-controller",
"activerecord",
""
] |
Working in Eclipse on a Dynamic Web Project (using Tomcat (v5.5) as the app server), is there some way I can configure things so Tomcat will start with security turned on (i.e. as if I ran catalina.sh start -security)? | Go into 'Window' -> 'Preferences' then select 'Java' -> 'Installed JREs', clone the JRE used by Tomcat and add the following to the default VM Arguments
```
-Djava.security.manager -Djava.security.policy="XXXX\conf\catalina.policy"
```
With XXXX replaced by the appropriate path - Mine was `C:\Program Files\Apache Sof... | Or you can just check "Enable Security" in Server Overview page.
(Server -> your server setting -> Overview )
then eclipse will add parameters below
> -Djava.security.manager -Djava.security.policy=X:XXX\XXX.metadata.plugins\org.eclipse.wst.server.core\tmp0\conf\catalina.policy
> -Dwtp.configured.security=true | Configuring tomcat security manager in Eclipse | [
"",
"java",
"eclipse",
"tomcat",
""
] |
Lately I've been taking a look at [Haxe](http://haxe.org), to build an application to be deployed to Apache running PHP. Well, while it looks like it might suit my needs (deploying to PHP, but not using an awful language), I haven't found anything to make the actual application development easier than building a tradit... | There is a port of PureMVC for Haxe: [https://github.com/PureMVC/puremvc-haxe-standard-framework/wiki](https://github.com/PureMVC/puremvc-haxe-standard-framework/wiki "PureMVC haXe")
As far as I know this the only thing for Haxe, but there are discussions on the mailing list about creating a own framework, but this co... | I'm happy to say that haXigniter has been completely rewritten, to get away from the PHP-framework-style as mentioned by Marek. Now it adheres much more to better OO-principles and is also a standard haXe library, so upgrades are much simpler. Please check it out at <http://github.com/ciscoheat/haxigniter>. | Web "frameworks" for Haxe to deploy in a PHP environment? | [
"",
"php",
"web-frameworks",
"haxe",
""
] |
Structs seem like a useful way to parse a binary blob of data (ie a file or network packet). This is fine and dandy until you have variable size arrays in the blob. For instance:
```
struct nodeheader{
int flags;
int data_size;
char data[];
};
```
This allows me to find the last data character... | You cannot have multiple variable sized arrays. How should the compiler at compile time know where friend[] is located? The location of friend depends on the size of data[] and the size of data is unknown at compile time. | This is a very dangerous construct, and I'd advise against it. You can only include a variable-length array in a struct when it is the LAST element, and when you do so, you have to make sure you allocate enough memory, e.g.:
```
nodeheader *nh = (nodeheader *)malloc(sizeof(nodeheader) + max_data_size);
```
What you w... | Dereferencing Variable Size Arrays in Structs | [
"",
"c++",
"struct",
""
] |
What is the difference between applying the visitor design pattern to your code and the following approach:
```
interface Dointerface {
public void perform(Object o);
}
public class T {
private Dointerface d;
private String s;
public String getS() {
return s;
}
public T(String s)... | Two things:
* In your example you need two methods. The `perfom` and the `setInterface`. With a visitor pattern you would only need one method, the `perfom`, usually called `accept`.
* If you need more than one 'performer', you will have to set the performer -via the `setInterface` method- for each. This makes it impo... | There is quite a big difference.
The visitor pattern uses interfaces, but its purpose is to be able to perform an operation to one or more classes (who implement an interface) without having to change the classes. Hence, the implementation actually "visits" the class and does its thing without the class being modified... | what is the difference between using the visitor pattern and an interface? | [
"",
"java",
"design-patterns",
"coding-style",
"visitor-pattern",
""
] |
I want to make a JavaScript application that's not open source, and thus I wish to learn how to can obfuscate my JS code? Is this possible? | **Obfuscation:**
Try [**YUI Compressor**](http://yuilibrary.com/). It's a very popular tool, built, enhanced and maintained by the Yahoo UI team.
You may also use:
* [Google Closure Compiler](http://closure-compiler.appspot.com/home)
* [UglifyJS](http://marijnhaverbeke.nl/uglifyjs)
`UPDATE: This question was origin... | I'm surprised no one has mentioned Google's [Closure Compiler](http://code.google.com/closure/compiler/). It doesn't just minify/compress, it analyzes to find and remove unused code, and rewrites for maximum minification. It can also do type checking and will warn about syntax errors.
JQuery recently switched from YUI... | How can I obfuscate (protect) JavaScript? | [
"",
"javascript",
"obfuscation",
"source-code-protection",
""
] |
Does any one know how can I convert a BSTR to an int in VC++ 2008
Thanks in advance. | You can [pass a BSTR safely](https://stackoverflow.com/questions/71980/how-do-you-efficiently-copy-bstr-to-wchart) to any function expecting a `wchar_t *`. So you can use [\_wtoi](http://msdn.microsoft.com/en-us/library/yd5xkb5c(VS.80).aspx)(). | Google suggests [`VarI4FromStr`](http://msdn.microsoft.com/en-us/library/windows/desktop/ms221194%28v=vs.85%29.aspx):
```
HRESULT VarI4FromStr(
_In_ LPCOLESTR strIn,
_In_ LCID lcid,
_In_ ULONG dwFlags,
_Out_ LONG *plOut
);
``` | Convert BSTR to int | [
"",
"c++",
"winapi",
""
] |
I notice that modern C and C++ code seems to use `size_t` instead of `int`/`unsigned int` pretty much everywhere - from parameters for C string functions to the STL. I am curious as to the reason for this and the benefits it brings. | The `size_t` type is the unsigned integer type that is the result of the `sizeof` operator (and the `offsetof` operator), so it is guaranteed to be big enough to contain the size of the biggest object your system can handle (e.g., a static array of 8Gb).
The `size_t` type may be bigger than, equal to, or smaller than ... | Classic C (the early dialect of C described by Brian Kernighan and Dennis Ritchie in The C Programming Language, Prentice-Hall, 1978) didn't provide `size_t`. The C standards committee introduced `size_t` to eliminate a portability problem
[Explained in detail at embedded.com (with a very good example)](http://www.emb... | unsigned int vs. size_t | [
"",
"c++",
"c",
"size-t",
""
] |
What is the SQL command to copy a table from one database to another database?
I am using MySQL and I have two databases x and y. Suppose I have a table in x called a and I need to copy that table to y database.
Sorry if the question is too novice.
Thanks. | If your two database are separated, the simplest thing to do would be to create a dump of your table and to load it into the second database. Refer to your database manual to see how a dump can be performed.
Otherwise you can use the following syntax (for MySQL)
```
INSERT INTO database_b.table (SELECT * FROM databas... | If the target table doesn't exist....
```
CREATE TABLE dest_table AS (SELECT * FROM source_table);
```
If the target table does exist
```
INSERT INTO dest_table (SELECT * FROM source_table);
```
Caveat: Only tested in Oracle | SQL Command for copying table | [
"",
"sql",
"mysql",
""
] |
I've been writing some providers in c# that inherit from the providerbase class. I've found that it's hard to write tests that use the providers as most mocking frameworks will only allow you to mock an interface.
Is there any way to mock a call to a provider that inherits from providerbase?
If not, is there a patter... | Mocking frameworks should be able to create for you a mock object based on a class, as long as it's got virtual members.
You may also want to take a look at [Typemock](http://www.typemock.com/) | I know Rhino mocks can mock classes too, most other mocking frameworks should have no problems with this either.
Things too keep in mind: The class can't be sealed. You need to mark methods you want to mock virtual and the class needs a constructor with no arguments this can be protected, private won't work. (just tr... | Mocking classes that aren't interfaces | [
"",
"c#",
"unit-testing",
"mocking",
""
] |
I want to calculate the time span between 2 times which I saved in a database.
So literally I want to know the length of time between the 2 values.
14:10:20 - 10:05:15 = 02:05:05
So the result would be 02:05:05.
How would I be able to achieve this using C#?
14:10:20 is the format I saved it in in my database. | Read the two time values into TimeSpan variables, then perform a `.Subtract()` on the bigger TimeSpan variable to get the TimeSpan result.
E.g. `TimeSpan difference = t1.Subtract(t2);`. | Your first step will be to get the timevalues stored in your database into .NET `DateTime` structs.
If you stored them as SQL-DateTime values in the database you can get them directly as `DateTime`. It would look something like this:
```
SQLCommand getTimeCommand = new SQLCommand("SELECT time FROM table", dbConnectio... | How do you calculate accumulative time in C#? | [
"",
"c#",
"datetime",
"time",
""
] |
I'm experimenting with internationalization by making a Hello World program that uses properties files + ResourceBundle to get different strings.
Specifically, I have a file "messages\_en\_US.properties" that stores "hello.world=Hello World!", which works fine of course.
I then have a file "messages\_ja\_JP.propertie... | I realized that native2ascii was assuming (surprise) that it was converting from my operating system's default encoding each time, and as such not producing the correct escaped Unicode string.
Running native2ascii with the "-encoding *encoding\_name*" option where *encoding\_name* was the name of the source file's enc... | As of JDK 1.6, Properties has a [load()](http://java.sun.com/javase/6/docs/api/java/util/Properties.html#load(java.io.Reader)) method that accepts a Reader. That means you can save all the property files as UTF-8 and read them all directly by passing an InputStreamReader to load(). I think that's the most elegant solut... | How do I properly store and retrieve internationalized Strings in properties files? | [
"",
"java",
"encoding",
"properties",
"internationalization",
""
] |
Are there PHP libraries which can be used to fill PDF forms and then save (flatten) them to PDF files? | The libraries and frameworks mentioned here are good, but if all you want to do is fill in a form and flatten it, I recommend the command line tool called pdftk (PDF Toolkit).
See <https://www.pdflabs.com/tools/pdftk-the-pdf-toolkit/>
You can call the command line from php, and the command is
`pdftk` *formfile.pdf* ... | A big +1 to the accepted answer, and a little tip if you run into encoding issues with the fdf file. If you generate the fields.fdf and upon running
```
file -bi fields.fdf
```
you get
```
application/octet-stream; charset=binary
```
then you've most likely run into a UTF-16 character set issue.
Try converting the ... | Filling PDF Forms with PHP | [
"",
"php",
"pdf",
""
] |
I've never had to do IPC on Windows before. I'm developing a pair of programs, a standard GUI/CLI app, and a windows service. The app has to tell the service what to do. So, assuming the communication is local only, what would be the best communication method for these two processes?
By best I mean more robust and le... | IPC in .Net can be achieved using:
# WCF
using named pipes **requires .Net 3.0** and above.
## Code example
* The WCF class **NetNamedPipeBinding** can be used for interprocess communication on the same machine. The MSDN documentaion for this class includes a code sample covering this scenario <http://msdn.microsof... | For local only, we have had success using Named Pipes. Avoids the overhead of TCP, and is pretty much (at least for .NET) as efficient as you can get while also having a decent API to work with. | Interprocess communication for Windows in C# (.NET 2.0) | [
"",
"c#",
".net",
"ipc",
""
] |
What I would like is a method to convert a double to a string which rounds using the half-up method - i.e. if the decimal to be rounded is 5, it always rounds up to the next number. This is the standard method of rounding most people expect in most situations.
I also would like only significant digits to be displayed ... | Use [`setRoundingMode`](http://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html#setRoundingMode(java.math.RoundingMode)), set the [`RoundingMode`](http://docs.oracle.com/javase/8/docs/api/java/math/RoundingMode.html) explicitly to handle your issue with the half-even round, then use the format pattern for... | Assuming `value` is a `double`, you can do:
```
(double)Math.round(value * 100000d) / 100000d
```
That's for 5 digits precision. The number of zeros indicate the number of decimals. | How to round a number to n decimal places in Java | [
"",
"java",
"decimal",
"rounding",
"digits",
""
] |
I want to programmatically create a new column in an MS Access table. I've tried many permutations of `ALTER TABLE MyTable Add MyField DECIMAL (9,4) NULL;` and got:
> Syntax Error in Field Definition
I can easily create a number field that goes to a `Double` type, but I want `decimal`. I would very strongly prefer to... | If you want to create a new column in an acces table, it is easy to use the DAO.tableDef object:
```
Dim my_tableDef As DAO.TableDef
Dim my_field As DAO.Field
Set my_tableDef = currentDb.TableDefs(my_table)
Set my_Field = my_tableDef.CreateField(my_fieldName, dbDecimal, myFieldSize)
my_Field.decimalPlaces = myDecimal... | The decimal data type isn't supported in the default Jet 4.0 mdb file. You have to use the SQL Server compatibility syntax (ANSI 92) setting to use the decimal data type in the SQL Window.
Click on the menu, Tools > Options. Click on the Tables/Query tab. Mark the check box for "This database" in the SQL Server compat... | How do I create a decimal field in Access with Alter Table? | [
"",
"sql",
"ms-access",
""
] |
I am attempting to use linq to shape list of data into a particular shape to be returned as Json from an ajax call.
Given this data:
```
var data = new List<string>();
data.Add("One");
data.Add("Two");
data.Add("Three");
```
And this code: \*\* Which is not correct and is what needs to be fixed!! \*\*
```
var shape... | Solution offered for correctness, not performance.
```
List<string> data = new List<string>()
{
"One",
"Two",
"Three"
};
string result =
"{ "
+
string.Join(", ", data
.Select(c => @"""" + c + @""": ""... | In json, the "c" in "c" : "One" is the property name. And in the C# world, you can't create property names on the fly (ignoring System.ComponentModel).
Basically, I don't think you can do what you want. | Object Initializer syntax to produce correct Json | [
"",
"c#",
"linq",
"json",
""
] |
This is a minor bug (one I'm willing to live with in the interest of go-live, frankly), but I'm wondering if anyone else has ideas to fix it.
I have a C# WinForms application. When the app is launched via the executable (not via the debugger), the first thing the user sees is a console window, followed by the main win... | My first guess would be to double check your Project Property settings and make sure that the output type is Windows Application and not Console Application. | I found it.
When the project is built in Visual Studio, there are no problems -- no console window.
When the project is built from CruiseControl, that's when we get a console window.
The difference? Visual Studio (based on my election of a WinForms app) is appending /target:winexe to the csc line.
CruiseControl cal... | Console window displays at WinForm startup (C#) | [
"",
"c#",
".net",
"winforms",
""
] |
If I have a subclass that has yet to implement a function provided by the base class, I can override that function and have it throw a `NotSupportedException`. Is there a way to generate a compile-time error for this to avoid only hitting this at runtime?
Update: I can't make the base class abstract. | [Obsolete("This still needs implementing", true/false)] true if you don't want the build to succeed, false if you just want a warning
Slightly hackish ... but it does the job of warning at compile time. | You can make the base class abstract:
```
abstract class Foo
{
public abstract void Bar();
}
```
Now, any subclass must implement `Bar()`, or it won't compile. | Compile-time error for NotSupportedException in subclass function | [
"",
"c#",
"exception",
"inheritance",
""
] |
There's another post on SO relating to .NET -- not us. Pure PHP. Trying to find the best way/process to deploy stable version of our PHP app. I've seen an article on [Capistrano](http://www.simplisticcomplexity.com/2006/8/16/automated-php-deployment-with-capistrano/), but am curious what else is out there. Aside from t... | I've used a home-grown script for quite some time. It will (based on an application configuration file):
1. Run `svn export` on the repository based on a tag.
2. Package the export into a tar or zip file, which includes the tag in the name.
3. Use `scp` to copy the package to the appropriate server (QA or release).
4.... | Coincidentally, I was just reading about an Apache Ant/gnu make like build tool called [Phing](http://phing.info). What I like about it is the ability to write [custom extensions](http://phing.info/docs/guide/current/chapters/ExtendingPhing.html#WritingTasks) in PHP! | What's the best process / app for automated deployment of PHP apps? | [
"",
"php",
"deployment",
""
] |
The [Flot API documentation](http://flot.googlecode.com/svn/trunk/API.txt) describes the library's extensive hooks for customizing the axes of a graph. You can set the number of ticks, their color, etc. separately for each axis. However, I can not figure out how to prevent Flot from drawing the vertical grid lines with... | As Laurimann noted, Flot continues to evolve. The ability to control this has been added to the API (as noted in the flot issue Nelson linked to).
If you download the latest version (which is still labeled 0.6), you can disable lines on an axis with "tickLength", like so:
```
xaxis: {
tickLength: 0
}
```
Rather an... | This post comes over two years later than OP and Flot (now version 0.6) might have evolved a lot during that time or maybe there's better options than it around but in either case here's my contribution.
I accidentally bumped into a workaround for this problem: set grid's tick color's alpha channel to fully transparen... | In Flot, is it possible to eliminate or hide grid ticks without eliminating the corresponding label? | [
"",
"javascript",
"jquery",
"graph",
"flot",
""
] |
I want to attach a click event to a button element and then later remove it, but I can't get `unclick()` or `unbind()` event(s) to work as expected. In the code below, the button is `tan` colour and the click event works.
```
window.onload = init;
function init() {
$("#startButton").css('background-color', 'beige... | There's no such thing as `unclick()`. Where did you get that from?
You can remove individual event handlers from an element by calling unbind:
```
$("#startButton").unbind("click", process_click);
```
If you want to remove all handlers, or you used an anonymous function as a handler, you can omit the second argument... | Or you could have a situation where you want to unbind the click function just after you use it, like I had to:
```
$('#selector').click(function(event){
alert(1);
$(this).unbind(event);
});
``` | Event handling jQuery unclick() and unbind() events? | [
"",
"javascript",
"jquery",
"css",
"event-handling",
""
] |
Is there any way to redefine a class or some of its methods without using typical inheritance? For example:
```
class third_party_library {
function buggy_function() {
return 'bad result';
}
function other_functions(){
return 'blah';
}
}
```
What can I do to replace `buggy_function()`?... | It's called [monkey patching](http://en.wikipedia.org/wiki/Monkey_patch). But, PHP doesn't have native support for it.
Though, as others have also pointed out, the [runkit library](http://docs.php.net/runkit) is available for adding support to the language and is the successor to [classkit](http://docs.php.net/manual/... | runkit seems like a good solution but its not enabled by default and parts of it are still experimental. So I hacked together a small class which replaces function definitions in a class file. Example usage:
```
class Patch {
private $_code;
public function __construct($include_file = null) {
if ( $include_file ... | Redefine Class Methods or Class | [
"",
"php",
"class",
"methods",
"redefine",
""
] |
I have a collection of classes that I want to serialize out to an XML file. It looks something like this:
```
public class Foo
{
public List<Bar> BarList { get; set; }
}
```
Where a bar is just a wrapper for a collection of properties, like this:
```
public class Bar
{
public string Property1 { get; set; }
pub... | Just to check, have you marked Bar as [Serializable]?
Also, you need a parameter-less ctor on Bar, to deserialize
Hmm, I used:
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
Foo f = new F... | Everything looks great. As @Carl said you need to add the **[Serializable]** attibute to your classes, but other than that your XML creation should work find.
**Foo**
```
[Serializable]
[XmlRoot("Foo")]
public class Foo
{
[XmlArray("BarList"), XmlArrayItem(typeof(Bar), ElementName = "Bar")]
public List<Bar> B... | Serializing Lists of Classes to XML | [
"",
"c#",
"xml",
"serialization",
""
] |
Consider:
```
var something = {
wtf: null,
omg: null
};
```
My JavaScript knowledge is still horribly patchy since I last programmed with it, but I think I've relearned most of it now. Except for this. I don't recall ever seeing this before. What is it? And where can I learn more about it? | It is an object literal with two properties. Usually this is how people create associative arrays or hashes because JS doesn't natively support that data structure. Though note that it is still a fully-fledged object, you can even add functions as properties:
```
var myobj = {
name: 'SO',
hello: function() {
... | It's object literal syntax. The 'wft' and 'omg' are property names while, null and null are the property values.
It is equivalent to:
```
var something = new Object();
something.wtf = null;
something.omg = null;
```
Check out Mozilla's documentation on object literals: <https://developer.mozilla.org/en-US/docs/Web/J... | What is this thing in JavaScript? | [
"",
"javascript",
"object-literal",
""
] |
Here's the jist of the problem: Given a list of sets, such as:
```
[ (1,2,3), (5,2,6), (7,8,9), (6,12,13), (21,8,34), (19,20) ]
```
Return a list of groups of the sets, such that sets that have a shared element are in the same group.
```
[ [ (1,2,3), (5,2,6), (6,12,13) ], [ (7,8,9), (21,8,34) ], [ (19,20) ] ]
```
N... | The problem is exactly the computation of the connected components of an hypergraph: the integers are the vertices, and the sets are the hyperedges. A usual way of computing the connected components is by flooding them one after the other:
* for all i = 1 to N, do:
* if i has been tagged by some j < i, then continue (... | You could think of it as a graph problem where the set (1,2,3) is connected to the set (5,2,6) via the 2. And then use a standard algorithm to fine the connected sub-graphs.
Here's a quick python implementation:
```
nodes = [ [1,2,3], [2,4,5], [6,7,8], [10,11,12], [7,10,13], [12], [] ]
links = [ set() for x in nodes ... | Partition a list of sets by shared elements | [
"",
"sql",
"algorithm",
"set",
""
] |
What's the C++ way of parsing a string (given as char \*) into an int? Robust and clear error handling is a plus (instead of [returning zero](http://en.cppreference.com/w/cpp/string/byte/atoi)). | In the new C++11 there are functions for that: stoi, stol, stoll, stoul and so on.
```
int myNr = std::stoi(myString);
```
It will throw an exception on conversion error.
Even these new functions still have the **same issue** as noted by Dan: they will happily convert the string "11x" to integer "11".
See more: <ht... | ## What not to do
Here is my first piece of advice: **do not use stringstream for this**. While at first it may seem simple to use, you'll find that you have to do a lot of extra work if you want robustness and good error handling.
Here is an approach that intuitively seems like it should work:
```
bool str2int (int... | How to parse a string to an int in C++? | [
"",
"c++",
"parsing",
""
] |
I'm trying to write a faster user switching app for Windows. Win+L and selecting users is very cumbersome. If I start Task Manager as administrator, it shows active users and I can select one and "Connect" (if I enter their password).
How do I get the list of all users (or all active users)?
I'm using C# (Visual Stud... | I'd try [WTSEnumerateSessions](http://msdn.microsoft.com/en-us/library/aa383833(VS.85).aspx) to get all available sessions. | If you'd rather not deal with the P/Invokes, you can use [Cassia](http://cassia.googlecode.com), which wraps the ugly for you:
```
using Cassia;
foreach (ITerminalServicesSession session in new TerminalServicesManager().GetSessions())
{
if (!string.IsNullOrEmpty(session.UserName))
{
Console.WriteLine(... | How do I get a list of local Windows users who are logged in? | [
"",
"c#",
".net",
"windows",
""
] |
Is there a freely available Base64 decoding code snippet in C++? | See *[Encoding and decoding base 64 with C++](http://www.adp-gmbh.ch/cpp/common/base64.html)*.
Here is the implementation from that page:
```
/*
base64.cpp and base64.h
Copyright (C) 2004-2008 René Nyffenegger
This source code is provided 'as-is', without any express or implied
warranty. In no event wil... | Here's my modification of [the implementation that was originally written by *René Nyffenegger*](http://www.adp-gmbh.ch/cpp/common/base64.html). And why have I modified it? Well, because it didn't seem appropriate to me that I should work with binary data stored within `std::string` object ;)
**base64.h**:
```
#ifnde... | Base64 decode snippet in C++ | [
"",
"c++",
"base64",
""
] |
I mostly use lambda functions but sometimes use nested functions that seem to provide the same behavior.
Here are some trivial examples where they functionally do the same thing if either were found within another function:
**Lambda function**
```
>>> a = lambda x : 1 + x
>>> a(5)
6
```
**Nested function**
```
>>>... | If you need to assign the `lambda` to a name, use a `def` instead. `def`s are just syntactic sugar for an assignment, so the result is the same, and they are a lot more flexible and readable.
`lambda`s can be used for *use once, throw away* functions which won't have a name.
However, this use case is very rare. You r... | Practically speaking, to me there are two differences:
The first is about what they do and what they return:
* def is a keyword that doesn't return anything and creates a 'name' in the local namespace.
* lambda is a keyword that returns a function object and does not create a 'name' in the local namespace.
Hence, if... | Which is more preferable to use: lambda functions or nested functions ('def')? | [
"",
"python",
"syntax",
"function",
"lambda",
""
] |
In my `urls.py` file, I have:
```
from myapp import views
...
(r'^categories/$', views.categories)
```
Where `categories` is a view function inside `myapp/views.py`. No other URLconf lines reference `views.categories`.
In a unit test file, I’m trying to grab this URL using `django.core.urlresolvers.reverse()`, inste... | After futher investigation, turns out it was an issue with how I was importing the views module:
[How do I successfully pass a function reference to Django’s reverse() function?](https://stackoverflow.com/questions/146522/how-do-i-successfully-pass-a-function-reference-to-djangos-reverse-function)
Thanks for the help... | Jack M.'s example is nearly correct.
It needs to be a url function, not a tuple, if you want to use named urls.
```
url(r'^no_monkeys/$', 'views.noMonkeys', {}, "no-monkeys"),
``` | How do I use django.core.urlresolvers.reverse with a function reference instead of a named URL pattern? | [
"",
"python",
"django",
""
] |
I collect a few corner cases and [brain teasers](http://www.yoda.arachsys.com/csharp/teasers.html) and would always like to hear more. The page only really covers C# language bits and bobs, but I also find core .NET things interesting too. For example, here's one which isn't on the page, but which I find incredible:
`... | I think I showed you this one before, but I like the fun here - this took some debugging to track down! (the original code was obviously more complex and subtle...)
```
static void Foo<T>() where T : new()
{
T t = new T();
Console.WriteLine(t.ToString()); // works fine
Console.WriteLine... | Bankers' Rounding.
This one is not so much a compiler bug or malfunction, but certainly a strange corner case...
The .Net Framework employs a scheme or rounding known as Banker's Rounding.
In Bankers' Rounding the 0.5 numbers are rounded to the nearest even number, so
```
Math.Round(-0.5) == 0
Math.Round(0.5) == 0
... | What's the strangest corner case you've seen in C# or .NET? | [
"",
"c#",
".net",
""
] |
In visual C++, I can do things like this:
```
template <class T>
class A{
protected:
T i;
};
template <class T>
class B : public A<T>{
T geti() {return i;}
};
```
If I try to compile this in g++, I get an error. I have to do this:
```
template <class T>
class B : public A<T>{
T geti() {return A<T>::i;}
... | This used to be allowed, but changed in [gcc 3.4](http://gcc.gnu.org/gcc-3.4/changes.html#cplusplus).
In a template definition, unqualified names will no longer find members of a dependent base (as specified by [temp.dep]/3 in the C++ standard). For example,
```
template <typename T> struct B {
int m;
... | I figured this one out:
* [C++ Super FAQ: "Why am I getting errors when my template-derived-class uses a nested type it inherits from its template-base-class?"](https://isocpp.org/wiki/faq/templates#nondependent-name-lookup-types)
* [C++ Super FAQ: "Why am I getting errors when my template-derived-class uses a member ... | Accessing protected members from subclasses: gcc vs msvc | [
"",
"c++",
"gcc",
"g++",
"visual-c++",
""
] |
I got a text file with a couple of lines and I am looking for a string in this file. I need to pass following command line parameters to the program:
- file path
- the string I am looking for
- maximum number of processes the program is allowed to "fork" in order to complete this task.
How to such a program shou... | A couple of thoughts.
* You will have to open the file separately from each process, otherwise they will share a single file descriptor and thus have a shared position in the file (or not, see the comments, as this may be system specific...).
* You may not see the speed increase you are hoping for due to disk access a... | Consider why you think you need to parallelize this, and if you're going to see any actual performance benefit. You're likely to be limited by disk access time, and there's overhead to forking. Your best option might be to do a standard single-threaded search (probably with a regex). | How to paralleize search for a string in a file with a help of fork? (GNU Linux/g++) | [
"",
"c++",
"linux",
"file",
"search",
"parallel-processing",
""
] |
In the STL library some containers have iterators and it is commonly held that they are a superior way of iterating through these containers rather than simple for loops e.g.
```
for ( int i=0; i < vecVector.size(); i++ )
{
..
}
```
Can anyone tell me why and in what cases I should use iterators and in what cases t... | Note that the usually implementation of vector won't use an "int" as the type of the index/size. So your code will at the very least provoke compiler warnings.
### Genericity
Iterators increase the genericity of your code.
For example:
```
typedef std::vector<int> Container ;
void doSomething(Container & p_aC)
{
... | Using iterators allows your code to be agnostic about the implementation of your container. If random access for your container is cheap, there isn't much difference performance-wise.
But in lots of cases you won't know whether that is the case. If you try do use your method on a linked list, for example, with subscri... | Iterators.. why use them? | [
"",
"c++",
"stl",
"iterator",
""
] |
Basically what the title says. (Forgive me because I am a .NET newb)
In my department, we have a server running .net 3.5 and ever since I got into this section I have been using LINQ. However, I am starting a personal project on a different server (obviously), so 2 questions:
What do I need to get up and running with... | To get up and running, I would definitely recommend checking out [LINQ in Action](https://rads.stackoverflow.com/amzn/click/com/1933988169 "LINQ in Action").

Your compiler needs to be [.NET 3.5 framework](http://www.microsoft.com/downloads/details.aspx?FamilyId=333325F... | I would encourage you to check out [LinqPad](http://www.linqpad.net/) as a learning tool. It's a standalone application that lets you play with Linq queries without worrying about getting it to run on a server. | Getting started using Linq, what do I need? | [
"",
"c#",
".net",
"linq",
""
] |
The following code:
```
template <typename S, typename T>
struct foo {
void bar();
};
template <typename T>
void foo <int, T>::bar() {
}
```
gives me the error
```
invalid use of incomplete type 'struct foo<int, T>'
declaration of 'struct foo<int, T>'
```
(I'm using gcc.) Is my syntax for partial specialization... | You can't partially specialize a function. If you wish to do so on a member function, you must partially specialize the entire template (yes, it's irritating). On a large templated class, to partially specialize a function, you would need a workaround. Perhaps a templated member struct (e.g. `template <typename U = T> ... | Although coppro mentioned two solutions already and Anonymous explained the second one, it took me quite some time to understand the first one. Maybe the following code is helpful for someone stumbling across this site, which still ranks high in google, like me. The example (passing a vector/array/single element of num... | "invalid use of incomplete type" error with partial template specialization | [
"",
"c++",
"gcc",
"templates",
"partial-specialization",
""
] |
I've recently inherited C# console application that is in need of some pruning and clean up. Long story short, the app consists of a single class containing over 110,000 lines of code. Yup, over 110,000 lines in a single class. And, of course, the app is core to our business, running 'round the clock updating data used... | You could try to use [NDepend](http://www.ndepend.com/) if you just need to extract some stats about your class. Note that this tool relies on Mono.Cecil internally to inspect assemblies. | To complete the *Romain Verdier* answer, lets dig a bit into what NDepend can bring to you here. (*Disclaimer: I am a developer of the NDepend team*)
NDepend lets query your .NET code with some LINQ queries. Knowing which methods call and is called by which others, is as simple as writing the following LINQ query:
``... | How do you programmatically identify the number of references to a method with C# | [
"",
"c#",
"refactoring",
""
] |
I have many years of experience in Java including Swing, Servlet and JDBC, but have never programmed for a Java EE server.
Many job advertisements from large companies are specifically asking for Java EE experience. Are there specific skills or development environments that I should learn to qualify for these kinds of... | Download JBoss and get to work on the sample applications in the documentation. If you've done java, you're 95% there. Java EE adds the container and naming aspect to the java you already know and love. With the advent of EJB3, beans got a lot simpler as you only need a couple of annotations to get rolling with EJB. Ja... | "Are there specific skills or development environments that I should learn to qualify for these kinds of jobs?"
If I were to interview someone for a typical Java EE shop, I would like to know how well you know the following
1) servlets
2) EJB (maybe)
3) JSP
4) ant
5) junit
6) subversion or other VCS
7) h... | Java EE Programming Skills | [
"",
"java",
"jakarta-ee",
""
] |
What is the difference between the `search()` and `match()` functions in the Python `re` module?
I've read the [Python 2 documentation](https://docs.python.org/2/library/re.html?highlight=matching%20searching#search-vs-match) ([Python 3 documentation](https://docs.python.org/3/library/re.html#search-vs-match)), but I ... | `re.match` is anchored at the beginning of the string. That has nothing to do with newlines, so it is not the same as using `^` in the pattern.
As the [re.match documentation](http://docs.python.org/2/library/re.html#re.match) says:
> If zero or more characters at the
> **beginning of string** match the regular expre... | `search` ⇒ find something anywhere in the string and return a match object.
`match` ⇒ find something at the *beginning* of the string and return a match object. | What is the difference between re.search and re.match? | [
"",
"python",
"regex",
"search",
"match",
"string-matching",
""
] |
I was trying to insert new data into an existing XML file, but it's not working. Here's my xml file:
```
<list>
<activity>swimming</activity>
<activity>running</activity>
<list>
```
Now, my idea was making two files: an index page, where it displays what's on the file and provides a field for inserting new el... | is your code block copy and pasted from your existing files? if so i see two potential issues:
```
<form name='input' action'insert.php' method='post'> // should be:
<form name="input" action="insert.php" method="post">
```
note: you're missing `action`**=**`"insert.php"`, which would cause the form to just reload it... | Final Solution
**sample.XML**
```
<list>
<activity>swimming</activity>
<activity>running</activity>
<activity>Jogging</activity>
<activity>Theatre</activity>
<activity>Programming</activity>
</list>
```
**index.php**
```
<html>
<head><title>test</title></head>
</head>
<?php
$xmldoc = new DO... | Inserting data in XML file with PHP DOM | [
"",
"php",
"xml",
"dom",
""
] |
What is the best way to take a given PHP object and serialize it as XML? I am looking at simple\_xml and I have used it to parse XML into objects, but it isn't clear to me how it works the other way around. | take a look at PEAR's [XML\_Serializer](http://pear.php.net/package/XML_Serializer) package. I've used it with pretty good results. You can feed it arrays, objects etc and it will turn them into XML. It also has a bunch of options like picking the name of the root node etc.
Should do the trick | I'd agree with using PEAR's XML\_Serializer, but if you want something simple that supports objects/arrays that have properties nested, you can use this.
```
class XMLSerializer {
// functions adopted from http://www.sean-barton.co.uk/2009/03/turning-an-array-or-object-into-xml-using-php/
public static funct... | PHP Object as XML Document | [
"",
"php",
"xml",
"xml-serialization",
""
] |
I am working a standalone c# desktop application that sends out documents and then imports them from Outlook when they are sent back. The application picks up the emails from a specified folder processes them and then saves the senders name plus other stuff to a database.
This works well for Outlook 2003 and 2007 whic... | I'm using the Outlook Redemption solution in a C# production code. It works beautifully.
With it, you can get the SenderID of a mail message (IRDOMail), and from there, you can use the GetAddressEntryFromID() method of the IRDOSession object. | While having a similar problem at work, we decided to go the netMAPI route, which has caused some problems.
The main problem with it is that MAPI managed its own memory, as does .NET meaning that occasionally (we have around 300 people using our in house software) it would cause our application to crash, generating th... | Consistently retrieve "From" email addresses across Outlook versions | [
"",
"c#",
".net",
"outlook",
"ms-office",
""
] |
I am trying to convert an `int` into three `bytes` representing that `int` (big endian).
I'm sure it has something to do with bit-wise and and bit shifting. But I have no idea how to go about doing it.
For example:
```
int myInt;
// some code
byte b1, b2 , b3; // b1 is most significant, then b2 then b3.
```
\*Not... | To get the least significant byte:
```
b3 = myInt & 0xFF;
```
The 2nd least significant byte:
```
b2 = (myInt >> 8) & 0xFF;
```
And the 3rd least significant byte:
```
b1 = (myInt >> 16) & 0xFF;
```
**Explanation:**
Bitwise ANDing a value with 0xFF (11111111 in binary) will return the least significant 8 bits (b... | ```
byte b1 = (myint >> 16) & 0xff;
byte b2 = (myint >> 8) & 0xff;
byte b3 = myint & 0xff;
```
I am unsure how this holfds in java though, i aam not a java dev | How can I turn an int into three bytes in Java? | [
"",
"java",
"bit-manipulation",
"byte",
"bit-shift",
""
] |
Other than standard OO concepts, what are some other strategies that allow for producing good, clean PHP code when a framework is not being used? | Remember: MVC, OOP and tiers are design concepts, not language constructs, nor file-structuring.
For me, this means that when not using a framework, and when there's not different teams for programming and designing; there's no value in using *another* template system on top of PHP (which is a template language). Also... | I'd say pretty much the same as for any other language:
* Don't optimise prematurely
* Keep methods small
* Practise DRY
* Practise data-driven programming
* Use sensible shortcuts (e.g. ternary operator)
* Format your code well so that it can be understood by others
* Don't use OO blindly
* Always check return codes ... | How do you write good PHP code without the use of a framework? | [
"",
"php",
""
] |
What is the most efficient way to get the default constructor (i.e. instance constructor with no parameters) of a System.Type?
I was thinking something along the lines of the code below but it seems like there should be a simplier more efficient way to do it.
```
Type type = typeof(FooBar)
BindingFlags flags = Bindin... | ```
type.GetConstructor(Type.EmptyTypes)
``` | If you actually **need** the ConstructorInfo object, then see [Curt Hagenlocher's answer](https://stackoverflow.com/questions/142356/most-efficient-way-to-get-default-constructor-of-a-type#142362).
On the other hand, if you're really just trying to create an object at run-time from a `System.Type`, see [`System.Activa... | Most efficient way to get default constructor of a Type | [
"",
"c#",
".net",
"reflection",
""
] |
I hope this is programmer-related question. I'm in the hobby business of C# programming. For my own purposes I need to parse html files and the best idea is..regular expression. As many found out, it's quite time consuming to learn them and thus I'm quite interested if you know about some application that would be able... | Yes there is Roy Osherove wrote exactly what you're looking for - [regulazy](http://files.osherove.com/Regulazy/Regulazy.103.zip) | You might also want to try txt2re : <http://txt2re.com/>, which tries to identify patterns in a user-supplied string and allows to build a regex out of them. | Is there an Application to Create Regular Expression Out of Text by Selecting Wanted Area? | [
"",
"c#",
"regex",
"automation",
""
] |
[JavaScript post request like a form submit](https://stackoverflow.com/q/133925) shows you how to submit a form that you create via POST in JavaScript. Below is my modified code.
```
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "test.jsp");
var hiddenFie... | Add
```
<form target="_blank" ...></form>
```
or
```
form.setAttribute("target", "_blank");
```
to your form's definition. | If you want to create and submit your form from Javascript as is in your question and you want to create popup window with custom features I propose this solution (I put comments above the lines i added):
```
var form = document.createElement("form");
form.setAttribute("method", "post");
form.setAttribute("action", "t... | After submitting a POST form open a new window showing the result | [
"",
"javascript",
"html",
"post",
""
] |
I am just checking out F#, so apologies if this is a silly question, but in the VS2008 F# CTP 1.9.6.2 'Tutorial' project, both // and /// are used for commenting code.
Is there a functional difference between the two slash vs three slash commenting, or is it convention (as it appears in the tutorial code) to comment a... | Using three slashes (///) is a C# convention for [XML Documentation Comments](https://learn.microsoft.com/en-gb/dotnet/csharp/programming-guide/xmldoc/) that is adopted by F# as well. | /// is for documentation comments. VS will use it when generating intellisense information. | .NET // vs /// Comments convention | [
"",
"c#",
"f#",
"comments",
""
] |
I am looking for a method to compare and sort UTF-8 strings in C++ in a case-insensitive manner to use it in a [custom collation function in SQLite](http://www.sqlite.org/c3ref/create_collation.html).
1. The method should *ideally* be locale-independent. However I won't be holding my breath, as far as I know, collatio... | What you really want is logically impossible. There is no locale-independent, case-insensitive way of sorting strings. The simple counter-example is "i" <> "I" ? The naive answer is no, but in Turkish these strings are unequal. "i" is uppercased to "İ" (U+130 Latin Capital I with dot above)
UTF-8 strings add extra com... | I have no definitive answer in the form of example code, but I should point out that an UTF-8 bytestream contains, in fact, Unicode characters and you have to use the wchar\_t versions of the C/C++ runtime library.
You have to convert those UTF-8 bytes into wchar\_t strings first, though. This is not very hard, as the... | Case-insensitive UTF-8 string collation for SQLite (C/C++) | [
"",
"c++",
"sqlite",
"unicode",
"utf-8",
"internationalization",
""
] |
How do you perform a CROSS JOIN with LINQ to SQL? | A cross-join is simply the Cartesian product of two sets. There's no explicit join operator for it.
```
var combo = from p in people
from c in cars
select new
{
p.Name,
c.Make,
c.Model,
c.Colour
};
``` | The same thing with the Linq extension method `SelectMany` (lambda syntax):
```
var names = new string[] { "Ana", "Raz", "John" };
var numbers = new int[] { 1, 2, 3 };
var newList=names.SelectMany(
x => numbers,
(y, z) => { return y + z + " test "; });
foreach (var item in newList)
{
Console.WriteLine(item... | How do you perform a CROSS JOIN with LINQ to SQL? | [
"",
"c#",
"linq",
"linq-to-sql",
"cross-join",
""
] |
With very large amounts of ram these days I was wondering, it is possible to allocate a single chunk of memory that is larger than 4GB? Or would I need to allocate a bunch of smaller chunks and handle switching between them?
Why???
I'm working on processing some openstreetmap xml data and these files are huge. I'm cur... | Short answer: Not likely
In order for this to work, you absolutely would **have** to use a 64-bit processor.
Secondly, it would depend on the Operating System support for allocating more than 4G of RAM to a single process.
In theory, it would be possible, but you would have to read the documentation for the memory al... | **A Primer on physcal and virtual memory layouts**
You would need a 64-bit CPU and O/S build and almost certainly enough memory to avoid thrashing your working set. A bit of background:
A 32 bit machine (by and large) has registers that can store one of 2^32 (4,294,967,296) unique values. This means that a 32-bit poi... | Can you allocate a very large single chunk of memory ( > 4GB ) in c or c++? | [
"",
"c++",
"c",
"memory",
"malloc",
""
] |
I'm using a lot of JQuery in a web application that I am building for a client and I want to find an javascript implementation of a modal dialog that is reasonably stable across the following browser set.
IE 7+
FF 2+
Chrome and Safari
I've tried a couple of jQuery plugins but there always seems to be artifacts in one... | I used [jqModal](http://dev.iceburg.net/jquery/jqModal/) few times and I'm very satisfied. It is pretty configurable yet very light weight. | Have you tried [YUI](http://developer.yahoo.com/yui/container/dialog/)? I'm not sure what the support is for Chrome but I've had good luck with it for IE and Firefox and allegedly it works with Safari. | What is the most stable modal dialog implementation across browsers to use from javascript for a web app? | [
"",
"javascript",
"jquery",
"modal-dialog",
"cross-browser",
"jqmodal",
""
] |
For my current C++ project I need to detect a unique string for every monitor that is connected and active on a large number of computers.
Research has pointed to 2 options
1. Use WMI and query the Win32\_DesktopMonitor for all active monitors. Use the PNPDeviceID for unique identification of monitors.
2. Use the Enu... | This is my current work-in-progress code for detecting the monitor device id, reliably.
```
CString DeviceID;
DISPLAY_DEVICE dd;
dd.cb = sizeof(dd);
DWORD dev = 0;
// device index
int id = 1;
// monitor number, as used by Display Properties > Settings
while (EnumDisplayDevices(0, dev, &dd, 0))
{
DISPLAY_DEVI... | I've just discovered you can query Win32\_PnPEntity for service="monitor", and it will return all monitors.
Results on my machine:
```
select * from Win32_PnPEntity where service="monitor"
Availability | Caption | ClassGuid | CompatibleID | ConfigManagerErrorCode | ConfigMa... | EnumDisplayDevices vs WMI Win32_DesktopMonitor, how to detect active monitors? | [
"",
"c++",
"windows",
"winapi",
"wmi",
""
] |
I'm playing around with the [`<canvas>`](http://developer.mozilla.org/en/HTML/Canvas) element, drawing lines and such.
I've noticed that my diagonal lines are antialiased. I'd prefer the jaggy look for what I'm doing - is there any way of turning this feature off? | For images there's now [`context.imageSmoothingEnabled`](http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#dom-context-2d-imagesmoothingenabled)`= false`.
However, there's nothing that explicitly controls line drawing. You may need to draw your own lines ([the hard way](http://en.wiki... | Draw your `1-pixel` lines on coordinates like `ctx.lineTo(10.5, 10.5)`. Drawing a one-pixel line over the point `(10, 10)` means, that this `1` pixel at that position reaches from `9.5` to `10.5` which results in two lines that get drawn on the canvas.
A nice trick to not always need to add the `0.5` to the actual coo... | Can I turn off antialiasing on an HTML <canvas> element? | [
"",
"javascript",
"html",
"canvas",
"antialiasing",
""
] |
I have a method that's about ten lines of code. I want to create more methods that do exactly the same thing, except for a small calculation that's going to change one line of code. This is a perfect application for passing in a function pointer to replace that one line, but Java doesn't have function pointers. What's ... | Anonymous inner class
Say you want to have a function passed in with a `String` param that returns an `int`.
First you have to define an interface with the function as its only member, if you can't reuse an existing one.
```
interface StringFunction {
int func(String param);
}
```
A method that takes the point... | For each "function pointer", I'd create a small [functor class](http://en.wikipedia.org/wiki/Function_object#In_Java) that implements your calculation.
Define an interface that all the classes will implement, and pass instances of those objects into your larger function. This is a combination of the "[command pattern](... | What's the nearest substitute for a function pointer in Java? | [
"",
"java",
"closures",
"function-pointers",
""
] |
I keep reading about how great this new Canvas element for HTML5 is and I see amazing demos done with just javascript and no flash. Where can I find some good information on how to some of these things myself? | [The specification](http://www.whatwg.org/specs/web-apps/current-work/multipage/the-canvas-element.html#the-canvas-element) defines the API and behaviour.
[This tutorial](http://developer.mozilla.org/en/Canvas_tutorial) should help you get started. | There's the original [Apple tutorial](http://developer.apple.com/documentation/AppleApplications/Conceptual/SafariJSProgTopics/Tasks/Canvas.html)
Also the [draft html5 spec](http://www.w3.org/html/wg/html5/#the-canvas-element)
And of course you can (as people have) ask questions about specific features, etc on SO :D | Where can I find some good information about how the new canvas HTML element works? | [
"",
"javascript",
"html",
"canvas",
""
] |
When is it a good idea to use [`PHP_EOL`](https://www.php.net/manual/en/reserved.constants.php)?
I sometimes see this in code samples of PHP. Does this handle DOS/Mac/Unix endline issues? | Yes, `PHP_EOL` is ostensibly used to find the newline character in a cross-platform-compatible way, so it handles DOS/Unix issues.
Note that [PHP\_EOL](http://php.net/manual/en/reserved.constants.php) represents the endline character for the *current* system. For instance, it will not find a Windows endline when execu... | From `main/php.h` of PHP version 7.1.1 and version 5.6.30:
```
#ifdef PHP_WIN32
# include "tsrm_win32.h"
# include "win95nt.h"
# ifdef PHP_EXPORTS
# define PHPAPI __declspec(dllexport)
# else
# define PHPAPI __declspec(dllimport)
# endif
# define PHP_DIR_SEPARATOR '\\'
# define PHP_EOL "\r\n"... | When do I use the PHP constant "PHP_EOL"? | [
"",
"php",
"eol",
""
] |
I have a new application written in WPF that needs to support an old API that allows it to receive a message that has been posted to a hidden window. Typically another application uses FindWindow to identify the hidden window using the name of its custom window class.
**1) I assume to implement a custom window class I... | For the record I finally got this to work.
Turned out the difficulties I had were down to string marshalling problems.
I had to be more precise in my importing of win32 functions.
Below is the code that will create a custom window class in c# - useful for supporting old APIs you might have that rely on custom window c... | I'd like to comment the answer of morechilli:
```
public CustomWindow(string class_name){
if (class_name == null) throw new System.Exception("class_name is null");
if (class_name == String.Empty) throw new System.Exception("class_name is empty");
// Create WNDCLASS
WNDCLASS wind_class = new WNDCLASS(... | Registering a custom win32 window class from c# | [
"",
"c#",
"windows",
"winapi",
"interop",
""
] |
I am using PHP with Apache on Linux, with Sendmail. I use the PHP [`mail`](http://php.net/manual/en/function.mail.php) function. The email is sent, but the envelope has the `Apache_user@localhostname` in `MAIL FROM` (example nobody@conniptin.internal) and some remote mail servers reject this because the domain doesn't ... | mail() has a 4th and 5th parameter (optional). The 5th argument is what should be passed as options directly to sendmail. I use the following:
```
mail('to@blah.com','subject!','body!','From: from@blah.com','-f from@blah.com');
``` | I would also recommend checking into [PHPMailer](http://phpmailer.codeworxtech.com). It's great for creating and sending email, making the process a lot easier, along with support for SMTP. | How to change envelope from address using PHP mail? | [
"",
"php",
"email",
""
] |
I have followed all the instructions here: <http://www.tonyspencer.com/2003/10/22/curl-with-php-and-apache-on-windows/>
to install & config apache
get the PHP5 packages
and get the CURL packages.
I run the apache and run a PHP script. no problem.
but when I run the php script with curl, it fails.
It returns: `**Call... | You're probably mistaking what PHP.ini you need to edit. first, add a PHPinfo(); to a info.php, and run it from your browser.
Write down the PHP ini directory path you see in the variables list now!
You will probably notice that it's different from your PHP-CLI ini file.
Enable the extension
You're done :-) | **Use the following steps to install curl:**
1. Open <https://curl.haxx.se/dlwiz?type=bin> in a browser.
2. Select your operating system in the dropdown box: either Windows /Win32 or Win 64. Click Select!
3. For Win 32, choose whether you will use curl in a Windows Command Prompt (Generic) or in a Cygwin terminal (cyg... | How do I install cURL on Windows? | [
"",
"php",
"windows",
"curl",
"windows-xp",
"installation",
""
] |
How can I determine if I have write permission on a remote machine in my intranet using C# in .Net? | The simple answer would be to try it and see. The Windows security APIs are not for the faint of heart, and may be possible you have write permission without having permission to view the permissions! | Been there too, the best and most reliable solution I found was this:
```
bool hasWriteAccess = true;
string remoteFileName = "\\server\share\file.name"
try
{
createRemoteFile(remoteFileName);
}
catch (SystemSecurityException)
{
hasWriteAccess = false;
}
if (File.Exists(remoteFileName))
{
File.Del... | How can I programmatically determine if I have write privileges using C# in .Net? | [
"",
"c#",
".net",
"networking",
"file-permissions",
""
] |
In Gmail, I have a bunch of labeled messages.
I'd like to use an IMAP client to get those messages, but I'm not sure what the search incantation is.
```
c = imaplib.IMAP4_SSL('imap.gmail.com')
c.list()
('OK', [..., '(\\HasNoChildren) "/" "GM"', ...])
c.search(???)
```
I'm not finding many examples for this sort of t... | `imaplib` is intentionally a thin wrapper around the IMAP protocol, I assume to allow for a greater degree of user flexibility and a greater ability to adapt to changes in the IMAP specification. As a result, it doesn't really offer any structure for your search queries and requires you to be familiar with the [IMAP sp... | ```
import imaplib
obj = imaplib.IMAP4_SSL('imap.gmail.com', 993)
obj.login('username', 'password')
obj.select('**label name**') # <-- the label in which u want to search message
obj.search(None, 'FROM', '"LDJ"')
``` | How do I perform an IMAP search in Python (using Gmail and imaplib)? | [
"",
"python",
"gmail",
"imap",
""
] |
i have a library with some entities that share the same interface. clients and service share this assembly. now i wonder if there is a way to have this Interface-type as Parameter in my service contracts so that i can use the same method for all classes implementing the interface.
the entities themselve are all decora... | I solved the problem using the ServiceKnownType attribute at the implementations of the OperationContracts.
When telling your classes that implement the interface as ServiceKnownType's, you can use the interface as parameter and therefore are able to use all classes implementing your interface as long as they are seri... | It certainly isn't possible under regular "mex". It *might* be possible with assembly sharing, but I really wouldn't recommend it - you are fighting WCF: it will be brittle, etc. Of course, you can always mask this in your object model - i.e. rather than calling the [OperationContract] method directly, abstract this aw... | Wcf and Interfaces as Parameters | [
"",
"c#",
".net",
"wcf",
"web-services",
""
] |
I am converting an excel sheet formula to java but I can't understand how excel manages to take the following: 0.22
Applies a formula: =TEXT(R5/14, "h:mm")
and somehow arrives at: 0.22
Again if I provide: 2.8
it arrives at 4.48
Can someone please explain to me how it does this. I have read a little regarding decimal a... | Excel stores datetime values as:
* The number to the left of the decimal represents the number of days since January 1, 1900
* The number to the right of the decimal represents the fractional portion of a 24-hour day
In your example, you are converting a decimal to a textual representation of the hour and minute port... | Or the Abacus Formula Compiler for Java, which allows you to compile the formulas in Excel sheets right down to Java byte code for fast and easy calling from your Java apps (can compile at run-time without the JDK).
<http://www.formulacompiler.org/> | Expressing Excel formula in Java (decimal to time interpretation) | [
"",
"java",
"excel",
"datetime",
"decimal",
""
] |
I'm writing an app which for various reasons involves Internet Explorer (IE7, for the record), ActiveX controls, and a heroic amount of JavaScript, which is spread across multiple .js includes.
One of our remote testers is experiencing an error message and IE's error message says something to the effect of:
```
Line:... | In short. Not really. Try finding the error in FF first, and if that fails, you can get an almost as good debugger with [Visual Web Developer](http://www.berniecode.com/blog/2007/03/08/how-to-debug-javascript-with-visual-web-developer-express/). Debugging IE just sucks for the most part. | The best way I found to debug javascript was to add several Response.Write() or alert message near the place i believed the code broke. The write or alert that doesn't show is closest to the problematic area of the code.
I did it this way because I haven't found an easier way.
Update: If you use this method of debugg... | Is there any good or reliable way to figure out where a JavaScript error is using only an Internet Explorer error message? | [
"",
"javascript",
"debugging",
"internet-explorer",
""
] |
Simply put, is there a way to create a 2D javascript array using similar syntax to this?
```
var newArray = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
``` | You can create any n-dimensional arrays using *exactly* the format you suggest as in the following sample:
```
<script>
var newArray = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
var newArray3d =
[[[ 0, 1, 2],[ 3, 4, 5],[ 6, 7, 8]],
[[10, 11, 12],[13, 14, 15],[16, 17,... | Yes. This works fine:
```
<script>
var newArray = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8]
]
alert(newArray[0][2]);
</script>
``` | 2D Javascript array | [
"",
"javascript",
"arrays",
"multidimensional-array",
""
] |
How can dynamic Key-value pairs of objects be stored in app.config in using the application settings api, at runtime?
I've been trying to get my head around, and I can't find any meaningful example or documentation.
I seems that .Net dictionary classes can't be serialized in XML to store them in app.config
Is the on... | After some more searching net, I've found a very good (albeit very long) article which describes in dept the .Net configuration model:
[Unraveling the Mysteries of .NET 2.0 Configuration](http://www.codeproject.com/KB/dotnet/mysteriesofconfiguration.aspx)
I also found something very usefull:
[Configuration Section D... | You ought to be able to do something like this:
```
// Open App.Config of executable
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
// Add an Application Setting with a name Key and a Value stored in variable called Value
config.AppSettings.Settings... | How to store key-value pairs in application settings at runtime? | [
"",
"c#",
".net",
"settings",
"app-config",
""
] |
How does one do this?
If I want to analyze how something is getting compiled, how would I get the emitted assembly code? | Use the [-S](https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-S) option to `gcc` (or `g++`), optionally with [-fverbose-asm](https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#index-fverbose-asm) which works well at the default [-O0](https://gcc.gnu.org/onlinedocs/gcc/Optimize-Options.html#index-O0) ... | This will generate assembly code with the C code + line numbers interwoven, to more easily see which lines generate what code ([-S](https://gcc.gnu.org/onlinedocs/gcc/Overall-Options.html#index-S) [-fverbose-asm](https://gcc.gnu.org/onlinedocs/gcc/Code-Gen-Options.html#index-fverbose-asm) [-g](https://gcc.gnu.org/onlin... | How do you get assembler output from C/C++ source in GCC? | [
"",
"c++",
"c",
"assembly",
"gcc",
"disassembly",
""
] |
I have a problem which requires me to parse several log files from a remote machine.
There are a few complications:
1) The file may be in use
2) The files can be quite large (100mb+)
3) Each entry may be multi-line
To solve the in-use issue, I need to copy it first. I'm currently copying it directly from the remote ma... | If you are reading a sequential file you want to read it in line by line over the network. You need a transfer method capable of streaming. You'll need to review your IO streaming technology to figure this out.
Large IO operations like this won't benefit much by multithreading since you can probably process the items ... | The better option, from the perspective of performance, is going to be to perform your parsing at the remote server. Apart from exceptional circumstances the speed of your network is always going to be the bottleneck, so limiting the amount of data that you send over your network is going to greatly improve performance... | What's the best way to read and parse a large text file over the network? | [
"",
"c#",
".net",
"multithreading",
"parsing",
"networking",
""
] |
I'm developing non-interactive cpu-bound application which does only computations, almost no IO. Currently it works too long and while I'm working on improving the algorithm, I also think if it can give any benefit to change language or platform. Currently it is C++ (no OOP so it is almost C) on windows compiled with I... | Just to be thorough: the first thing to do is to gather profile data and the second thing to do is consider your algorithms. I'm sure you know that, but they've got to be #included into any performance-programming discussion.
To be direct about your question "Can switching to ASM help?" the answer is "If you don't kno... | It's always algorithm, rarely language. Here's my clue: "while I'm working on improving the algorithm".
Tweaking may not be enough.
Consider radical changes to the algorithm. You've got to eliminate processing, not make the processing go faster. The culprit is often "search" -- looping through data looking for someth... | What language/platform would you recommend for CPU-bound application? | [
"",
"c++",
"performance",
"algorithm",
""
] |
I was asked to build a java system that will have the ability to load new code (expansions) while running.
How do I re-load a jar file while my code is running? or how do I load a new jar?
Obviously, since constant up-time is important, I'd like to add the ability to re-load existing classes while at it (if it does no... | Reloading existing classes with existing data is likely to break things.
You can load new code into new class loaders relatively easily:
```
ClassLoader loader = URLClassLoader.newInstance(
new URL[] { yourURL },
getClass().getClassLoader()
);
Class<?> clazz = Class.forName("mypackage.MyClass", true, loader);... | This works for me:
```
File file = new File("c:\\myjar.jar");
URL url = file.toURL();
URL[] urls = new URL[]{url};
ClassLoader cl = new URLClassLoader(urls);
Class cls = cl.loadClass("com.mypackage.myclass");
``` | How to load a jar file at runtime | [
"",
"java",
"jar",
"runtime",
"classloader",
""
] |
Suppose you have a collection of `Foo` classes:
```
class Foo
{
public string Bar;
public string Baz;
}
List<Foo> foolist;
```
And you want to check this collection to see if another entry has a matching `Bar`.
```
bool isDuplicate = false;
foreach (Foo f in foolist)
{
if (f.Bar == SomeBar)
{
... | ```
fooList.Exists(item => item.Bar == SomeBar)
```
That's not LINQ, but a Lambda expression, but nevertheless, it uses a v3.5 feature. No problem:
```
fooList.Exists(delegate(Foo Item) { return item.Bar == SomeBar});
```
That should work in 2.0. | Implement the [IEqualityComparer<T>](http://msdn.microsoft.com/en-us/library/ms132151.aspx) interface, and use the matching [Contains](http://msdn.microsoft.com/en-us/library/bb339118.aspx) method.
```
public class MyFooComparer: IEqualityComparer<Foo> {
public bool Equals(Foo foo1, Foo foo2) {
return Equals... | Checking for duplicates in a collection | [
"",
"c#",
".net",
".net-2.0",
""
] |
**Summary:** C#/.NET is supposed to be garbage collected. C# has a destructor, used to clean resources. What happen when an object A is garbage collected the same line I try to clone one of its variable members? Apparently, on multiprocessors, sometimes, the garbage collector wins...
**The problem**
Today, on a train... | It's simply a bug in your code: finalizers should not be accessing managed objects.
The only reason to implement a finalizer is to release unmanaged resources. And in this case, you should carefully implement [the standard IDisposable pattern](http://msdn.microsoft.com/en-us/library/b1yfkh5e.aspx).
With this pattern,... | What you're seeing is perfectly natural.
You don't keep a reference to the object that owns the byte array, so that object (not the byte array) is actually free for the garbage collector to collect.
The garbage collector really can be that aggressive.
So if you call a method on your object, which returns a reference... | Finalizer launched while its object was still being used | [
"",
"c#",
".net",
"garbage-collection",
"finalization",
""
] |
I want to log to the console when I'm using un-minimized JavaScript files.
Comments are taken out already when I minimize JavaScript. I'm wondering if there's a way I can write a command that isn't commented out but will still be taken out when I minimize the JavaScript file. | If your goal is just to reduce the js size you can separate you logging functions into a separate file.
In your "main" js add a function `function doLogging(object){}` then in your separate logging functions file replace the function with `function doLogging(object){/*your logging code*/};`
Just remember to include y... | I think I'd be pretty upset if a Javascript minimizer changed the behaviour of my code based on some funny/clever/odd code construct. How could you ever be sure that code construct isn't there intentionally?
As has been suggested, have a variable that disables logging. Then as part of your minimize script or batch job... | Javascript Commands Only Executed When Unminimized | [
"",
"javascript",
"minimize",
""
] |
I have a legacy application that is written in C# and it displays a very complex treeview with 10 to 20 thousand elements.
In the past I encountered a similar problem (but in C++) that i solved with the OWNERDATA capability offered by the Win32 API.
Is there a similar mechanism in C#?
EDIT: The plan is to optimize t... | I don't believe the .NET TreeView supports what you want, although this type of model is supported by .NET's DataGridView (see DataGridView's [VirtualMode](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.virtualmode.aspx) property). The TreeView will let you draw your own nodes but it won't le... | One technique for improving performance is to load TreeNodes as the user expands the treeview. Normally a user will not require 20,000 nodes to be open on their screen at once. Only load the level that the user needs to see, along with whatever child information you need to properly display affordances to the user (exp... | Slow treeview in C# | [
"",
"c#",
"winforms",
"user-interface",
"optimization",
""
] |
How can I validate that my ASPNET AJAX installation is correct.
I have Visual Studio 2008 and had never previously installed any AJAX version.
My UpdatePanel is nto working within IIS6, although it works ok within Visual Studio's web server. The behaviour I get is as if the UpdatePanel doesnt exist at all - i.e. it r... | Check for any JavaScript errors. Sometimes the JavaScript required for the UpdatePanel to work fails to load. | Another option would be to check your web.config. You could for example create an new Ajax enabled ASP.NET website from Visual Studio. This will generate a correct web.config. Copy over all non-ajax sections from your existing web.config and you're set. This worked for me.
-Edoode | How to validate ASPNET AJAX installation | [
"",
"c#",
"asp.net",
"ajax",
""
] |
I am trying to write a web service to spec and it requires a different response body depending on whether the method completes successfully or not. I have tried creating two different DataContract classes, but how can I return them and have them serialized correctly? | The answer is **yes** but it is tricky and you lose strong typing on your interface. If you return a **Stream** then the data could be xml, text, or even a binary image. For DataContract classes, you'd then serialize the data using the **DataContractSerializer**.
See the [BlogSvc](http://codeplex.com/blogsvc) and more... | The best way to indicate that your WCF web service has failed would be to throw a FaultException. There are settings in your service web.config files that allow the entire fault message to be passed to the client as part of the error.
Another approach may be to inherit both of your results from the same base class or ... | Is there a way to return different types from a WCF REST method? | [
"",
"c#",
".net",
"wcf",
"rest",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.