Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
In C/C++, if a multi-byte wide character (wchar\_t) value is transmitted from a big-endian system to a little-endian system (or vice-versa), will it come out the same value on the other side? Or will the bytes need to be swapped? | Yes you will need to swap them.
The bytes will be retrieved from the transport in the same order they were put in. Just at the other end the ordering of these bytes has a different meaning. So you need to convert them to the correct endian-ness (is that a word?).
The tried and true method is to convert to network by... | Endian conversion is not sufficient and as a consequence not needed. Sizeof(wchar\_t) differs, and therefore the encoding too. Hence, you need to agree on an interchange format. The logical choice is UTF-8. But since UTF-8 is byte-oriented, you do not have endianness issues anymore. | Is endian conversion required for wchar_t data? | [
"",
"c++",
"c",
"endianness",
"data-transfer",
"wchar-t",
""
] |
Imagine that I will make an async call in .NET, i.e. HttpWebRequest.BeginGetResponse, and the HttpWebRequest object isn't referenced at a broader scope. Will the Garbage Collector destroy it and cause problems?
Example code:
```
using System;
using System.Net;
public class AsyncHttpWebRequest
{
void Main()
{... | An object is considered alive and non-eligible for garbage collection if any live thread contains a reference to it, or if it's referenced statically (directly or indirectly in both cases).
In both examples the async API keeps a reference to your request (within the thread pool where async IO operations are lodged) an... | No, the garbage collector won't cause you problems.
Don't assume that because **you** don't have access to the object, the garbage collector is going to clean it up.
The garbage collector starts with a number of "roots" - objects and references that are known reachable. Then, all the objects reachable from those root... | Does the Garbage Collector destroy temporarily unreferenced objects during async calls in .NET? | [
"",
"c#",
".net",
"asynchronous",
"garbage-collection",
""
] |
I have a bunch of old classic ASP pages, many of which show database data in tables. None of the pages have any sorting functionality built in: you are at the mercy of whatever ORDER BY clause the original developer saw fit to use.
I'm working on a quick fix to tack on sorting via client-side javascript. I have a scri... | You can try grabbing the `cssText` and `className`.
```
var css1 = table.rows[1].style.cssText;
var css2 = table.rows[2].style.cssText;
var class1 = table.rows[1].className;
var class2 = table.rows[2].className;
// sort
// loop
if (i%2==0) {
table.rows[i].style.cssText = css1;
table.rows[i].class... | You can set the style attribute of any element... the trick is that in IE you have to do it differently. ([bug 245](http://webbugtrack.blogspot.com/2007/10/bug-245-setattribute-style-does-not.html))
```
//Standards base browsers
elem.setAttribute('style', styleString);
//Non Standards based IE browser
elem.style.setA... | Set HTML element's style property in javascript | [
"",
"javascript",
"html",
"styles",
""
] |
I know how to do a regular php mysql search and display the results. However, because of the nature of what I'm trying to accomplish I need to be able to sort by relevancy. Let me explain this better:
Normal Query "apple iphone applications" will search the database using %apple iphone application%, but if there aren'... | take a look at the [MySQL FULLTEXT search functions](http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html),
These should automatically return results by relevancy, and give you much more control over your searches
The only potential issue with using fulltext indexes is that they aren't supported by InnoDB table... | Maybe this might help someone (order by relevance and keep word count):
None full-text:
```
SELECT *, ( (value_column LIKE '%rusten%') + (value_column LIKE '%dagen%') + (value_column LIKE '%bezoek%') + (value_column LIKE '%moeten%') ) as count_words
FROM data_table
WHERE (value_column LIKE '%dagen%' OR value_column L... | PHP MySQL Search And Order By Relevancy | [
"",
"php",
"mysql",
"search",
""
] |
I read about using the CASE expression inside the WHERE clause here:
<http://scottelkin.com/sql/using-a-case-statement-in-a-sql-where-clause/>
I'm trying to use this to filter results from my select statement, based on a contract number which will be passed in by the user's application. My code currently throws an er... | After reading your explanation, there's a better way to do this without `CASE`:
```
WHERE @ContractNo = 0 OR tblContracts.ContractNo = @ContractNo
```
This will return only matching contract numbers, unless `@ContractNo` is 0, in which case it will return all records.
**Edit:** I've just noticed that [casperOne prop... | Are you sure you want to do this? Your case statement ALWAYS returns `@ContractNo`. I think what you are looking for is this:
```
where
case @ContractNo
when 0 then tblContracts.ContractNo
else @ContractNo
end = tblContracts.ContractNo
```
The filter above says "give me the contract where ... | SQL - CASE expression inside WHERE | [
"",
"sql",
"where-clause",
""
] |
I can't find the answer to this anywhere, and before I start pawing through generated code with Reflector I thought it'd be worth asking:
Suppose I have the following LINQ query run against DataTables in a DataSet:
```
var list =
from pr in parentTable.AsEnumerable()
join cr in childTable.AsEnumerable() on cr.... | I don't think so. In this case, LINQ to Objects will probably just treat the two sides as regular enumerable objects, and do the join manually (without looking at the `DataRelation`). | Digging around in Reflector didn't seem to give any indication that LINQ uses DataRelations, but that code's awfully hard to read. So I wrote a little performance test, and unless there's something dumb about the test that I missed, the results are pretty definitive: no, LINQ doesn't use DataRelations and GetChildRows(... | Does LINQ use DataRelations to optimize joins? | [
"",
"c#",
"linq",
"join",
"dataset",
"datarelation",
""
] |
I am trying to pass an XML list to a view but I am having trouble once I get to the view.
My controller:
```
public ActionResult Search(int isbdn)
{
ViewData["ISBN"] = isbdn;
string pathToXml= "http://isbndb.com/api/books.xml?access_key=DWD3TC34&index1=isbn&value1=";
pathToXml += isbdn;
... | first.. you have to return the data to the view modal...
```
public ActionResult Search(int isbdn)
{
ViewData["ISBN"] = isbdn;
string pathToXml= "http://isbndb.com/api/books.xml?access_key=DWD3TC34&index1=isbn&value1=";
pathToXml += isbdn;
var doc = XDocument.Load(pathToXml);
... | I don't know if you intentionally cut off your code half way through the method. But you should be able to do the following to get your elements from your controller action to the view:
```
ViewData["XmlItems"] = items;
```
then in your view you call
```
<% foreach(XElement e in ViewData["XmlItems"] as IEnumerable<X... | Passing a XML parsed list from a controller to a view in ASP.NET MVC | [
"",
"c#",
"asp.net-mvc",
"xml",
""
] |
I'd like to dynamicly parse in text wiki-content.
I found [JsWiki](http://sourceforge.net/projects/jswiki) but its in beta form, and looks like with no community even developers). Any other? | It depends what you mean by wiki content. There are many wiki frameworks just as there are many formats for wiki text. If you're looking for something that parses mediawiki content, such as wikipedia, there's a [good list of parsers here](http://www.mediawiki.org/wiki/Alternative_parsers). Some are Javascript based and... | You could use the [Ra-Ajax InPlaceEdit](http://ra-ajax.org/samples/Ajax-InPlaceEdit.aspx) for such things if you're on ASP.NET. It doesn't have automated built in wiki parsing, but it allows for adding up any control you wish including LinkButtons and Literals which you can then build up with the HTML you want yourself... | JavaScript edit-inplace-holders which work with Wiki sources | [
"",
"javascript",
"wiki-engine",
""
] |
I'm fiddling with calling DLLs from C#, and came across the need to define my own structs. Lots of articles force a sequential layout for the struct with
```
[StructLayout(LayoutKind.Sequential)]
struct Foo ...
```
So, I followed suite, and my programme worked. Now, when I took the line out, it still works. Why do I ... | The internal layout of a managed struct is undocumented and undiscoverable. Implementation details like member order and packing are intentionally hidden. With the [StructLayout] attribute, you force the P/Invoke marshaller to impose a specific layout and packing.
That the default just happens to match what you need t... | Interesting point. I'm sure I had code that failed until I put in an explicit LayoutKind.Sequential, however I have confirmed Sequential is the default for structures even in 1.1.
Note the [VB Reference for Structure](http://msdn.microsoft.com/en-us/library/k69kzbs1.aspx)
implies at Remarks > Behaviour > Memory Consum... | When should I explicitly specify a StructLayout? | [
"",
"c#",
"interop",
"struct",
"marshalling",
""
] |
I am developing a Java based desktop application. There are some data generated from the application object model that I need to persist (preferably to a file). There is also a requirement to protect the persisted file so that others can't derive the object model details from the data. What's the best strategy for doin... | Your question has two parts. 1st: How to persist data? 2nd: How to protect them?
There is a lot of ways how to persist data. From simple XML, java serialization to own data format. There is no way how to prevent revers engineering data just by "plain text". You can just make it harder, but not impossible. To make it q... | If you don't need to modify this file you can serialize the object graph to a file. The contents are binary and they could only be read using the classes where they were written.
You can also use Java DB ( shipped with java since 1.5 I think ) and an ORM tool for that such as Hibernate.
**EDIT**
It is bundled since ... | Object persistence strategy for desktop application | [
"",
"java",
"desktop",
"object-persistence",
""
] |
That is, if I had two or more sets, and I wanted to return a new set containing either:
1. All of the elements each set has in common (AND).
2. All of the elements total of each set (OR).
3. All of the elements unique to each set. (XOR).
Is there an easy, pre-existing way to do that?
**Edit:** That's the wrong termi... | Assuming 2 Set objects a and b
AND(intersection of two sets)
```
a.retainAll(b);
```
OR(union of two sets)
```
a.addAll(b);
```
XOR
either roll your own loop:
```
foreach item
if(a.contains(item) and !b.contains(item) || (!a.contains(item) and b.contains(item)))
c.add(item)
```
or do this:
```
c.addAll(a);
c... | You can use the [Google-Collections Sets class](https://github.com/google/guava/blob/master/guava/src/com/google/common/collect/Sets.java) which has the methods intersection() union() and symmetricDifference().
```
Sets.intersection(set1, set2);
Sets.union(set1, set2);
SetView view = Sets.intersection(Sets.union(set1... | Java: Is there an easy, quick way to AND, OR, or XOR together sets? | [
"",
"java",
"union",
"set",
"intersection",
""
] |
I have a .NET assembly which I am accessing from VBScript (classic ASP) via COM interop. One class has an indexer (a.k.a. default property) which I got working from VBScript by adding the following attribute to the indexer: `[DispId(0)]`. It works in most cases, but not when accessing the class as a member of another o... | I stumbled upon this exact problem a few days ago. I couldn't find a reasonable explanation as to why it doesn't work.
After spending long hours trying different workarounds, I think I finally found something that seems to work, and is not so dirty. What I did is implement the accessor to the collection in the contain... | Results of my investigation on this subject:
The problem is relative to IDispatch implementation the common language runtime uses when exposing dual interfaces and dispinterfaces to COM.
Scripting language like VBScript (ASP) use OLE Automation IDispatch implementation when accessing to COM Object.
Despite it seems ... | Why is the indexer on my .NET component not always accessible from VBScript? | [
"",
"c#",
".net",
"vbscript",
"com-interop",
""
] |
I know downcasting like this won't work. I need a method that WILL work. Here's my problem: I've got several different derived classes all from a base class. My first try was to make an array of base class. The program has to select (more or less at random) different derived classes. I had tried casting from a base cla... | Not sure what you mean. Sounds like you store the objects by value, and you you have an array of `Base`. That won't work, because as soon as you assign a Derived, that object will be converted to a Base, and the Derived part of the object is sliced away. But i think you want to have a array of pointers to base:
```
Ba... | Casting from a base class to a derived class is a bad code smell in most circumstances.
**Polymorphism**, through the use of virtual methods, is a better approach.
The calling code should invoke a method using the base class pointer, allowing it to be dispatched to the appropriate implementation in the derived class.... | a better way than casting from a base class to derived class | [
"",
"c++",
"class-design",
""
] |
I'm working on a document application and part of this application I've to add support to read the keyboard pressed events and replace the pre-defined characters set if that keyboard entry is match with the pre-defind short form/word.The actual application has implemented in C++.
Please provide me your thoughts on how... | Standard C++ doesn't support keypress events, so you'll have to look at either an OS function, or a framework function. Portable C++ frameworks like wxWidgets or Qt support keypress events on Windows, Mac and Linux. | Learn how to catch the keydown events using wxWidgets api, maybe here:
<http://docs.wxwidgets.org/stable/wx_eventhandlingoverview.html#eventhandlingoverview>
pay attention to [key events](http://docs.wxwidgets.org/stable/wx_wxkeyevent.html#wxkeyevent). Implement a switch in C++ to see what key combination was pressed, ... | Read keyboard characters to determine shortcuts | [
"",
"c++",
"text",
"keyboard-shortcuts",
"keyboard-events",
""
] |
Is it possible to determine if an ASP.NET page is a postback from javascript?
So basically a javascript equivalent of C# Page.IsPostBack.
Thanks. | I would just put a render tag in the javascript
```
var isPostBack = <%= Page.IsPostBack ? "true" : "false" %>;
```
Putting the "true" and "false" as strings should be done to eliminate any possible issues converting the type to a string as in C# true.ToString() is usually "True" which is an error in javascript. | Sure. Just use your server code to write out a javascript flag, if you really need this.
But I suspect you're barking up the wrong tree here. | Use javascript to determine if an ASP.NET page is a postback | [
"",
"asp.net",
"javascript",
""
] |
I have an `IDictionary<TKey,TValue>` implementation that internally holds n other `Dictionary<TKey, TValue>` and distributes that insertions by the HashCode of the key to the invidual sub-dictionaries. With 16 sub-dictionaries, the number of collisions is pretty low on a 4-core machine.
For parallel insertions, i lock... | For write-only load the Monitor is cheaper than ReaderWriterLockSlim, however, if you simulate read + write load where read is much greater than write, then ReaderWriterLockSlim should out perform Monitor. | I'm no guru, but my guess is that RWLS is more geared towards heavy contention (e.g., hundreds of threads) whereas `Monitor` is more attuned towards those one-off synchronization issues.
Personally I use a `TimerLock` class that uses the `Monitor.TryEnter` with a timeout parameter. | ReaderWriterLockSlim vs. Monitor | [
"",
"c#",
"multithreading",
"locking",
"readerwriterlock",
""
] |
I have always wondered if, in general, declaring a throw-away variable before a loop, as opposed to repeatedly inside the loop, makes any (performance) difference?
A *(quite pointless)* example in Java:
**a)** declaration before loop:
```
double intermediateResult;
for(int i=0; i < 1000; i++){
intermediateResult ... | Which is better, **a** or **b**?
From a performance perspective, you'd have to measure it. (And in my opinion, if you can measure a difference, the compiler isn't very good).
From a maintenance perspective, **b** is better. Declare and initialize variables in the same place, in the narrowest scope possible. Don't lea... | Well I ran your A and B examples 20 times each, looping 100 million times.(JVM - 1.5.0)
A: average execution time: .074 sec
B: average execution time : .067 sec
To my surprise B was slightly faster.
As fast as computers are now its hard to say if you could accurately measure this.
I would code it the A way as well b... | Difference between declaring variables before or in loop? | [
"",
"java",
"performance",
"loops",
"variables",
"initialization",
""
] |
this is what I did. is there a better way in python?
```
for k in a_list:
if kvMap.has_key(k):
kvMap[k]=kvMap[k]+1
else:
kvMap[k]=1
```
Thanks | Use defaultdict
```
from collections import defaultdict
kvmap= defaultdict(int)
for k in a_list:
kvmap[k] += 1
``` | Single element:
```
a_list.count(k)
```
All elements:
```
counts = dict((k, a_list.count(k)) for k in set(a_list))
``` | what's the pythonic way to count the occurrence of an element in a list? | [
"",
"python",
""
] |
I'm writing a piece of code that requires the `DOM` of a website to remain frozen while arbitrary JavaScript runs. Attributes changing is fine but I can't have anything changing the original tag structure of the page!
I know in JavaScript there are a base number of functions that can modify the `DOM`:
```
appendChild... | Have you tried **HTMLElement**.prototype.appendChild = function(){} to overwrite DOM methods at a higher level? | While this is really hackish, the only way to maintain the current DOM structure is to store a "snapshot" of the DOM and check it periodically.
```
//place in anonymous function to prevent global access
(function() {
//storing the whole DOM as objects would be ideal, but too memory intensive, so a string will have t... | Freezing the DOM to JavaScript: Overwriting DOM modification functions as no-ops | [
"",
"javascript",
"dom",
"sandbox",
""
] |
If a user types in a long line without any spaces or white space, it will break formating by going wider than the current element. Something like:
> HAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHAHA..................................................................................................................................... | I haven't personally used it, but [Hyphenator](http://code.google.com/p/hyphenator/) looks promising.
Also see related (possibly duplicate) questions:
* [word wrap in css / js](https://stackoverflow.com/questions/322929/word-wrap-in-css-js)
* [Who has solved the long-word-breaks-my-div problem? (hint: not stackoverfl... | in CSS3:
```
word-wrap:break-word
``` | How to wrap long lines without spaces in HTML? | [
"",
"php",
"html",
"css",
"word-wrap",
""
] |
Here's a question for those of you with experience in larger projects and API/framework design.
I am working on a framework that will be used by many other projects in the future, so I want to make it nice and extensible, but at the same time it needs to be simple and easy to understand.
I know that a lot of people c... | Your class includes data members; methods that perform basic internal operations on those data members where the functionality should never change should always be private. So methods that do basic operations with your data members such as initialization and allocation should be private. Otherwise, you run the risk of ... | When you mark a method with the word virtual, you're allowing the users to change the way that piece of logic is executed. For many purposes, that is exactly what you want. I believe you already know that.
However, types should be designed for this sort of extension. You have to actively pick out the methods, where it... | Can you ever have too many "protected virtual" methods? | [
"",
"c#",
".net",
"virtual",
"protected",
""
] |
I ran across this case of `UnboundLocalError` recently, which seems strange:
```
import pprint
def main():
if 'pprint' in globals(): print 'pprint is in globals()'
pprint.pprint('Spam')
from pprint import pprint
pprint('Eggs')
if __name__ == '__main__': main()
```
Which produces:
```
pprint is in g... | Looks like Python sees the `from pprint import pprint` line and marks `pprint` as a name local to `main()` *before* executing any code. Since Python thinks pprint ought to be a local variable, referencing it with `pprint.pprint()` before "assigning" it with the `from..import` statement, it throws that error.
That's as... | Where's the surprise? *Any* variable global to a scope that you reassign within that scope is marked local to that scope by the compiler.
If imports would be handled differently, *that* would be surprising imho.
It may make a case for not naming modules after symbols used therein, or vice versa, though. | Python globals, locals, and UnboundLocalError | [
"",
"python",
"binding",
"scope",
"identifier",
""
] |
I have an assortment of database objects (tables, functions, views, stored procedures) each scripted into its own file (constraints are in the same file as the table they alter) that I'd like to be able execute in an arbitrary order. Is this possible in SQL Server 2005?
Some objects as an example:
Table A (reference... | In my experience the most problematic issue is with views, which can reference recursively. I once wrote a utility to iterate through the scripts until the errors were all resolved. Which only works when you're loading everything. Order was important - I think I did UDTs, tables, FKs, views (iteratively), SPs and UDFs ... | If you script the foreign keys into separate files, you can get rid of table-table dependencies, if you run the FK script after creating all tables.
As far as I'm aware, functions and procedures check for object existence only in JOIN clauses.
The only difficulty I found was views depending on views, as a view defini... | Can I disable identifier checking in SQL Server 2005? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"version-control",
""
] |
We have a fairly large group of Maven2 projects, with a root POM file listing 10+ modules and a lot of properties used by the modules (dependency version numbers, plugin configuration, common dependencies, etc). Some of the modules are, like the root project, parents to other sets of modules.
To clarify, the root proj... | I tried this again, with Galileo and the latest version of m2eclipse. It is now possible to import Maven projects directly (without mvn eclipse:eclipse), and it turns out that the root POM is also imported as a project, which is excactly what I wanted. | Well. Lots of people do this by making the parent POM a sibling project, and having a simple reactor POM in the root. However this can cause problems with website generation and the release plugin, as neither supports this mode as fully as one might like.
A big problem we often have is that people try to check out the... | With multi-module Maven projects, is it possible to make my root (pom-packaged) project available in Eclipse? | [
"",
"java",
"eclipse",
"maven-2",
"pom.xml",
""
] |
For example:
```
using System;
using System.Web;
using System.Collections;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Security;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
using S... | **In general** all they do is add clutter.
However, they can *in some specific circumstances* cause problems with duplicate names in scope, or duplicate extension methods. For example, if there are classes `Foo.SomeType` and `Bar.SomeType`, and you have `using Foo;` and `using Bar;`, then references to `SomeType` will... | In general I like to remove unused using statements as they clutter up the code.
[ReSharper](https://www.jetbrains.com/resharper/) grays out unused using statements.
[](https://web.archiv... | Does it matter if I include more references and namespaces in a class | [
"",
"c#",
""
] |
it's a really weird thing - i have a website that works perfectly in maxthon (internet explorer based browser). i started it in opera and found out that the data put in the Session dictionary on one site, is not available on the other... i mean i have Welcome.aspx, where when you click next the following code is execut... | If your write the session on the first hit then you should do
```
Response.Redirect("nextpage.asp", false);
```
Otherwise it wont write the whole responsestream and the cookie might not have been written. You can instead choose to have cookiless sessions. But then your open to session hijacking. | ASP.NET session is stored by a key that is saved as a cookie in the browser. Check Opera to see if it is accepting cookies - it will need to in order for ASP.NET session to work properly. | asp.net: data put in session is available while working in internet explorer but not in opera | [
"",
"c#",
"asp.net",
"session",
"opera",
""
] |
I'm building a site that's sort of a cross between StackOverflow and Digg (only a different genre). Typically in the past I would have just built it using ASP.Net web forms. However I want to use this project as a way to learn new technologies. I'm using ASP.Net Mvc which is really great, but I need to learn/use some k... | You should definitely start with the basics of Javascript. Start with things like printing "Hello World" to the page. Move on to basic language features like variables, loops, conditionals, and functions. I recommend the [W3Schools Introduction to Javascript](http://www.w3schools.com/jS/js_intro.asp "W3Schools Introduc... | Start by learning the basics of Javascript. It's important you know how to use it's internals before you dive into deeper abstractions. Mozila has [a fantastic resource](http://developer.mozilla.org/en/JavaScript) on Javascript, including an [overview guide](http://developer.mozilla.org/en/Core_JavaScript_1.5_Guide).
... | Where do I begin learning all the different JavaScript technologies/libraries? | [
"",
"javascript",
""
] |
What is a good way of parsing command line arguments in Java? | Check these out:
* <http://commons.apache.org/cli/>
* <http://www.martiansoftware.com/jsap/>
Or roll your own:
* <http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html>
---
**For instance,** this is how you use [`commons-cli`](https://mvnrepository.com/artifact/commons-cli/commons-cli/1.3.1) to parse 2 s... | Take a look at the more recent [JCommander](http://jcommander.org/).
I created it. I’m happy to receive questions or feature requests. | How do I parse command line arguments in Java? | [
"",
"java",
"command-line",
"command-line-arguments",
""
] |
To summarize, as we all know,
a) Silverlight is expected to be hosted by a browser, and runs in an isolated sandbox so that there won’t be any security issues
1. Silverlight don’t have direct access
to the file system, other than the
isolated storage area
2. There is no
direct way to open common dialog
bo... | Two ways I can think about is,
**Create a "Shell"**
Host the HTML Page with Silverlight, in a Winforms desktop application, using a web browser control, and communicate to and fro using HTML DOM. Then I can request the hosted shell to do things like printing. [See details here](http://amazedsaint.blogspot.com/2008/12... | Is a full WPF application not an option for your situation?
As you probably know Silverlight uses a subset of WPF so you may be able to change your application relatively easy.
A wpf app would be easier than having a web server etc bundled within your application.
You wont in the foreseeable future be able to have a... | Thoughts about using Silverlight In Desktop Apps? | [
"",
"c#",
".net",
"silverlight",
"silverlight-2.0",
""
] |
Is there a collation type which is officially recommended by MySQL, for a general website where you aren't 100% sure of what will be entered? I understand that all the encodings should be the same, such as MySQL, Apache, the HTML and anything inside PHP.
In the past I have set PHP to output in "UTF-8", but which colla... | The main difference is sorting accuracy (when comparing characters in the language) and performance. The only special one is utf8\_bin which is for comparing characters in binary format.
`utf8_general_ci` is somewhat faster than `utf8_unicode_ci`, but less accurate (for sorting). The *specific language utf8 encoding* ... | Actually, you probably want to use `utf8_unicode_ci` or `utf8_general_ci`.
* `utf8_general_ci` sorts by stripping away all accents and sorting as if it were ASCII
* `utf8_unicode_ci` uses the Unicode sort order, so it sorts correctly in more languages
However, if you are only using this to store English text, these s... | What is the best collation to use for MySQL with PHP? | [
"",
"php",
"mysql",
"encoding",
"collation",
""
] |
I'm making a simple remove link with an onClick event that brings up a confirm dialog. I want to confirm that the user wants to delete an entry. However, it seems that when Cancel is clicked in the dialog, the default action (i.e. the href link) is still taking place, so the entry still gets deleted. Not sure what I'm ... | There's a typo in your code (the tag **a** is closed too early).
You can either use:
```
<a href="whatever" onclick="return confirm('are you sure?')"><img ...></a>
```
note the **return (confirm)**: the value returned by scripts in intrinsic evens decides whether the default browser action is run or not; in case you ... | Well, I used to have the same problem and the problem got solved by adding the word "**return**" before confirm:
```
onclick="return confirm('Delete entry?')"
```
I wish this could be heplful for you..
Good Luck! | Simple JavaScript problem: onClick confirm not preventing default action | [
"",
"javascript",
"html",
""
] |
Does anyone know a good .NET dictionary API? I'm not interested in meanings, rather I need to be able to query words in a number of different ways - return words of x length, return partial matches and so on... | Grab the flat text file from an open source spellchecker like ASpell (<http://aspell.net/>) and load it into a List or whatever structure you like.
for example,
```
List<string> words = System.IO.File.ReadAllText("MyWords.txt").Split(new string[]{Environment.NewLine}).ToList();
// C# 3.0 (LINQ) example:
// get ... | You might want to look for a [Trie](http://en.wikipedia.org/wiki/Trie) implementation. That will certainly help with "words starting with XYZ" as well as exact matches. You may well want to have all of your data in multiple data structures, each one tuned for the particular task - e.g. one for anagrams, one for "by len... | Dictionary API (lexical) | [
"",
"c#",
".net",
"api",
""
] |
I am having some difficulty accessing the value of the selected radio button in a radiogroup. I've attempted a number of different approaches based upon discussion in other posts on the forum and around the web. Unfortunately haven't been lucky (or skilled) enough to get it working. Based on the following FormPanel con... | This is something of a wild guess, but how about this:
```
myForm2.getForm().getValues()['id-1'];
``` | The method `getValue()` on the radio group itself will return the object that is checked, if any, otherwise, it returns undefined.
(by the way I set value instead of inputValue for my boxes, although I don't think it makes much of a difference, maybe it does on the last "getValue"), I'm using extjs 3.0, and my radiogr... | Ext RadioGroup - How to Access the value of selected radio button? | [
"",
"javascript",
"extjs",
""
] |
Parameterized Queries in .Net always look like this in the examples:
```
SqlCommand comm = new SqlCommand(@"
SELECT *
FROM Products
WHERE Category_ID = @categoryid
",
conn);
comm.Parameters.Add("@categoryid", SqlDbType.Int);
comm.Parameters["@categoryid"].Value = CategoryID;
```
But I'm running into... | Let's say that you have your category ids in an integer array and Name is a string. The trick is to create the command text to allow you to enter all of your category ids as individual parameters and construct the fuzzy match for name. To do the former, we use a loop to construct a sequence of parameter names @p0 throu... | You need "%" in value of sql parameter.
```
SqlCommand comm = new SqlCommand("SELECT * FROM Products WHERE Category_ID IN (@categoryid1, @categoryid2) OR name LIKE @name", conn);
comm.Parameters.Add("@categoryid1", SqlDbType.Int);
comm.Parameters["@categoryid1"].Value = CategoryID[0];
comm.Parameters.Add("@categoryid2... | Parameterized Queries with LIKE and IN conditions | [
"",
".net",
"sql",
"parameters",
"sql-injection",
"parameterized",
""
] |
How the variables can be transferred between the Winforms? Example customer id
Thanks | You must declare a public property in the form you wish to pass to. Then, after instantiating your new form, it's a simple assignment:
C#: `MyOtherInstantiatedForm.CustomerID = CurrentCustomerID;`
Do you need to pass around CustomerID to several forms? How about other customer information? If you provide more informa... | The most important thing to note here is that a Form is nothing more than a C# class. If you think about a Form in these terms, the answer will probably jump out, by itself.
Essentially, there are two options that you have. The first is to expose a property on the Form, for which you wish to pass data to. This is a de... | Windows application | [
"",
"c#",
"vb.net",
"winforms",
""
] |
How accurate is **System.Diagnostics.Stopwatch**? I am trying to do some metrics for different code paths and I need it to be exact. Should I be using stopwatch or is there another solution that is more accurate?
I have been told that sometimes stopwatch gives incorrect information. | Why don't you profile your code instead of focusing on microbenchmarks?
There are some good open source profilers, like:
* [NProf](http://code.google.com/p/nprof/)
* [Prof-It for C#](http://dotnet.jku.at/projects/Prof-It/)
* [NProfiler](http://chimpswithkeyboards.com/projects/nprofiler/)
* [ProfileSharp](http://www.s... | I've just written an article that explains how a test setup must be done to get an high accuracy (better than 0.1 ms) out of the stopwatch. I *think* it should explain everything.
*[Performance Tests: Precise Run Time Measurements with System.Diagnostics.Stopwatch](http://www.codeproject.com/KB/testing/stopwatch-measu... | How accurate is System.Diagnostics.Stopwatch? | [
"",
"c#",
".net",
"performance",
"stopwatch",
""
] |
I have an application that I want to export high-resolution (or rather, high pixel density?) images for printing - for example, I want images that print at 250 dots per inch (DPI), instead of the default, which I understand to be 72 DPI.
I'm using a BufferedImage with a Graphics2D object to draw the image, then ImageI... | Kurt's answer showed the way, still it took me quite some time to get it run, so here is the code that sets DPI when saving a PNG. There is a lot to do to get the proper writers and such...
```
private BufferedImage gridImage;
...
private void saveGridImage(File output) throws IOException {
output.delete();
... | # Seting up TIFF DPI
If you want to set dpi for TIFF, try to do that by next steps:
```
private static IIOMetadata createMetadata(ImageWriter writer, ImageWriteParam writerParams, int resolution) throws
IIOInva... | How to set DPI information in an image? | [
"",
"java",
"image",
""
] |
I wonder if it is a good practice to use JUnit's @Ignore. And how people are using it?
I came up with the following use case: Let's say I am developing a class and writing a JUnit test for it, which doesn't pass, because I'm not quite done with the class. Is it a good practice to mark it with @Ignore?
I'm a little co... | Thats pretty much fine, I suppose.
The [docs](https://github.com/junit-team/junit/wiki/Ignoring-tests) says,
> Test runners will report the number of ignored tests, along with the number of tests
> that ran and the number of tests that failed.
Hence, it means even if you forget to remove that afterwards, you should ... | I routinely use @Ignore for tests which fail because of a known bug. Once the bug is acknowledged and logged in the bug databases, the test failure serves no purpose, since the bug is already known.
Still it makes sense to keep the test code, because it will be useful again once the bug is fixed. So I mark it to be ig... | JUnit's @Ignore | [
"",
"java",
"unit-testing",
"testing",
""
] |
Is there a way to undefine the += on strings and wstrings for chars and wchar\_t?
Basically I want to avoid bugs like the following:
```
int age = 27;
std::wstring str = std::wstring(L"User's age is: ");
str += age;
std::string str2 = std::string("User's age is: ");
str2 += age;
```
The above code will add the asc... | **You cannot deactivate a specific function** of a class (here std::basic\_string) as it is it's interface that clearly (and officially) allow that manipulation. Trying to overload the operator will only mess things up.
Now, **you can "wrap" std::basic\_string in another class**, using private inheritance or compositi... | Most source control systems allow you to run sanity checks against your code during checkin. So you could set up a test the performs the validation and refuses the checkin on failure:
Example:
Test Script:
```
#!/bin/tcsh
# Pass the file to test as the first argument.
echo "#include <string>\
void operator+=(std::s... | How to avoid a common bug in a large codebase? | [
"",
"c++",
"string",
""
] |
Does such a thing exist for [YAML](http://en.wikipedia.org/wiki/Yaml) (aka [YAML](http://yaml.org))?
If this existed at one time, it must have been obliterated because the latest search turned up nada. It looks like there are plenty of implementations that **dump** from Javascript to YAML output only, but having troub... | Possibly newer version of js-yaml here:
<http://github.com/visionmedia/js-yaml> | Was just looking for the same, here's a basic [Javascript-based YAML parser](http://refactormycode.com/codes/1045-js-yaml-parser) written by [Tj Holowaychuk](http://refactormycode.com/users/634) over at [refactormycode.com](http://refactormycode.com/). I'm duplicating it here to ensure it isn't lost, appears the JsYaml... | Pure Javascript YAML library that supports both dump and load? | [
"",
"javascript",
"serialization",
"markup",
"yaml",
"parsing",
""
] |
I would like to map a many-to-many in Hibernate using a link table. I have two classes, Parent and Child class, for example:
```
public class Parent{
private List<Child> _children;
//...getters and setters
}
```
I use a link table (link\_table) with three columns `link_id`, `parent_id`, and `child_id`. The database... | I don't think that it is possible (or necessary) to add a link\_id primary key to the join table. The join table will usually consist of the primary keys of the two participating tables.
Using XML you will need syntax like this:
```
<class name="Parent">
....
<list name="children" table="link_table">
<ke... | I do this using annotations, specifically @ManyToMany and @JoinTable:
[Hibernate Docs:](http://www.hibernate.org/hib_docs/annotations/reference/en/html/entity.html#eentity-mapping-association-collection-manytomany)
```
@Entity
public class Employer implements Serializable {
@ManyToMany(
targetEntity=org.h... | How to map many-to-many List in Hibernate with a Link Table | [
"",
"java",
"hibernate",
"mapping",
""
] |
We have a site that needs to (as part of our process) generate a document (e.g. Word docx document) that is derived from data within our application merged with a template document. This document can be edited at run time by the user after it is generated. We know we are looking at a CMS like system (since the users wi... | I am working on a similar problem -- generating word documents from information stored in a SharePoint site. The real magic here relies on using Content Controls in office 2007 - as the new version of the Office suite is based on Office Open XML, generating documents from data is almost trivial.
Enabling the documents... | [Infopath](http://msdn.microsoft.com/en-us/library/ms573938.aspx) is the forms technology that Sharepoint people are going to recommend to you. Most Infopath forms features require a full MOSS installation and the associated licensing fees. I think you can acheive what you want here with just WSS however.
If DOCX file... | Sharepoint as template application | [
"",
"c#",
"sharepoint",
"sharepoint-2007",
""
] |
Trying to add an onclick handler to my tabs, and can't seem to get the DOM selection right. Can you guys help?
```
<div id="tabstrip">
<ul>
<li id="a" class="selected"><a href="#">A</a></li>
<li id="b"><a href="#">B</a></li>
<li id="b"><a href="#">C</a></li>
</ul>
</div>
function initTab... | Seems like your closure is wrong.
Try
```
as[j].onclick = function(items, i)
{
return function()
{
changeTab(items[i].id);
return false;
};
}(items, i);
```
If it works then the question is a dupe of [jQuery Closures, Loops and Events](https://stackoverflow.com/questions/359467/jquery-clos... | I agree to RoBorg and suggest reading about JavaScript scopes. It will explain a lot. | Trouble adding onclick handler to hyperlink tag inside listitem | [
"",
"javascript",
"onclick",
"handler",
""
] |
I'm building a site where users can track their collection of figures for Dungeons & Dragons (www.ddmdb.com). The models/relationships involved in this funcitonality are the following:
**User:**
* id
* login (username)
* *a bunch of other fields*
**Miniature:**
* id
* name
* number (# in the set, not count)
* relea... | Using fd's suggestion and information found at <http://www.ruby-forum.com/topic/52385>, I created the following method:
```
def miniature_count(miniature_id)
if @counts.nil?
@counts = Hash.new
ownerships.collect{|o| @counts[o.miniature_id] = o.have_count }
end
count = @counts[miniature_id] || 0
end
```
... | The first thing I would say is that the User model should own the code that works out how many of a given miniature the user owns, since it seems like "business logic" rather than view formatting.
My suggestion would be to add a method to your User model:
```
def owns(miniature_id)
o = ownerships.detect { |o| o.min... | How can I make this Ruby on Rails page more efficient? | [
"",
"sql",
"ruby-on-rails",
"activerecord",
"performance",
""
] |
Given a function:
```
function x(arg) { return 30; }
```
You can call it two ways:
```
result = x(4);
result = new x(4);
```
The first returns 30, the second returns an object.
How can you detect which way the function was called **inside the function itself**?
Whatever your solution is, it must work with the fol... | **NOTE: This is now possible in ES2015 and later. See [Daniel Weiner's answer](https://stackoverflow.com/a/31060154/96100).**
I don't think what you want is possible [prior to ES2015]. There simply isn't enough information available within the function to make a reliable inference.
Looking at the ECMAScript 3rd editi... | ### As of ECMAScript 6, this is possible with [`new.target`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new.target)
`new.target` will be set as `true` if the function is called with `new` (or with `Reflect.construct`, which acts like `new`), otherwise it's `undefined`.
```
function Fo... | How to detect if a function is called as constructor? | [
"",
"javascript",
"constructor",
""
] |
I have an application that has several objects (about 50 so far, but growing). There is only one instance of each of these objects in the app and these instances get shared among components.
What I've done is derive all of the objects from a base BrokeredObject class:
```
class BrokeredObject
{
virtual int GetInter... | My use-case tended to get a little more complex - I needed the ability to do a little bit of object initialization and I needed to be able to load objects from different DLLs based on configuration (e.g. simulated versus actual for hardware). It started looking like COM and ATL was where I was headed, but I didn't want... | Yes, there is a way. A pretty simple even in C++ to what that C# code does (without checking for inheritance though):
```
template<typename T>
BrokeredObject * GetOrCreateObject() {
return new T();
}
```
This will work and do the same as the C# code. It is also type-safe: If the type you pass is not inherited from ... | Looking for a better C++ class factory | [
"",
"c++",
"design-patterns",
""
] |
I can create a literal long by appending an L to the value; why can't I create a literal short or byte in some similar way? Why do I need to use an int literal with a cast?
And if the answer is "Because there was no short literal in C", then why are there no short literals in C?
This doesn't actually affect my life i... | In C, `int` at least was meant to have the "natural" word size of the CPU and `long` was probably meant to be the "larger natural" word size (not sure in that last part, but it would also explain why `int` and `long` have the same size on x86).
Now, my guess is: for `int` and `long`, there's a natural representation t... | I suspect it's a case of "don't add anything to the language unless it really adds value" - and it was seen as adding sufficiently little value to not be worth it. As you've said, it's easy to get round, and frankly it's rarely necessary anyway (only for disambiguation).
The same is true in C#, and I've never particul... | Why are there no byte or short literals in Java? | [
"",
"java",
"primitive",
""
] |
I'm trying to enforce integrity on a table in a way which I do not think a Constraint can...
```
CREATE TABLE myData
(
id INTEGER IDENTITY(1,1) NOT NULL,
fk_item_id INTEGER NOT NULL,
valid_from DATETIME NOT NULL,
invlaid_from DATETIME NOT NULL
)... | You can't delete directly from inserted (updates to the logical tables raise an error) but you can join back to the source table as seen below
```
create table triggertest (id int null, val varchar(20))
Go
create trigger after on [dbo].triggertest
for Update
as
Begin
delete tt from triggertest tt inner join
... | Don't delete the records from the inserted table... that's silent failure. The road to hell is paved in Partial Commits.
You need to [RAISERROR](http://msdn.microsoft.com/en-us/library/ms178592.aspx), which is essentially what a [constraint](http://msdn.microsoft.com/en-us/library/ms188066.aspx) would do. | Using Triggers To Enforce Constraints | [
"",
"sql",
"sql-server",
"sql-server-2005",
"triggers",
"constraints",
""
] |
I am creating an HTML form with some radio button options. I'd like to have one option as "Other - please specify" and allow the user to type something in.
Two questions:
1) How can I make a "hybrid" input type of `radio/text`?
2) On the PHP back end, if the input has the same `name` attribute as the radio inputs, w... | #1: To the "other:" radio field, add a `<input type="text" ...>` with style display:none and only display it when user selects the "other:" radio field.
However, I'm not entirely sure if #2 would work. You'd get `rboption=other` from the radio button AND `rboption=some%20text` from the text field. One will usually ove... | Why not just add a different *name* attribute to the input and only validate it if the *other* radio button has been selected? | How can I make a radio button for "Other - please specify?" | [
"",
"php",
"html",
"forms",
"radio-button",
""
] |
When I click on a row in my GridView, I want to go to a other page with the ID I get from the database.
In my RowCreated event I have the following line:
```
e.Row.Attributes.Add(
"onClick",
ClientScript.GetPostBackClientHyperlink(
this.grdSearchResults, "Select$" + e.Row.RowIndex));
```
To preve... | I have the solution.
This is what i have done:
```
if(e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes["onClick"] = "location.href='view.aspx?id=" + DataBinder.Eval(e.Row.DataItem, "id") + "'";
}
```
I have putted the preceding code in the RowDataBound event. | Martijn,
Here's another example with some nifty row highlighting and a href style cursor:
```
protected void gvSearch_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onmouseover", "this.style.backgroundColor='#ceedfc'");
e.Row.... | c# gridview row click | [
"",
"c#",
"gridview",
"click",
""
] |
Suppose I have a `std::vector` (let's call it `myVec`) of size `N`. What's the simplest way to construct a new vector consisting of a copy of elements X through Y, where 0 <= X <= Y <= N-1? For example, `myVec [100000]` through `myVec [100999]` in a vector of size `150000`.
If this cannot be done efficiently with a ve... | ```
vector<T>::const_iterator first = myVec.begin() + 100000;
vector<T>::const_iterator last = myVec.begin() + 101000;
vector<T> newVec(first, last);
```
It's an O(N) operation to construct the new vector, but there isn't really a better way. | Just use the vector constructor.
```
std::vector<int> data();
// Load Z elements into data so that Z > Y > X
std::vector<int> sub(&data[100000],&data[101000]);
``` | Best way to extract a subvector from a vector? | [
"",
"c++",
"stl",
"vector",
"range",
""
] |
I have the following table and data in SQL Server 2005:
```
create table LogEntries (
ID int identity,
LogEntry varchar(100)
)
insert into LogEntries values ('beans')
insert into LogEntries values ('beans')
insert into LogEntries values ('beans')
insert into LogEntries values ('cabbage')
insert into LogEntries va... | This is a set-based solution for the problem. The performance will probably suck, but it works :)
```
CREATE TABLE #LogEntries (
ID INT IDENTITY,
LogEntry VARCHAR(100)
)
INSERT INTO #LogEntries VALUES ('beans')
INSERT INTO #LogEntries VALUES ('beans')
INSERT INTO #LogEntries VALUES ('beans')
INSERT INTO #LogEntri... | I think this will do it... didn't check too thoroughly though
```
select
COUNT(*),subq.LogEntry
from
(
select
ROW_NUMBER() OVER(ORDER BY id)-ROW_NUMBER() OVER(PARTITION BY logentry ORDER BY id) as t,*
from
LogEntries
) subq
group by
subq.t,subq.LogEntry
order by
MIN(subq.ID... | Group repeated rows in TSQL | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
""
] |
I want in a good performance way (I hope) replace a named parameter in my string to a named parameter from code, example, my string:
```
"Hi {name}, do you like milk?"
```
How could I replace the {name} by code, Regular expressions? To expensive? Which way do you recommend?
How do they in example NHibernates HQL to ... | Have you confirmed that regular expressions are too expensive?
The cost of regular expressions is greatly exaggerated. For such a simple pattern performance will be quite good, probably only slightly less good than direct search-and-replace, in fact. Also, have you experimented with the `Compiled` flag when constructi... | Regex is certainly a viable option, especially with a `MatchEvaluator`:
```
Regex re = new Regex(@"\{(\w*?)\}", RegexOptions.Compiled); // store this...
string input = "Hi {name}, do you like {food}?";
Dictionary<string, string> vals = new Dictionary<string, string>();
vals.Add("name", "Fred");
v... | C# Named parameters to a string that replace to the parameter values | [
"",
"c#",
"regex",
"performance",
"string",
"named-parameters",
""
] |
I have a site where users can post stuff (as in forums, comments, etc) using a customised implementation of TinyMCE. A lot of them like to copy & paste from Word, which means their input often comes with a plethora of associated MS inline formatting.
I can't just get rid of `<span whatever>` as TinyMCE relies on the s... | [HTML Purifier](http://htmlpurifier.org/) will create standards compliant markup and filter out many possible attacks (such as XSS).
For faster cleanups that don't require XSS filtering, I use the PECL extension [Tidy](http://www.php.net/tidy) which is a binding for the [Tidy HTML](http://www.w3.org/People/Raggett/tid... | In my case, this worked just fine:
```
$text = strip_tags($text, '<p><a><em><span>');
```
Rather than trying to pull out stuff you don't want such as embedded word xml, you can just specify you're allowed tags. | PHP to clean-up pasted Microsoft input | [
"",
"php",
"ms-word",
"tinymce",
"user-input",
""
] |
At my current job I've been working on making web apps with Java, Tapestry, Hibernate, MSSQL, and Tomcat.
I've got an idea for a little web game I'd like to write. I'd like to know what the SO community would use for something like this.
Should I stick to what I know? I was thinking it would be very beneficial for me... | My recommendation would be to see what you could do with a combination of Google App Engine, Django, and JavaFX.
In doing so, you'd learn some new technologies (App Engine) and languages (Python for Django, JavaFX) while taking advantage of what you already know about web apps and Java. | If its a personal project then take this as an opportunity to learn something new. | What would you use to build a web app? | [
"",
"java",
""
] |
So, I have an API that I need to implement in to an existing framework. This API manages interactions with an external server. I've been charged with coming up with a way to create an easily repeatable "pattern," so that if people are working on new projects in the given framework they have a simple solution for integr... | If your boss is hostile to inheritance, try aggregation. (*Has-a* relationships rather than inheritance's *is-a* relationship.) Assuming you interface with the API in question via an object, maybe you can just keep that object in a property of your framework 'main' class, so you'd interact with it like `main->whatevera... | Sounds to me like what your boss is having a problem with is the Framework part of this. There is an important distiction between Framework and API, in order to code to a framework you must have a good understanding of it and how it fits within your overall development, much more of a wholeistic view, adding to framewo... | Avoiding Inheritance Madness | [
"",
"c++",
"design-patterns",
""
] |
I have a std::vector containing a handful of numbers, which are not in any particular order, and may or may not have gaps between the numbers - for example, I may have { 1,2,3, 6 } or { 2,8,4,6 } or { 1, 9, 5, 2 }, etc.
I'd like a simple way to look at this vector and say 'give me the lowest number >= 1 which does *no... | The checked answer uses < for comparison. != is much simpler:
```
int find_gap(std::vector<int> vec) {
std::sort(vec.begin(), vec.end());
int next = 1;
for (std::vector<int>::iterator it = vec.begin(); it != vec.end(); ++it) {
if (*it != next) return next;
++next;
}
return next;
}
f... | The standard algorithm you are looking for is **[std::adjacent\_find](http://en.cppreference.com/w/cpp/algorithm/adjacent_find)**.
Here is a solution that also uses a lambda to make the predicate clean:
```
int first_gap( std::vector<int> vec )
{
// Handle the special case of an empty vector. Return 1.
if( vec.e... | Finding gaps in sequence of numbers | [
"",
"c++",
"stl",
""
] |
When using auto implemnted properies like
public string MyProperty { get; set; }
This is great until you come to naming conventions.
I use underscore for class level fields ie
string \_MyProperty;
so with auto implemented means that it is not obvious what the variable is and it scope.
If you get my meaning, any t... | PascalCasing tells you its class level AND public. (Look at this [article about naming conventions for .NET](http://www.irritatedvowel.com/Programming/Standards.aspx)) | you don't need the \_ at all when you use the automatic properties and a modern IDE (like visual studio). intellisense will work correctly if you use automatic properties and different visibilities. the compiler will also check it.
```
public string SomeString { private set; get; }
private string some2string;... | C# - Using auto implemented properties and naming conventions | [
"",
"c#",
""
] |
I am asking about that as I am going to develop a client side application using c# to display stock data and make some user-interaction, so give me links for best tutorials you read before | [Jeremy Miller's guide](http://codebetter.com/blogs/jeremy.miller/archive/2007/07/25/the-build-your-own-cab-series-table-of-contents.aspx) is an excellent starting place. It covers several important patterns including:
* [Model - View - Controller](http://codebetter.com/blogs/jeremy.miller/archive/2007/05/23/build-you... | To answer your question, the most common pattern appears to be generalized hacking in my experience, however if you want a nice pattern check out the [MVP (Model View Presenter)](http://www.codeplex.com/websf/Wiki/View.aspx?title=MVP_landing_page) pattern from Microsoft's Patterns and Practices group. Although it's an ... | What is the most common design patterns for any windows forms application? | [
"",
"c#",
"winforms",
"design-patterns",
""
] |
I have to pass some parameter from an action to another action,for example to keep trace of an event.
What is the best way to do that?
I would not use session parameters. Thanks | Assuming you are serverside within one action and wishing to invoke another action with some parameters.
You can use the s:action tag to invoke another action, possibly with additional/other parameters than the original action:
```
<s:action name="myAction" ignoreContextParams="true" executeResult="true">
... | ```
<td>
<s:url id="url" action="Logging">
<s:param name="m_userNameInAction"><s:property value="m_userNameInForm"/></s:param>
</s:url>
<s:a href="%{url}">English</s:a>
</td>
``` | Struts2 parameters between actions | [
"",
"java",
"jsp",
"struts2",
"parameters",
"action",
""
] |
I'm currently writing an implementation of a JDBC driver (*yes, you read that correctly*) in a TDD manner and while I have only finished class stubs at this point and only some minor functionality, it just occured to me that since `Statement` is a superclass for `PreparedStatement` which is a superclass for `CallableSt... | I would specifically never do alternative 1 (letting the test-class hierarchy be the same as the actual class hierarchy) if this means you will be running the same tests repeatedly for each test subclass. I am also generally sceptical of subclassing test classes other than the general utility base class.
I normally ma... | "test every single method individually for each implementation class"
In particular, failure to override a superclass method properly is a common bug. The author of the subclass makes assumptions about the superclass. The superclass changes, and the subclass is now broken. | Should I unit test methods which are inherited from super class? | [
"",
"java",
"unit-testing",
"tdd",
"junit",
""
] |
Netbeans tells me it's bad to access a static method from a non static method. Why is this bad?
"Accessing static method getInstance" is the warning:
```
import java.util.Calendar;
public class Clock
{
// Instance fields
private Calendar time;
/**
* Constructor. Starts the clock at the current opera... | You're probably accessing the static method from an instance instead of directly. Try using `Calendar.getInstance()` instead:
```
private String getSystemTime()
{
return Calendar.getInstance().get(Calendar.HOUR)+":"+
Calendar.getInstance().get(Calendar.MINUTE);
}
``` | What do you mean by "return a static method"? It's fine to call a static method from an instance method in my view - depending on the circumstances, of course. Could you post some code which Netbeans complains about?
One thing I *could* imagine is if you only use static methods from an instance method, without using a... | Why is accessing a static method from a non-static method bad? | [
"",
"java",
"oop",
"static",
"methods",
""
] |
Using the standard MVC set up in Zend Framework, I want to be able to display pages that have anchors throughout. Right now I'm just adding a meaningless parameter with the '#anchor' that I want inside the .phtml file.
```
<?= $this->url(array(
'controller'=>'my.controller',
'action'=>'my.action',
'anchor'... | one of possibilities is to override url helper, or to create a new one.
```
class My_View_Helper_Url extends Zend_View_Helper_Url
{
public function url(array $urlOptions = array(), $name = null, $reset = false, $encode = true)
{
if (isset($urlOptions['anchor']) && !empty($urlOptions['anchor']))
... | There are multiple ways you could go about implementing a [fragment id](http://www.w3.org/TR/REC-html40/intro/intro.html#fragment-uri) into your URLs. Below are some options, along with some pros and cons for each.
## Direct Add
You could simply add the `"#$fragment_id"` after your `url()` call. Inelegant, but simple... | How Can I Write Zend Framework URLs That Have Anchor Tags In The Body? | [
"",
"php",
"zend-framework",
"zend-framework-mvc",
""
] |
I recall hearing that the connection process in mysql was designed to be very fast compared to other RDBMSes, and that therefore using [a library that provides connection pooling](http://www.sqlalchemy.org/) (SQLAlchemy) won't actually help you that much if you enable the connection pool.
Does anyone have any experien... | There's no need to worry about residual state on a connection when using SQLA's connection pool, unless your application is changing connectionwide options like transaction isolation levels (which generally is not the case). SQLA's connection pool issues a connection.rollback() on the connection when its checked back i... | Even if the connection part of MySQL itself is pretty slick, presumably there's still a network connection involved (whether that's loopback or physical). If you're making a *lot* of requests, that could get significantly expensive. It will depend (as is so often the case) on exactly what your application does, of cour... | Mysql connection pooling question: is it worth it? | [
"",
"python",
"mysql",
"sqlalchemy",
"connection-pooling",
""
] |
This question is for the java language in particular. I understand that there is a static protion of memory set aside for all static code.
My question is how is this static memory filled? Is a static object put into static memory at import, or at first reference? Also, do the same garbage collection rules apply to sta... | Imports don't correlate with any instructions in compiled code. They establish aliases for use at compile time only.
There are some reflective methods that allow the class to be loaded but not yet initialized, but in most cases, you can assume that whenever a class is referenced, it has been initialized.
Static membe... | There is normally no such thing as "static" memory. Most vm's have the permanent generation of the heap (where classes get loaded), which is normally not garbage collected.
Static objects are allocated just like any other object. But, if they live for long they will be moved between the different generations in the ga... | Whats up with static memory in java? | [
"",
"java",
"memory-management",
"static",
""
] |
Does anyone know anywhere there's a wide collection of Python source code on the net with decent documentation? If so, can someone post it up here? | Perhaps the [Python Standard Library](http://docs.python.org/library/)? Or are you looking for something more specific? | I am not sure what you meant by "source code"? Source code of Python libraries or code examples and recipes?
Well the link to Python STL is great (@zenazn).
In addition to that if you are looking for specific issues and their solutions and recipes, I will suggest:
1. <http://code.activestate.com/recipes/langs/python... | Python source code collection | [
"",
"python",
""
] |
I am designing a helper method that does lazy loading of certain objects for me, calling it looks like this:
```
public override EDC2_ORM.Customer Customer {
get { return LazyLoader.Get<EDC2_ORM.Customer>(
CustomerId, _customerDao, ()=>base.Customer, (x)=>Customer = x); }
set { base.Customer = valu... | "base.Foo" for a virtual method will make a non-virtual call on the parent definition of the method "Foo". Starting with CLR 2.0, the CLR decided that a non-virtual call on a virtual method can be a potential security hole and restricted the scenarios in which in can be used. They limited it to making non-virtual calls... | I suspect the problem is that you're basically saying, "I don't want to use the most derived implementation of Customer - I want to use *this* particular one" - which you wouldn't be able to do normally. You're allowed to do it within a derived class, and for good reasons, but from other types you'd be violating encaps... | What is 'unverifiable code' and why is it bad? | [
"",
"c#",
""
] |
Coming from a C++ background, I've run into a snag with overloading based on a specific instance of a generic type. The following doesn't work since only once instance of the code for the `Foo<T>` class is ever generated, so inside the `Method`, the type of `this` is simply `Foo<T>`, not `Foo<A>` or `Foo<B>` as I'd hop... | This works for the static case. Dealing with instance functions would be a bit more complicated. This [post from Jon Skeet](http://msmvps.com/blogs/jon_skeet/archive/2008/08/09/making-reflection-fly-and-exploring-delegates.aspx) might provide a reasonable way to deal with instance methods.
```
class Program
{
stat... | I now have a genuinely complete piece of code which demonstrates the problem. Note to OP: please try compiling your code before posting it. There were a bunch of things I had to do to get this far. It's good to make it as easy as possible for other people to help you. I've also removed a bunch of extraneous bits. Other... | How can I overload a C# method by specific instances of a generic type | [
"",
"c#",
"generics",
"overloading",
""
] |
I want to fill a map with class name and method, a unique identifier and a pointer to the method.
```
typedef std::map<std::string, std::string, std::string, int> actions_type;
typedef actions_type::iterator actions_iterator;
actions_type actions;
actions.insert(make_pair(class_name, attribute_name, identifier, metho... | I wrote that stuff last hours, and added it to my collection of useful stuff. The most difficult thing is to cope with the factory function, if the types you want to create are not related in any way. I used a `boost::variant` for this. You have to give it a set of types you ever want to use. Then it will keep track wh... | Perhaps you're looking for [member function pointers](http://www.parashift.com/c++-faq-lite/pointers-to-members.html).
Basic usage:
```
class MyClass
{
public:
void function();
};
void (MyClass:*function_ptr)() = MyClass::function;
MyClass instance;
instance.*function_ptr;
```
As stated in the C++ FAQ... | What is the simplest way to create and call dynamically a class method in C++? | [
"",
"c++",
"model-view-controller",
"object",
""
] |
I want to move the form title, icon and close, and help buttons from left side to right side (change the layout).
I moved the form controls manually to keep background image but now I want to change the form title.
When I set rightToLeft property to yes and rightToLeftLayout to true in the form properties the backgro... | To further Blounty's answer, the MSDN specs clearly state that BackgroundImage, Opacity and others aren't supported when using RightToLeftLayout:
[<http://msdn.microsoft.com/en-us/library/system.windows.forms.form.righttoleftlayout(vs.80).aspx>](http://msdn.microsoft.com/en-us/library/system.windows.forms.form.rightto... | BackgroundImage, Opacity, TransparencyKey, and the painting events are not supported when RightToLeftLayout is set to yes. | RightToLeft property in Form in C# | [
"",
"c#",
"winforms",
"internationalization",
""
] |
Simple question: do I have to `delete` or `delete []` `c`? Does the language matter?
```
char c[] = "hello"
``` | In c++ that is not dynamic memory allocation. No `delete[]` will be needed.
Your example is basically a short-cut for this:
```
char c[6]={'h','e','l','l','o','\0'};
``` | The rule in C++ is that you use `delete[]` whenever you use `new[]`, and `delete` whenever you use `new`. If you don't use `new`, as in your example, you do not need to `delete` anything.
In your example, the six bytes for the `c` array are allocated on the stack, instead of on the heap, if declared within a function.... | Is this dynamic memory allocation? | [
"",
"c++",
"c",
"memory",
"memory-management",
"new-operator",
""
] |
How can we write an update sql statement that would update records and the 'set' value changes every time?
For example:
If we have records like this
```
SomeNumber SomeV CurCode WhatCodeShouldBe
200802754 432 B08 B09
200802754 432 B08 B09
200802754 432 B08 B09
200808388 714 64B C00
200804119 270 64B C00
```
I wish t... | ```
update a
set
3rdColumn = b.2ndColumn
from
tableA a
inner join tableB b
on a.linkToB = b.linkToA
```
That is based on [your new comments](https://stackoverflow.com/questions/317822/update-with-changing-set-value#317942) | i have got that data by forming some temptables and gathering information from different tables. :( updating this temp table wont be a help...I need to be able to carry the changes over to the original table. I'll try to give better example...
Table A:
200802754 432 B08
200802754 432 B08
200802754 432 B08
200808388 71... | Update with changing set value | [
"",
"sql",
"sql-update",
""
] |
Is there some equivalent of "friend" or "internal" in php? If not, is there any pattern to follow to achieve this behavior?
**Edit:**
Sorry, but standard Php isn't what I'm looking for. I'm looking for something along the lines of what ringmaster did.
I have classes which are doing C-style system calls on the back en... | PHP doesn't support any friend-like declarations. It's possible to simulate this using the PHP5 \_\_get and \_\_set methods and inspecting a backtrace for only the allowed friend classes, although the code to do it is kind of clumsy.
There's some [sample code](http://bugs.php.net/bug.php?id=34044) and discussion on th... | It is also possible to elevate privileges, aka leaking data selectively, using a handshake and closures in php >=5.3.3.
Basically, the interaction goes: class A has a public method which accepts a class B object, and calls B->grantAccess (or whatever your interface defines), passing it a closure. The closure `use($tha... | PHP equivalent of friend or internal | [
"",
"php",
"oop",
"friend",
""
] |
Title might be a bit confusing, so let me explain.
I have a website that has a side-panel, which contains information about the user, things the user can do, etc. When the user is not logged in, this side-panel becomes the area for logging in or registration.
The code for this is:
```
<?php
if($user->loggedIn)
{
?>
... | You could load the page with an AJAX request and then strip out the data other than the side panel, but what would be the point? Your best option would be to simply separate the side panel into its own file.
Oh, and that would also be considered the proper way of doing it, so you can edit the sidebar without editing t... | If i understand corectly what you neey, you may try this way:
```
$.ajax({
type: "GET",
url: "url", // replace 'url' with your url
cache: false,
success: function(data){
alert($(data).find('#sidebar').html());
}
});
```
Maybe will work with $.load() or $.get(), dunno. | AJAX - Reload a part of a webpage without the use of a separate file to load | [
"",
"javascript",
"jquery",
"ajax",
"xmlhttprequest",
"httprequest",
""
] |
I have a problem that seems like its a result of a deadlock-situation.
Whe are now searching for the root of the problem but meantime we wanted to restart the server and get the customer going.
And now everytime we start the program it just says "SqlConnection does not support parallel transactions". We have not chang... | It seems to be that you are sharing connections and creating new transactions on the same open connection (this is the parallel part of the exception you are seeing).
Your example seems to support this as you have no mention of how you acquire the connection in it.
You should do a review of your code and make sure th... | Yours doesn't appear to be an unusual problem. Google found a lot of hits when I pasted your error string into the query box.
Reading past answers, it sounds like it has something to do with interleaving transactions improperly or isolation level.
How long are connections held open? Do you have long-running transacti... | Strange SQL2005 problem. "SqlConnection does not support parallel transactions" | [
"",
"sql",
"transactions",
""
] |
I'm working on an assignment that is telling me to assume that I have a singly linked list with a header and tail nodes. It wants me to insert an item y before position p. Can anybody please look over my code and tell me if I'm on the right track? If not, can you provide me with any tips or pointers (no pun intended)?
... | Just write it down if you get stuck with an algorithm:
```
// First we have a pointer to a node containing element (elm)
// with possible a next element.
// Graphically drawn as:
// p -> [elm] -> ???
tmp = new Node();
// A new node is created. Variable tmp points to the new node which
// currently has no value.
// ... | **Hint**: insertion into a linked list is only constant when position *n* = 0, or the head of the list. Otherwise, the worst-case complexity is *O(n)*. That's not to say that you cannot create a reasonably efficient algorithm, but it will always have *at least* linear complexity. | Inserting a node into a linked list in constant-time? | [
"",
"java",
"linked-list",
""
] |
The callstack shows the following:
```
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandle& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.Creat... | I solved the issue which is caused of SelectList object because it does not provide the default constructor so we cant have in out ViewModel. | For those Googling this exception, here is a more general way to diagnose it:
The only easy way I've found to diagnose this problem is to override MVC as close to the exception as possible with your own code. Then your code will break inside Visual Studio when this exception occurs, and you can read the Type causing t... | Server Error in '/' Application. No parameterless constructor defined for this object | [
"",
"c#",
"asp.net-mvc",
""
] |
I have this PHP code
```
echo '<a href="#" onclick="updateByQuery(\'Layer3\', ' . json_encode($query) . ');">Link 1</a>';
```
which generates a link like this:
```
<a href="#" onclick="updateByQuery('Layer3', "Ed Hardy");">Link 1</a><li>Link 2</li>
```
Causing the javascript to not be called. How would I make it ge... | Try to do the reverse... use single quotes for html, and double quotes for javascript. That's how we do that in fact. | You should [html encode](http://www.php.net/htmlentities) it:
```
echo '<a href="#" onclick="updateByQuery(\'Layer3\', ' . htmlentities(json_encode($query)) . ');">Link 1</a>';
```
You could also use `htmlspecialchars` | php quoting problem | [
"",
"php",
""
] |
How can I calculate the width and height of a `<div>` element, so as to be able to center it in the browser's display (viewport)? What browsers support each technique? | You should use the [`.offsetWidth`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth) and [`.offsetHeight`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight) properties.
Note they belong to the element, not `.style`.
```
var width = document.getElementById('foo').offset... | Take a look at [`Element.getBoundingClientRect()`](https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect).
This method will return an object containing the `width`, `height`, and some other useful values:
```
{
width: 960,
height: 71,
top: 603,
bottom: 674,
left: 360,
... | How do I retrieve an HTML element's actual width and height? | [
"",
"javascript",
"html",
"dhtml",
""
] |
I have a column in my database (a flag) with type varchar(1) that is populated either Y or NULL (not in my control).
In SQL Server, doing an ascending order by query, NULL is ordered at the top.
Is this SQL Server behaviour consistent with Oracle and DB2?
If, instead, I have a COALESCE on the column to ensure it is ... | I know for a fact that DB2 Express and DB2 (at least up to v8) does **not** support the `NULLS FIRST` clause.
If you want a portable solution, you may have to opt for something like:
```
select * from tbl where fld is null
union all select * from tbl where fld is not null
```
I think the result of the union (at ... | > In SQL Server, doing an ascending order by query, NULL is ordered at the top. Should this behaviour be consistent for Oracle and DB2?
[Apparently this is a relative newcomer to the standard](http://en.wikipedia.org/wiki/Order_by_(SQL)).
> The SQL standard's core functionality does not explicitly define a default so... | consistent behaviour among DBMSs with SQL Order By and nulls | [
"",
"sql",
"null",
"sql-order-by",
""
] |
How would you call the constructor of the following class in these three situations: Global objects, arrays of objects, and objects contained in another class/struct?
The class with the constructor (used in all three examples):
```
class Foo {
public:
Foo(int a) { b = a; }
private:
int b;
};
... | ### Global objects
Yours is the only way. On the other hand, try to avoid this. It’s better to use functions (or even other objects) as factories instead. That way, you can control the time of creation.
### Arrays of objects
There’s no way to do this directly. Non-POD objects will always be default-constructed. `std... | To correct some misconceptions about globals:
* The order is well defined within a compilation unit.
+ It is the same as the order of definition
* The order across compilation units is undefined.
* The order of destruction is the **EXACT** opposite of creation.
Not something I recommend but: So a simple solution is... | How do you call a constructor for global objects, for arrays of objects, and for objects inside classes/structs? | [
"",
"c++",
"oop",
"constructor",
""
] |
I have two questions:
1) How can I make an array which points to objects of integers?
```
int* myName[5]; // is this correct?
```
2) If I want to return a pointer to an array, which points to objects (like (1)) how can I do this in a method? ie) I want to impliment the method:
```
int **getStuff() {
// what goes h... | > How can I make an array which points
> to objects?
```
int * myName[5]; /* correct */
```
> If I want to return a pointer to an
> array, which points to objects (like
> (1)) how can I do this in a method?
Technically, you write this function:
```
int * (* getStuff() )[5] {
return &myName;
}
```
That returns ... | Note that your code,
```
int* myName[5];
```
declares an array containing 5 values, each of which is a "pointer to int", which is what you asked.
However this being C++, that's all it does. As a Python scripter, that might cause you some surprises.
It does not give any of those 5 pointers sensible values, and it do... | Pointer Pointer Methods C++ | [
"",
"c++",
"pointers",
"methods",
""
] |
I'm a C++ newbie, but I wasn't able to find the answer to this (most likely trivial) question online. I am having some trouble compiling some code where two classes include each other. To begin, should my #include statements go inside or outside of my macros? In practice, this hasn't seemed to matter. However, in this ... | By "the macros" I assume you mean the #ifndef include guards?
If so, #includes should definitely go inside. This is one of the major reasons why include guards exists, because otherwise you easily end up with an infinite recursion as you noticed.
Anyway, the problem is that at the time you use the A and B classes (ins... | > And just to be clear, in general, where should #include statements go?
Inside the include guards, for the reason you mentioned.
For your other problem: you need to forward-declare at least one of the classes, e.g. like this:
```
#ifndef B_H_
#define B_H_
// Instead of this:
//#include "A.h"
class A;
class B
{
... | Headers Including Each Other in C++ | [
"",
"c++",
"recursion",
"header",
"include",
""
] |
I would like to add an operator to a class. I currently have a `GetValue()` method that I would like to replace with an `[]` operator.
```
class A
{
private List<int> values = new List<int>();
public int GetValue(int index) => values[index];
}
``` | ```
public int this[int key]
{
get => GetValue(key);
set => SetValue(key, value);
}
``` | I believe this is what you are looking for:
**[Indexers (C# Programming Guide)](http://msdn.microsoft.com/en-us/library/6x16t2tx(v=VS.100).aspx)**
```
class SampleCollection<T>
{
private T[] arr = new T[100];
public T this[int i]
{
get => arr[i];
set => arr[i] = value;
}
}
// This cla... | How do I overload the [] operator in C# | [
"",
"c#",
"operator-overloading",
"indexer",
""
] |
Is there a class/example application for a message-only window that is in C++ [Win32](http://en.wikipedia.org/wiki/Windows_API)? | If I recall, the standard solution is to create a basic styleless window with a message pump as you normally would, but never call ShowWindow on it. This way you can receive and process the standard messages like WM\_QUERYENDSESSION which are sent to all windows. | From the docs for [CreateWindow](http://msdn.microsoft.com/en-us/library/ms632679(VS.85).aspx):
> hWndParent
> [in] Handle to the parent or owner window of the window being created. To
> create a child window or an owned
> window, supply a valid window handle.
> This parameter is optional for pop-up
> windows.
>
> Win... | Message Window C++ Win32 class/example | [
"",
"c++",
"winapi",
"window",
"message",
""
] |
I have a utility that I put together that uses the .NET Framework to capture an image of a web page so that I can use the thumbnail image to preview a page. There are sites which offer this service like websnapr.com, kwiboo.com and shrinktheweb.com. I would like to instead do it myself and leverage Firefox (Gecko) and ... | I use a Firefox add-on called [Screengrab](http://addons.mozilla.org/en-US/firefox/addon/1146) | checkout <http://browsershots.org/> its free and open. it says somewhere on the site what plugins and techniques they use... | Capturing the image of a web page using Firefox and Safari | [
"",
"c#",
".net",
""
] |
I'm binding a GridView to an LINQ query. Some of the fields in the objects created by the LINQ statement are strings, and need to contain new lines.
Apparently, GridView HTML-encodes everything in each cell, so I can't insert a <br /> to create a new line within a cell.
How do I tell GridView not to HTML encode the c... | Can you subscribe to the RowDataBound event? If you can, you can run:
```
if (e.Row.RowType == DataControlRowType.DataRow)
{
string decodedText = HttpUtility.HtmlDecode(e.Row.Cells[0].Text);
e.Row.Cells[0].Text = decodedText;
}
``` | What about setting the [`HtmlEncode` property](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.htmlencode.aspx) to `false`? To me, this is much simpler.
```
<asp:BoundField DataField="MyColumn" HtmlEncode="False" />
``` | How to render decoded HTML in a (i.e. a <br>) in GridView cell | [
"",
"c#",
"asp.net",
"gridview",
"newline",
""
] |
Why do we need both `using namespace` and `include` directives in C++ programs?
For example,
```
#include <iostream>
using namespace std;
int main() {
cout << "Hello world";
}
```
Why is it not enough to just have `#include <iostream>` or just have `using namespace std` and get rid of the other?
(I am thinking o... | In `C++` the concepts are separate. This is by design and useful.
You can include things that without namespaces would be ambiguous.
With namespaces you can refer to two different classes that have the same name. Of course in that case you would not use the `using` directive or if you did you would have to specify th... | using directives and include preprocessor directives are two different things. The `include` roughly corresponds to the `CLASSPATH` environment variable of Java, or the `-cp` option of the java virtual machine.
What it does is making the types known to the compiler. Just including `<string>` for example will make you ... | Why do we need both using-directives and include-directives? | [
"",
"c++",
"namespaces",
"header-files",
"language-design",
""
] |
It looks like if I load dynamic content using `$.get()`, the result is cached in browser.
Adding some random string in QueryString seems to solve this issue (I use `new Date().toString()`), but this feels like a hack.
Is there any other way to achieve this?
Or, if unique string is the only way to achieve this, any su... | I use `new Date().getTime()`, which will avoid collisions unless you have multiple requests happening within the same millisecond:
```
$.get('/getdata?_=' + new Date().getTime(), function(data) {
console.log(data);
});
```
**Edit:** This answer is several years old. It still works (hence I haven't deleted it), b... | The following will prevent all future AJAX requests from being cached, regardless of which jQuery method you use ($.get, $.ajax, etc.)
```
$.ajaxSetup({ cache: false });
``` | Prevent browser caching of AJAX call result | [
"",
"javascript",
"jquery",
"ajax",
"browser-cache",
""
] |
In a method, I want to be able to insert a value into a div which is part of the html document I choose to parse.
```
public void AddToDiv(string div)
{
//Code to read the html document and look for the div
//(name specified as the parameter of this method).
}
```
Question is, I could specify a div called "a... | Personally, I'd check for existence, rather than allowing the exception to be thrown, it's easier to determine the flow of logic, and fits better with the intent of your code.
See these questions and answers for a broader discussion
[When to throw an exception](https://stackoverflow.com/questions/77127/when-to-throw-... | There is a third option, but I'll write more about it later.
First of all, catching exception is all about catching errors you don't expect, handling them and either continue or close down gracefully.
Throwing exceptions should be used when you encounter situation which shouldn't occur or should be handled elsewhere.... | Difference between catch block and throw new Exception in method | [
"",
"c#",
"exception",
""
] |
I want to have a abstract view for any type of UI (web or window). In order to do that I must use Interface (IView ) in which I can only apply just rules about view. In fact, I want to set a some basic comple function to provide to its inheritances.
So in this way, I must use abstract class. The problem is
1) Interfa... | Will the functions you add change the definition of what the class is, or will you simply be creating functions to manipulate data that is already a part of the class?
If you need to redefine aspects of the base class of these two classes then yes, you will need to change your inheritance structure. But if the functio... | You can inherit a concrete class (web form/window form), declare your class abstract, and still implement an interface.
System.Web.UI.Page example:
```
public interface IView
{
void Foo();
}
public abstract class BasePage : Page, IView
{
//honor the interface
//but pass implementation responsibility to i... | Interface or Abstract Class to fulfill requirement | [
"",
"c#",
".net",
""
] |
I've faced strange problem. While user change of check box input element on form produces adequate event programmatic change don't. How should I face this challenge? Code following:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www... | It's impossible to track object's state within javascript language as it could be done in Objective-C (KVO). Nor it possible using DOM features - DOM do not fire events on every property change - instead it only fires events on certain user actions: mouse clicks, key presses, or page life cycle and their derivatives.
... | use the trigger function to trigger a click event on the checkbox. You won't need to grab the existing state as the checkbox will just be toggled by the click.
```
jQuery("#cb").trigger('click');
``` | How to handle programmatic change of the input element state in javascript | [
"",
"javascript",
"jquery",
"html",
"dom",
""
] |
I've seen a number of examples that have a thread procedure that looks like this.
```
private void ThreadProc()
{
while (serviceStarted)
{
// do some work
Thread.Sleep(new TimeSpan(0, 0, 5));
}
Thread.CurrentThread.Abort();
}
```
Is the `Abort()` r... | Calling `Thread.Abort()` does raise an exception, and if you're writing code that will be re-used (or part of a base library) it's difficult for other developers to handle `ThreadAbortExcpetion`s.
It's explained in this article about [Reliability Best Practices](http://msdn.microsoft.com/en-us/library/ms228970(VS.80).... | Once the loop exits, the thread will terminate on its own. There is not need to abort the thread.
The `CurrentThread.Abort` is not only superfluous, but genuinely harmful since it raises a `ThreadAbortException`. If another thread attempts to `Join()` your service loop thread, it will have to handle an exception unnec... | To CurrentThread.Abort or not to CurrentThread.Abort | [
"",
"c#",
".net",
"multithreading",
""
] |
I`m writing a chat using WinSock2 and WinAPI functions. And I have a little trouble.
I store the std::vector of client connections on server. When new client connects, new thread starts and all work with the client is done in this new thread. I do not use classes (I know it is not very good) so this list of connectio... | Yes, you are just lucky never to experience any problems. This is the problem with synchronization issues and race conditions, that the code will work in 99.9% of all cases, and when disaster strikes you won't know why.
I would take away the constructor taking a CRITICAL\_SECTION as a parameter since it is not clear w... | The biggest question I have for you is architectural. Does the thread for each connection really need direct access to this array of **other** connections? Shouldn't they really be enqueueing abstract messages of some sort? If each connection thread is conscious of the implementation details of the universe in which it... | Critical section - to be or not to be? | [
"",
"c++",
"winapi",
"critical-section",
""
] |
I have a Django model (schedule) with the class of entity, that is the parent of `Activity`, that is the parent of `Event`.
```
class Entity(models.Model):
<...>
class Activity(models.Model):
<...>
team_entity = models.ForeignKey(Entity)
<...>
class Event(models.Model):
<...>
activity = mo... | I now use django-piston. This does the trick. | Before you do serialization, when retrieving your objects, to preserve the relationships use select\_related() to get children, grandchildren, etc
see <http://docs.djangoproject.com/en/dev/ref/models/querysets/> | Django serialize to JSON | [
"",
"python",
"django",
"json",
""
] |
Given this field:
```
char lookup_ext[8192] = {0}; // Gets filled later
```
And this statement:
```
unsigned short *slt = (unsigned short*) lookup_ext;
```
What happens behind the scenes?
lookup\_ext[1669] returns 67 = 0100 0011 (C), lookup\_ext[1670] returns 78 = 0100 1110 (N) and lookup\_ext[1671] returns 68 = 0... | The statement that you show doesn't cast a char to an unsigned short, it casts a *pointer* to a char to a *pointer* to an unsigned short. This means that the usual arithmetic conversions of the pointed-to-data are not going to happen and that the underlying char data will just be interpreted as unsigned shorts when acc... | If I understand correctly, the type conversion will be converting a char array of size 8192 to a short int array of size half of that, which is 4096.
So I don't understand what you are comparing in your question. slt[1670] should correspond to lookup\_ext[1670\*2] and lookup\_ext[1670\*2+1]. | Casting a char to an unsigned short: what happens behind the scenes? | [
"",
"c#",
"c",
"casting",
""
] |
I am currently working on a project that spans accross multiple domains. What I want is for the user to be able to login on one site and be logged in on all the others at the same time.
The users session is stored in the database, the cookies that I set on each domain contain the session id.
So basically when a user ... | Have a look at my question [Cross Domain User Tracking](https://stackoverflow.com/questions/216430/cross-domain-user-tracking).
What you need to do is to add another HTTP header to the "image".
Quote from [Session variables are lost if you use FRAMESET in Internet Explorer 6](http://support.microsoft.com/kb/323752/EN... | Is it just me, or does it sound like your CSRFing yourself with your technique using images that works in Firefox?
Interesting approach, although I hope you're not opening yourself up to a security threat there. | PHP Multi site login | [
"",
"php",
"authentication",
"single-sign-on",
"multiple-domains",
""
] |
I am just getting started with Grails. How do I add Java libraries to my Grails project? I added the Smack library jar to the lib folder of my Grails project, but I still cannot import any of its packages into my Java or Groovy classes. I am using the Netbeans IDE. Any help would be appreciated..
Buzzy | This is a know bug in NetBeans: <http://www.netbeans.org/issues/show_bug.cgi?id=144243>
Maybe you can help the devolpers to fix it by adding a comment to this issue in the NetBeans bug tracker. | Here is what I did to solve the problem when running SpringSource Toolsuite:
1. Configure the build path by adding external jars (e.g. javax.mail, adwords-api, etc.)
2. Imported the same jars in to the lib folder (where mysql connector jar is located).
This should fix the compile time errors you would receive from mi... | Add Java Libraries to a Netbeans Grails Project | [
"",
"java",
"grails",
"netbeans",
"groovy",
"jar",
""
] |
It would be really handy to be able to somehow say that certain properties in the generated entity classes should, for example, be decorated by (say) validation attributes (as well as Linq To SQL column attributes).
Is it a T4 template someplace? Or are there other ways to skin the cat? | Damien Guard has written T4 templates that can be customized. See:
<http://damieng.com/blog/2008/09/14/linq-to-sql-template-for-visual-studio-2008>
...and:
<http://visualstudiomagazine.com/listings/list.aspx?id=560> | No, the SqlMetal tool is what handles the generation of the C# and it is defined within itself how the C# is generated (or VB for that matter).
I'm not familiar with the template style you want but you could try exteding the generated classes (if they aren't that big a change) since they are just partial classes.
Oth... | Possible to modify the C# that Linq To SQL generates? | [
"",
"c#",
"linq-to-sql",
"templates",
"code-generation",
""
] |
How can I change the master volume level? Using this code
```
[DllImport ("winmm.dll")]
public static extern int waveOutSetVolume (IntPtr hwo, uint dwVolume);
waveOutSetVolume (IntPtr.Zero, (((uint)uint.MaxValue & 0x0000ffff) | ((uint)uint.MaxValue << 16)));
```
I can set the wave volume but if the master volume is ... | Okay, here goes:
```
const int MAXPNAMELEN = 32;
const int MIXER_SHORT_NAME_CHARS = 16;
const int MIXER_LONG_NAME_CHARS = 64;
[Flags] enum MIXERLINE_LINEF : uint{
ACTIVE = 0x00000001,
DISCONNECTED = 0x00008000,
SOURCE = 0x80000000
}
[Flags] enum MIXER : uint{
GETLINEI... | For the master volume (for Vista and above), that would be:
[ISimpleAudioVolume::SetMasterVolume](http://msdn.microsoft.com/en-us/library/ms679141(VS.85).aspx)
As explained [here](http://www.tech-archive.net/Archive/Development/microsoft.public.win32.programmer.mmedia/2007-01/msg00045.html), you may refer to the sect... | Changing master volume level | [
"",
"c#",
"winapi",
"volume",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.