Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Unfortunately, despite having tried to learn regex at least one time a year for as many years as I can remember, I always forget as I use them so infrequently. This year my new year's resolution is to not try and learn regex again - *So this year to save me from tears I'll give it to Stack Overflow*. (Last Christmas re... | If your string will always be of that format, a regex is overkill:
```
>>> var g='{getThis}';
>>> g.substring(1,g.length-1)
"getThis"
```
`substring(1` means to start one character in (just past the first `{`) and `,g.length-1)` means to take characters until (but not including) the character at the string length min... | Try
```
/{(.*?)}/
```
That means, match any character between { and }, but don't be greedy - match the shortest string which ends with } (the ? stops \* being greedy). The parentheses let you extract the matched portion.
Another way would be
```
/{([^}]*)}/
```
This matches any character except a } char (another w... | Regex to get string between curly braces | [
"",
"javascript",
"regex",
""
] |
It seems to me that explicitly specifying serialVersionUID for new classes is bad. Consider the two cases of not changing it when layout has it should have been changed and changing it when it should not have.
Not changing when it should have been changed occurs almost only when it is explicit. In this case, it result... | Changing when it shouldn't may happen for reasons other than class layout changes - the problem is that it's compiler implementation dependent. If you do debug with Eclipse but do production builds with javac, you *may* end up with two incompatible sets of data. | At my work we explicitly prohibit specifying serialVersionUID, exactly because of the problems you bring up.
In addition, the classes we persist are only used to store data with no logic inside, so the only way they change is because of changing data members. | explicit serialVersionUID considered harmful? | [
"",
"java",
"serialization",
"serialversionuid",
""
] |
I have 2 tables:
1. Employees
2. Vouchers
Employees table has a single primary key.
Vouchers table has 3 foreign key constraints referencing the Employees table.
The following is a sample T-SQL script (not the actual table script) to create both tables and their relationship in SQL Server:
```
IF OBJECT_ID('dbo.Vouc... | Strictly from a relational design point of view, the Vouchers table as three Foreign Keys. Whether you choose to enforce them, through CASCADE assertions or otherwise, is an implementation issue, but the relational design still exists. Presumably you want to enforce that, if one of the three fields is not NULL, then a ... | I would not actually delete Employees, but instead use a trigger to set a flag to mark them as deleted.
I generally don't turn on cascade of Updates or Deletes, but instead require an application to explicitly perform these actions. | Data Modeling: What is a good relational design when a table has several foreign key constrainst to a single table? | [
"",
"sql",
"sql-server",
"data-modeling",
""
] |
Not quite an Attribute, not quite a Method. Stereotypes? `<<get>>` `<<set>>`?
---
*I'm retro-modelling an existing system, so I need to clearly reflect that this is not the same as a readonly field or a methods pair (regardless of what the IL says), so I think I'll go with the stereotype, but I'll accept the language... | Properties are just a convenient way of writing `get_MyValue()` and `set_MyValue(value)` allowing assignment rather than the normal method calling (using parenthesis).
What you are accessing is actually a .NET property, C# has its own syntax for accessing these. Since under the skin the real `get_` and `set_` methods ... | I usually prepare my UML diagrams in Visio (I know, I know; but what're ya gonna do?).
When diagramming properties, they end up as so:
```
+------------------------+
| MyClass |
|------------------------|
| - _foo : int |
|------------------------|
| «property» + Foo : int |
+----------------... | How to represent a C# property in UML? | [
"",
"c#",
".net",
"properties",
"uml",
""
] |
I'm writing an add-in for [ReSharper](http://en.wikipedia.org/wiki/ReSharper) 4. For this, I needed to reference several of ReSharper's assemblies. One of the assemblies (JetBrains.Platform.ReSharper.Util.dll) contains a `System.Linq` namespace, with a subset of extension methods already provided by System.Core.
When ... | This is no longer an issue, since I am able to use the LINQ extensions, as provided by ReSharper DLL files, even while targeting .NET 3.0.
Mr. Skeet was right again! I am able to use full LINQ syntax, while targeting .NET 3.0 in the project's properties and not referencing System.Core! | This is probably one of those rare cases where it makes sense to use an [extern alias](http://msdn.microsoft.com/en-us/library/ms173212.aspx).
In the properties page for the reference to System.Core (i.e. under References, select System.Core, right-click and select "Properties"), change the "Aliases" value to "global,... | Resolving extension methods/LINQ ambiguity | [
"",
"c#",
".net",
"visual-studio-2008",
"linq",
"extension-methods",
""
] |
Can jQuery test an array for the presence of an object (either as part of the core functionality or via an avaible plugin)?
Also, I'm looking for something like `array.remove`, which would remove a given object from an array. Can jQuery handle this for me? | [jQuery.inArray](http://docs.jquery.com/Utilities/jQuery.inArray) returns the first index that matches the item you searched for or -1 if it is not found:
```
if($.inArray(valueToMatch, theArray) > -1) alert("it's in there");
```
You shouldn't need an array.remove. Use splice:
```
theArray.splice(startRemovingAtThis... | If your list contains a list of elements, then you can use [jQuery.not](http://api.jquery.com/not/) or [jQuery.filter](http://api.jquery.com/filter/) to do your "array.remove". (Answer added because of the high google score of your original question). | jquery version of array.contains | [
"",
"javascript",
"jquery",
""
] |
Here's an example of the query I'm trying to convert to LINQ:
```
SELECT *
FROM Users
WHERE Users.lastname LIKE '%fra%'
AND Users.Id IN (
SELECT UserId
FROM CompanyRolesToUsers
WHERE CompanyRoleId in (2,3,4) )
```
There is a FK relationship between `CompanyRolesToUsers` and `Users`, b... | Here's a subquery for you!
```
List<int> IdsToFind = new List<int>() {2, 3, 4};
db.Users
.Where(u => SqlMethods.Like(u.LastName, "%fra%"))
.Where(u =>
db.CompanyRolesToUsers
.Where(crtu => IdsToFind.Contains(crtu.CompanyRoleId))
.Select(crtu => crtu.UserId)
.Contains(u.Id)
)
```
---
Regarding this ... | There is no subquery needed with this statement, which is better written as
```
select u.*
from Users u, CompanyRolesToUsers c
where u.Id = c.UserId --join just specified here, perfectly fine
and u.lastname like '%fra%'
and c.CompanyRoleId in (2,3,4)
```
or
```
select u.*
from Users u inner join CompanyRole... | How to do a subquery in LINQ? | [
"",
"c#",
"linq",
"linq-to-sql",
""
] |
How does Python evaluate the expression `1+++2`?
How many ever `+` I put in between, it is printing `3` as the answer. Please can anyone explain this behavior
And for `1--2` it is printing `3` and for `1---2` it is printing `-1` | Your expression is the same as:
```
1+(+(+2))
```
Any numeric expression can be preceded by `-` to make it negative, or `+` to do nothing (the option is present for symmetry). With negative signs:
```
1-(-(2)) = 1-(-2)
= 1+2
= 3
```
and
```
1-(-(-2)) = 1-(2)
= -1
```
I see you clarifie... | The extra +'s are not incrementors (like ++a or a++ in c++). They are just showing that the number is positive.
There is no such ++ operator. There is a unary + operator and a unary - operator though. The unary + operator has no effect on its argument. The unary - operator negates its operator or mulitplies it by -1.
... | Why does 1+++2 = 3? | [
"",
"python",
"evaluation",
"operator-precedence",
""
] |
In a lot of my PHP projects, I end up with classes that have non-public functions that I don't intend to extend.
Is it best to declare these as protected, or private?
I can see arguments both ways - making them private is a far more conservative approach, but it can be argued that they could be made protected later i... | My instinct is to keep them private, until you need them to be otherwise.
It has been argued (sadly I've misplaced the link) that making methods private is antisocial, in much the same way as making them 'final', in that it's fairly dictatorial about how people may use your code.
I'm not convinced, however, and agree... | I think you should only expose what you need to when you need to. This makes doing impact assessments of changes easier. i.e. If a method is private, you **know** the impact will be minimal if you change it. | Best to use Private methods or Protected methods? | [
"",
"php",
"oop",
""
] |
Is there a viable alternative to Hibernate? Preferably something that doesn't base itself on JPA.
Our problem is that we are building a complex (as in, many objects refer to each other) stateful RIA system. It seems as Hibernate is designed to be used mainly on one-off applications - JSF and the like.
The problem is ... | As mentioned, JPA <> EJB, they're not even related. EJB 3 happens to leverage JPA, but that's about it. We have a bunch of stuff using JPA that doesn't even come close to running EJB.
Your problem is not the technology, it's your design.
Or, I should say, your design is not an easy fit on pretty much ANY modern frame... | If you're after another JPA provider (Hibernate is one of these) then take a look at [EclipseLink](http://www.eclipse.org/eclipselink/). It's far more fully-featured than the JPA 1.0 reference implementation of TopLink Essentials. In fact, EclipseLink will be the JPA 2.0 reference implementation shipped with Glassfish ... | An alternative to Hibernate or TopLink? | [
"",
"java",
"hibernate",
"jpa",
"jakarta-ee",
"eclipselink",
""
] |
In ASP.NET 2, I've used Field Validators, and RequiredField validators, but I'm unsure of how to handle a case like this.
I have two check boxes on a page, and I need to be sure that at least one of them is set. So, if you look at in binary, it can be 01, 10 or 11, but it can not be 00. My question is, what the best... | Worst case you can write a CustomValidator the can do whatever you like. Sounds like what you need is along the lines of:
isValid = Check1.Checked | Check2.Checked | Use [CustomValidator](http://msdn.microsoft.com/en-us/library/9eee01cx.aspx) | ASP.NET Multiple Field Validation | [
"",
"c#",
"asp.net",
""
] |
I have to write a program that read from a file that contains the folowing:
```
toto, M, 50
fifi, F, 60
soso, F, 70
lolo, M, 60
fifi, F, 60
```
---
And then find the following:
Which mark is most repeated, and how many times is it repeated?
* average all students
* average all male
* average all female
How many a... | I haven't test it. But you should call `SW.close()` after finished writing stuffs. | The other answers talk about calling Close explicitly - I would suggest that instead of doing that, you wrap the use of the StreamWriter (and StreamReader and streams) in a `using` statement, e.g.
```
using (StreamWriter SW = new StreamWriter(FS))
{
for (int i = 0; i < Output.Length; i++)
{
SW.WriteLin... | Why is this file not actually writing to disk? | [
"",
"c#",
"file-io",
""
] |
What's the explanation for the following:
```
public class GenericsTest {
//statement 1
public ArrayList<Integer>[] lists;
public GenericsTest()
{
//statement 2
lists = new ArrayList<Integer>[4];
}
}
```
The compiler accepts statement 1. Statement 2 is flagged by the compiler ... | There seems to be obscure cases where you could inadvertently cause a ClassCastException as explained here
<http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf> (section 7.3)
an intersting discussion on this topic could be found here
<http://courses.csail.mit.edu/6.170/old-www/2006-Spring/forum/index.php%3Ftopic=32... | It's because you can't create, but you can **use** them:
```
public class GenericsTest {
//statement 1
public ArrayList<Integer>[] lists;
public GenericsTest()
{
//statement 2
lists = new ArrayList[4];
//statement 3
lists[0].add(new Integer(0));
//statement 4
... | Java generics and array initialization | [
"",
"java",
"arrays",
"generics",
""
] |
EDIT: It is not a listbox. My mistake. It is a list view.
I have a list view control that's driving me nuts. It is a multi-select list box, so if the user selects 5000 rows, then de-selects them by selecting a single row, the SelectedIndexChanged fires 5001 times. This causes my app to hang.
I'm trying to use threads... | I remember solving this issue [before](http://bytes.com/groups/net-c/723916-c-listview-selection-change):
> A better way perhaps for you would be
> to put a minimal delay in your
> ItemSelectionChange Handler. Say --
> 50ms. Use a timer, Once the selection
> changes, restart the timer. If the
> selection changed more ... | A possible solution is to delay the work, so you know whether or not more events have fired. This assumes the order of the selections is not important; all that matters is the current state.
Instead of doing the work as soon as the event fires, set up a timer to do it a couple milliseconds after the event fires. If th... | Using threads to count the loops in C# events | [
"",
"c#",
"multithreading",
""
] |
I have a web application that currently sends emails. At the time my web applications sends emails (sending of emails is based on user actions - not automatic), it has to run other processes like zipping up files.
I am trying to make my application "future proof" - so when there are a large number of users I don't wan... | It's a good approach, but the most important thing you can do right now is have a clear interface for queuing up the messages, and one for consuming the queue. Don't make the usage on either end hard-coded to a DB.
Later on, if this becomes a bottleneck, you may want the mail sending to be done from a different machin... | One aspect you might have ignored is the zipping speed you are using, it might be in your best interest to use a lighter compression level in your zip process as that can make large improvements in zip time (easily double) which can add up to a lot when you get into the realm of multiple users.
Even better if you make... | Web Application Architecture: Future Proofing | [
"",
"php",
"database",
"web-applications",
"cron",
""
] |
I'm using a string builder to build some SQL Scripts. I have a few Boolean Properties that I would like to test and then output different text based on true/false. I've you the C# syntax below when assigning a value to a variable, but it isn't working for this particular situation. Any ideas?
What I'm used to doing:
... | Add parentheses:
```
script.Append("sometext" + ((dbInfo.IsIdentity) ? " IDENTITY(1,1)" : ""));
``` | What about this?
```
script.Append( "sometext" );
script.Append( dbInfo.IsIdentity ? " IDENTITY(1,1)" : "" );
``` | Using a Boolean Expression in a StringBuilder | [
"",
"c#",
"string",
"syntax",
"boolean",
""
] |
I want to wait for a process to finish, but `Process.WaitForExit()` hangs my GUI. Is there an event-based way, or do I need to spawn a thread to block until exit, then delegate the event myself? | [process.EnableRaisingEvents](https://msdn.microsoft.com/en-us/library/system.diagnostics.process.enableraisingevents.aspx) = true;
[process.Exited](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.exited.aspx) += [EventHandler] | As of .NET 4.0/C# 5, it's nicer to represent this using the async pattern.
```
/// <summary>
/// Waits asynchronously for the process to exit.
/// </summary>
/// <param name="process">The process to wait for cancellation.</param>
/// <param name="cancellationToken">A cancellation token. If invoked, the task will retur... | Process.WaitForExit() asynchronously | [
"",
"c#",
".net",
"winforms",
"user-interface",
"asynchronous",
""
] |
I have `ControlA` which accepts an `IInterfaceB` which has a property of type
`List<unknownType>`
In an event of `ControlA` i need to add a new instance of `unknownType` to the List in `IInterfaceB`...
`unknownType` needs specific properties so i immediately thought it could be an interface, but quickly realised inte... | If I'm interpreting this correctly, you could add a constraint on unknownType to be of some interface that contains the properties you need:
```
class ControlA
{
void Frob<T>(IInterfaceB<T> something) where T : IHasSomeProperties, new()
{
something.ListOfT.Add(new T() { SomeProperty = 5 });
som... | Would a restriction on the type work?
```
List<T> where T : IInterface
``` | How would you approach this design? | [
"",
"c#",
"interface",
""
] |
Hi all I'm running into a situation where link buttons are not responding on a gridview control in one of my apps deployed on a production machine. Not sure exactly what's going on.
The problem is very similar to [this one](https://stackoverflow.com/questions/96837/linkbutton-not-firing-on-production-server) although ... | Turns out this was an issue with SQL server authentication. It was not immediately apparent to me because I was running my app in Firefox which did not display any errors; just non responsive UI elements. Running things in IE revealed the problem. I adjusted permissions on the database I was trying to connect to and th... | Any chance javascript is disabled in the browser? I've also had trouble like this with certain AV security apps that muck with javascript in the browser. | LinkButtons not working in ASP.net/C# app production deployment | [
"",
"c#",
"asp.net",
""
] |
In native programming the IXMLDOMDocument2 object had a [`tranformNode()`](http://msdn.microsoft.com/en-us/library/ms896487.aspx) method:
```
public BSTR transformNode(IXMLDOMNode stylesheet);
```
So in the end I could transform an XML document using:
```
public string TransformDocument(IXMLDOMDocument2 doc, IXMLDOM... | The functions take IXPathNavigable objects as input (and XmlDoucment/XmlNode classes implement IXPathNavigable).
Here's how it would work:
```
public string TransformDocument(XmlDocument doc, XmlDocument stylesheet)
{
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(stylesheet); // co... | First load the XSL and the XML doc.
```
XmlDocument xsldoc = new XmlDocument();
xsldoc.Load(xslfile);
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(xmlfile);
```
Load the xsl into a transform object.
```
XslCompiledTransform xsldoctrans = new XslCompiledTransform();
xsldoctrans.Load(xsldoc);
```
Transform it... | .NET XML: What is the .NET equivalent of XmlDocument.TransformNode? | [
"",
"c#",
".net",
"xml",
""
] |
I'm trying to fix a bug in a rich text editor I'm using, which causes `<embed>` tags to be inserted without their closing tag (which screws the output up completely). I've isolated the problem to this operation:
```
// body is a <body> tag
body.innerHTML = '<embed src="http://example.com/whatever"></embed>';
```
No f... | This might not be an answer to your problem, but *<embed>* was not part of any standardized version of HTML until HTML5, according to [W3C](http://validator.w3.org/docs/help.html). | This reminds me of the problems document.write had/has with <script /> tags.
Lies. Don't answer SO questions right before bed.
~~I tried the following in Firebug~~
```
//break up initial embed into single chunks
document.body.innerHTML = "<e"+"mbe"+"d></embed>"
```
and got the expected to show up when I checked the... | What's up with innerHTML and <embed>? | [
"",
"javascript",
"html",
"embed",
"innerhtml",
""
] |
I'm creating a small code plugin which allows you to do some things with arrays. I do not wish to add the functions to the array object using a prototype construction, what I want is that people can do something like:
```
arrayFunction( [1, 2, 3] ).someSpecialArrayFunction();
```
Thus leaving the normal array object ... | Or simply:
```
var arrayFunction = function(array) {
var someSpecialArrayFunction = function() {
// do something with array
};
return {
someSpecialArrayFunction: someSpecialArrayFunction
}
};
arrayFunction( [1, 2, 3] ).someSpecialArrayFunction();
```
Although be careful with this, if y... | I am not sure this is the best syntax to get what you want, but I suppose this is a trimmed down example ... Anyways here is a quick way to make it work
```
var arrayFunction = window.arrayFunction = function(array) {
return new arrayFunction.fn.init(array);
}
arrayFunction.fn = arrayFunction.prototype = {
ini... | Howto create a jquery-like $() wrapper function? | [
"",
"javascript",
""
] |
What scenarios would warrant the use of the "[Map and Reduce](http://en.wikipedia.org/wiki/MapReduce)" algorithm?
Is there a .NET implementation of this algorithm? | Linq equivalents of Map and Reduce:
If you’re lucky enough to have linq then you don’t need to write your own map and reduce functions. C# 3.5 and Linq already has it albeit under different names.
* Map is `Select`:
```
Enumerable.Range(1, 10).Select(x => x + 2);
```
* Reduce is `Aggregate`:
```
Enumerable... | The classes of problem that are well suited for a mapreduce style solution are problems of aggregation. Of extracting data from a dataset. In C#, one could take advantage of LINQ to program in this style.
From the following article:
<http://codecube.net/2009/02/mapreduce-in-c-using-linq/>
> the GroupBy method is acti... | Map and Reduce in .NET | [
"",
"c#",
"mapreduce",
""
] |
I have a stored procedure that returns two int Values. The first can not be null but the second can actually return a null value. When I try to execute my stored procedure using LINQ to SQL it fails with the statement:
> The null value cannot be assigned to a member with type System.Int32 which is a non-nullable value... | You need to declare the variable to be nullable. In the designer, click the property in your model that needs to be nullable, and then in the **Properties** window, set the "Nullable" property to **True**. This will tell the generator to create your property as `Nullable<int> or int?` | Try declaring the int variables as nullable. I.e.
```
int? myInt;
```
This way you can check them for null. | How can I handle a NULLable Int column returned from a stored procedure in LINQ to SQL | [
"",
"c#",
"asp.net",
"linq-to-sql",
"stored-procedures",
""
] |
I'm looking for a routine that will format a string of numbers as a UK phone number. The routine should account for UK area codes that require different formatting (i.e. London compared to Edinburgh compared to Worcester) as well as mobile numbers.
My phone numbers are stored in the database as strings, containing onl... | UK telephone numbers vary in length from 7 digits to 10 digits, not including the leading zero. "area" codes can vary between 2 and usually 4 (but occasionally 5) digits.
All of the tables that show the area code and total length for each number prefix are available from [OFCOM's website](http://www.ofcom.org.uk/stati... | \*\* I'm looking for a routine that will format a string of numbers as a UK phone number. \*\*
You could download the Ofcom database that lists the formats for each number range, including national dialling only numbers, and do a lookup for each number you need to format. The database lists the SABCDE digits and the f... | Format string as UK phone number | [
"",
"c#",
"regex",
"formatting",
"user-interface",
""
] |
At my place of work I've been put in charge of creating a coding standards document. Generally we follow what FxCop and StyleCop tools report to some degree but what we really require is document that will explain when to use a convention, why and maybe even a simple example.
This could be extended in the future for o... | [ScrewTurn Wiki](http://www.screwturn.eu/) is an free and open-source wiki made in C# and ASP.Net. Different database back-ends can be used, like MSSQL and MySQL, but also works without any database. It has [several plugins](http://www.screwturn.eu/UsersPlugins.ashx#Users_Storage_Providers_32) to work with Active Direc... | ## Mindtouch Deki
Great wiki and it's built on C# and PHP, so you can use it on Mono or .NET
It also has Active Directory integration.
Download their ready-to-use VMware image. It started using it on my own PC then moved it to the company's VMware server when they had it ready. | Coding Standard Wiki | [
"",
"c#",
"wiki-engine",
""
] |
I have a C# WCF REST Service which allows the addition of a bookmark, by sending an HTTP POST request with the bookmark serialised in XML. I have specified the operation contract for the service, which picks up the xml and automatically deserialises the object for me. My problem is that the deserialisation only works c... | The DataContractSerializer requires strict ordering of elements for both versioning and performance reasons.
There are some options I can think of,
1. write a message inspector to re-order the raw XML elements in AfterReceivedRequest before it's deserialized by dataContractSerializer.
2. using the XmlSerializer for y... | I haven't tried to do this myself, but I'll take a guess.
Would it help to create a [OnDeserializing] event on your DataContract that would fire just before deserialization? At that point maybe you could reorder the xml however it needs to be ordered so that deserialization would work properly.
If you have Juval Lowy... | Can WCF REST services support deserialisation of XML messages with arbitrary element order? | [
"",
"c#",
"wcf",
"rest",
""
] |
How do I do sorting when generating anonymous types in linq to sql?
Ex:
```
from e in linq0
order by User descending /* ??? */
select new
{
Id = e.Id,
CommentText = e.CommentText,
UserId = e.UserId,
User = (e.User.FirstName + " " + e.User.LastName).Trim()),
Date = string.Format("{0:d}", e.Date)
}
``` | If you're using LINQ to Objects, I'd do this:
```
var query = from e in linq0
select new
{
Id = e.Id,
CommentText = e.CommentText,
UserId = e.UserId,
User = (e.User.FirstName + " " + e.User.LastName).Trim()),
Date =... | If I've understood your question correctly, you want to do this:
```
from e in linq0
order by (e.User.FirstName + " " + e.User.LastName).Trim()) descending
select new
{
Id = e.Id,
CommentText = e.CommentText,
UserId = e.UserId,
User = (e.User.FirstName + " " + e.User.LastName).Trim()),
Date = string.Fo... | LINQ sorting anonymous types? | [
"",
"c#",
"linq-to-sql",
""
] |
Whenever I try to write graphical programs (whether a game or really any GUI app) I always wind up with one or two god classes with way too many methods (and long methods, too), and each class having far too many responsibilities. I have graphics being done at the same time as calculations and logic, and I feel like th... | Here is a simple (but effective) OO design to get you started:
First create a Game object that is pure Java/C# code. With no UI or anything else platform specific. The Game object handles a Board object and a Player object. The Board object manages a number of Tile objects (where the mines are). The Player object keep... | use a MVC framework that handles all the hard organization work for you. there's a ton of MVC framework topics on SO.
using high quality stuff written by others will probably teach you faster - you will get further and see more patterns with less headache. | How can I best apply OOP principles to games and other input-driven GUI apps? | [
"",
"java",
"model-view-controller",
"language-agnostic",
"oop",
""
] |
How do I convert a `string` to a `byte[]` in .NET (C#) without manually specifying a specific encoding?
I'm going to encrypt the string. I can encrypt it without converting, but I'd still like to know why encoding comes to play here.
Also, why should encoding even be taken into consideration? Can't I simply get what ... | **Contrary to the answers here, you DON'T need to worry about encoding ***if*** the bytes don't need to be interpreted!**
Like you mentioned, your goal is, simply, to *"get what bytes the string has been stored in"*.
(And, of course, to be able to re-construct the string from the bytes.)
**For those goals, I honest... | It depends on the encoding of your string ([ASCII](http://en.wikipedia.org/wiki/ASCII), [UTF-8](http://en.wikipedia.org/wiki/UTF-8), ...).
For example:
```
byte[] b1 = System.Text.Encoding.UTF8.GetBytes (myString);
byte[] b2 = System.Text.Encoding.ASCII.GetBytes (myString);
```
A small sample why encoding matters:
... | How do I get a consistent byte representation of strings in C# without manually specifying an encoding? | [
"",
"c#",
".net",
"string",
"character-encoding",
""
] |
The following code will not run correctly in IE7 with the latest service packs installed.
```
System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
response.Clear();
response.AddHeader("Content-Disposition", "attachment;filename=Contacts.xls");
response.ContentType = "application/octet-stream";
... | Add a Header telling IE *explicitly* to CACHE the file. IE has known bugs with not being able to properly save a file if it is sent as a no-cache file. | I had the same issue, and spent an hour being utterly frustrated. As usual microsoft IE browsers are the root of all headaches. Everything worked fine in other browsers. The solution is simple:
The user will have to adjust an IE7 setting by going to
'Tools' > 'Internet Options' > 'Security' Tab > For 'Internet' and/or ... | File download dialog IE7 disappears | [
"",
"c#",
"asp.net",
".net-3.5",
"internet-explorer-7",
"filedialog",
""
] |
I have two strings and I would like to mix the characters from each string into one bigger string, how can I do this in PHP? I can swap chars over but I want something more **complicated** since it could be guessed.
And please don't say md5() is enough and irreversible. :)
```
$string1 = '9cb5jplgvsiedji9mi9o6a8qq1';... | If you want to make a tamper-proof string which is human readable, add a secure hash to it. MD5 is indeed falling out of favour, so try [sha1](http://php.net/sha1). For example
```
$salt="secret";
$hash=sha1($string1.$string2.$salt);
$separator="_";
$str=$string1.$separator.$string2.$separator.$hash;
```
If you want ... | Use one of the [SHA](http://en.wikipedia.org/wiki/SHA_hash_functions) variants of the [hash()](http://www.php.net/hash) function. Sha2 or sha256 should be sufficient and certainly much better than anything you could come up with. | Mix two strings into one longer string PHP | [
"",
"php",
"security",
"string",
""
] |
I need to create an SQL query to insert some data into a table based on the results of a SELECT query into a local variable. My DB platform is MySQL 5.1, but I don't think that should make a difference here. Basically, what I want to do is:
```
SELECT id INTO var_name FROM table1 WHERE some_column='something' LIMIT 1;... | Try
```
INSERT INTO table2 (`number`)
SELECT id FROM table1 WHERE some_column='something' LIMIT 1
``` | You need to declare `@var_name` and then select into `@var_name`. I don't know MySQL too well but try something like this:
```
declare @var_name varchar(100);
SELECT id INTO @var_name FROM table1 WHERE some_column='something' LIMIT 1;
INSERT INTO table2 (`number`) VALUES (@var_name);
```
### Edit: Perhaps a better wa... | Problem with SELECT INTO using local variables | [
"",
"sql",
"mysql",
"mysql5",
""
] |
I have an object that is generated in one class
```
public class CreatingClass
{
public T CreateObject<T>(Dictionary<string, object> parameters) where T : IMyInterface, new()
{
....
}
public void DestroyObject(IMyInterface objectToDestroy)
{
....
}
}
```
I call this function f... | Note that you can't actually destroy an object; you are subject to the rules of garbage collection. At a push, you could check for `IDisposable` and call Dispose(),
You can use the `ref` samples provided, but I'm not sure there is much point; it is simpler just to clear the field with "obj = null;".
The `ref` usage c... | What you want is
```
public void DestroyClass(ref IMyInterface objectToDestroy)
{
....
objectToDestroy = null;
}
```
This is will set your local reference to null | C# Can I nullify an object from another class | [
"",
"c#",
".net",
"null",
""
] |
An existing process changes the status field of a booking record in a table, in response to user input.
I have another process to write, that will run asynchronously for records with a particular status. It will read the table record, perform some operations (including calls to third party web services), and update th... | There are several reasons, which were discussed on the Fog Creek forum here: <http://discuss.fogcreek.com/joelonsoftware5/default.asp?cmd=show&ixPost=173704&ixReplies=5>
The main benefit is that MSMQ can still be used when there is intermittant connectivity between computers (using a store and forward mechanism on the... | If the rate at which booking records is created is low I would have the second process periodically check the table for new bookings.
Unless you are already using MSMQ, introducing it just gives you an extra platform component to support.
If the database is heavily loaded, or you get a lot of lock contention with two... | MSMQ v Database Table | [
"",
"sql",
"msmq",
"message-queue",
""
] |
Can someone please help me out with printing the contents of an IFrame via a javascript call in Safari/Chrome.
This works in firefox:
```
$('#' + id)[0].focus();
$('#' + id)[0].contentWindow.print();
```
this works in IE:
```
window.frames[id].focus();
window.frames[id].print();
```
But I can't get anything to wor... | Put a print function in the iframe and call it from the parent.
iframe:
```
function printMe() {
window.print()
}
```
parent:
```
document.frame1.printMe()
``` | Here is my complete, cross browser solution:
In the iframe page:
```
function printPage() { print(); }
```
In the main page
```
function printIframe(id)
{
var iframe = document.frames
? document.frames[id]
: document.getElementById(id);
var ifWin = iframe.contentWindow || iframe;
iframe... | How do I print an IFrame from javascript in Safari/Chrome | [
"",
"javascript",
"iframe",
"webkit",
"printing",
""
] |
I want to overload operators < and > to allow the searching of an int value inside a BST (which ain't designed to store ints but rather words).
For those who are wondering why is this overload being done on the first place please check [C++ I'm stuck filling this BST with its proper values](https://stackoverflow.com/q... | I'm not quite sure why you want to overload > and < in this case, but perhaps I don't quite understand the question. It looks like you intend to have several different kinds of tree nodes, all of which inherit from `DataType`. If that is the case, simply add a const member function to the `DataType` base class:
```
cl... | Operator overloading doesn't really make sense here.
The member function
```
bool BST<DataType>::operator >(const int anotherId)const;
```
Basically means to compare a whole tree with an int, which is not what I think your goal was. You might want to ensure you have < defined for data type, and then also add to the ... | C++ Overloading Operator < with an int parameter (comparing to a type that isn't guaranteed to be an int) | [
"",
"c++",
"templates",
""
] |
I am using asp.net web site administration tool to manage the different roles in my project (currently Customer and Administrator). During the development, in vs 2008, its very easy to manage the roles. (Project -> Asp.Net configuration). How do I manage my roles and users when the system is deployed (IIS)? Is it possi... | Supposedly, developers are intended to admin the site using the visual studio web site administration tool. There is no out-of-the-box web interface to front-end that stuff. | This article describes how to create one, including the code that you can directly embed in your website:
<https://web.archive.org/web/20210510020726/https://aspnet.4guysfromrolla.com/articles/053007-1.aspx>
This article describes how you can run the ASP.NET configuration website administration tool on IIS:
<http://b... | Is there a ASP.NET web site administration tool in IIS? | [
"",
"c#",
"asp.net",
"visual-studio-2008",
"iis",
""
] |
I am using a hash table in JavaScript, and I want to show the values of the following in a hash table
```
one -[1,10,5]
two -[2]
three -[3, 30, 300, etc.]
```
I have found the following code. It works for the following data.
```
one -[1]
two -[2]
three-[3]
```
How do I assign one-[1,2] values to a ha... | Using the function above, you would do:
```
var myHash = new Hash('one',[1,10,5],'two', [2], 'three',[3,30,300]);
```
Of course, the following would also work:
```
var myHash = {}; // New object
myHash['one'] = [1,10,5];
myHash['two'] = [2];
myHash['three'] = [3, 30, 300];
```
since all objects in JavaScript are ha... | If all you want to do is store some static values in a lookup table, you can use an [Object Literal](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals#Object_literals) (the same format used by [JSON](http://json.org)) to do it compactly:
```
var table = { one: [1,10,5], two:... | Hash table in JavaScript | [
"",
"javascript",
"hashtable",
""
] |
I'd like to add an <option> element to a <select> element where the <option> element's text contains an HTML entity: —
In HTML, the code would look like this:
```
<select name="test" id="test">
<option value="">— Select One —</option>
</select>
```
My JavaScript code looks like this:
```
funct... | I just realized I could use a Unicode JavaScript escape:
```
e.options[0] = new Option('\u2014 Select One \u2014', '');
``` | You don't need to escape the entity - it works like this:
```
function selectOne() {
var e = document.getElementById('test');
e.options[0] = new Option('— Select One —', '');
}
``` | How do I dynamically create an <option> in JavaScript that contains an HTML entity (— ... «)? | [
"",
"javascript",
"html-entities",
"html-select",
""
] |
What is the best way to indicate that an object wants to take ownership of another object? So far, I've been using a `std::auto_ptr` in the public interface, so the client knows that the interface wants to take ownership of the passed object.
However, the latest GCC tells me `auto_ptr` is deprecated, so I wonder what ... | `boost::interprocess` is a library for interprocess communication, so I wouldn't use it for different purposes.
As discussed on this forum:
<http://objectmix.com/c/113487-std-auto_ptr-deprecated.html>
`std::auto_ptr` will be declared deprecated in the next version of the standard, where it will be recommended the us... | `std::unique_ptr` is indeed the new recommended way. With C++0x containers will become move-aware, meaning that they can handle types which are movable correctly (i.e., `std::vector<std::auto_ptr<x> >` does not work, but `std::vector<std::unique_ptr<x>>` will).
For `boost`, the `boost::interprocess` containers already... | Passing object ownership in C++ | [
"",
"c++",
""
] |
C# Which Event should I use to display data in a textbox when I select an item in a listbox?
I want to select an item in a list box (winforms) and then a textbox near by show some data related to that item but I don't know which event to use. I'll need to be able to click down the list and watch the textbox text updat... | [SelectedIndexChanged](http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selectedindexchanged.aspx) | You will want to handle either [`SelectedIndexChanged`](http://msdn.microsoft.com/en-us/library/system.windows.forms.listbox.selectedindexchanged.aspx) or [`SelectedValueChanged`](http://msdn.microsoft.com/en-us/library/system.windows.forms.listcontrol.selectedvaluechanged.aspx).
(Note that the `SelectedValueChanged` ... | C# Which Event should I use to display data in a textbox when I select an item in a listbox? | [
"",
"c#",
"listbox",
""
] |
While discussing a Java synchronization [question](https://stackoverflow.com/questions/416183/in-java-critical-sections-what-should-i-synchronize-on#416324), someone made a comment that the following snippets are not equivalent (and may compile to different bytecodes):
```
public synchronized void someMethod() {
//s... | They are equivalent in function, though the compilers I tested (Java 1.6.0\_07 and Eclipse 3.4) generate different bytecode. The first generates:
```
// access flags 33
public synchronized someMethod()V
RETURN
```
The second generates:
```
// access flags 1
public someMethod()V
ALOAD 0
DUP
MONITORENTER
MON... | I made the original comment that the statements are identical.
In both cases, the first thing that happens is that the calling thread will try to acquire the current object's (meaning, `this`') monitor.
I don't know about different bytecode, I'll be happy to hear the difference. But in practice, they are 100% identic... | Equivalent code for instance method synchronization in Java | [
"",
"java",
"synchronization",
""
] |
serial.write() method in pyserial seems to only send string data. I have arrays like [0xc0,0x04,0x00] and want to be able to send/receive them via the serial port? Are there any separate methods for raw I/O?
I think I might need to change the arrays to ['\xc0','\x04','\x00'], still, null character might pose a problem... | You need to convert your data to a string
```
"\xc0\x04\x00"
```
Null characters are not a problem in Python -- strings are not null-terminated the zero byte behaves just like another byte `"\x00"`.
One way to do this:
```
>>> import array
>>> array.array('B', [0xc0, 0x04, 0x00]).tostring()
'\xc0\x04\x00'
``` | An alternative method, without using the `array` module:
```
def a2s(arr):
""" Array of integer byte values --> binary string
"""
return ''.join(chr(b) for b in arr)
``` | Binary data with pyserial(python serial port) | [
"",
"python",
"binary",
"serial-port",
"pyserial",
""
] |
What is the correct way to close or reset a TcpClient connection?
We have software that communicates with hardware but sometimes something
goes wrong and we are no longer to communicate with it, until we restart the software.
I have tried forcing TcpClient.Close() and even setting it to null but that doesn't work.
Onl... | Given that the accepted answer is outdated and I see nothing in the other answers regarding this I am creating a new one. In .Net 2, and earlier, you had to manually close the stream before closing the connection. That bug is fixed in all later versions of `TcpClient` in C# and as stated in the doc of the [Close method... | You have to close the stream before closing the connection:
```
tcpClient.GetStream().Close();
tcpClient.Close();
```
Closing the client does not close the stream. | How to properly and completely close/reset a TcpClient connection? | [
"",
"c#",
".net",
"tcp",
""
] |
I come from the VBA world, and remember there was a `BeforeUpdate` call I could make on a combobox. Now I am in C# (and loving it) and I was wondering is there a `BeforeUpdate` call for a `ComboBox` on a Winform?
I can make an invisible textbox and store the info I need there and after the update, look at that box for... | You may consider `SelectionChangeCommited`.
From MSDN:
> SelectionChangeCommitted is raised
> only when the user changes the combo
> box selection. Do not use
> SelectedIndexChanged or
> SelectedValueChanged to capture user
> changes, because those events are also
> raised when the selection changes
> programmaticall... | One of the goodies of WF is that you can easily make your own. Add a new class to your project and paste the code below. Compile. Drop the new control from the top of the toolbox onto your form. Implement the BeforeUpdate event.
```
using System;
using System.ComponentModel;
using System.Windows.Forms;
public class M... | Is there a BeforeUpdate for a C# ComboBox on a Winform | [
"",
"c#",
"winforms",
"combobox",
"beforeupdate",
""
] |
I'm trying to bring a legacy C# .NET 1.1 application into the modern era. We use DataTables for our collections of what could have been business objects.
Given that most of the code thinks it is talking to the interface of a DataRow, what generic collection would make for the least painful transition? | if im reading your question rightly, you are asking for which container will just store a list of your Business objects and then allow you to just enumerate through the collection, or select via an index.
well I would consider looking into the List<>
where you methods would accept either IList<> (to access the index)... | Instead of changing away from the DataSet/DataTable APIs, why not subclass DataTable and DataRow into types suitable for your business logic?
The support for subclassed DataRow and DataTable objects is superb. You'll get the strong typing you want in your new code, along with the backwards compatiblity for your old co... | Best c# generics class for replacing DataTable as collection? | [
"",
"c#",
".net",
"generics",
"datatable",
""
] |
I'm trying to include JQuery in my DotNetNuke skin by adding these two lines of code at the top of my DNN skin:
```
<%
Page.ClientScript.RegisterClientScriptInclude("jquery", "http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js")
Page.ClientScript.RegisterStartupScript(Me.GetT... | Sigh. The solution is to make sure you put it in the Page\_Load() method, and not the page rendering code itself. I suppose I was too late in the page lifecycle to do what I'd wanted to do.
```
<script runat="server">
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.... | What version of DNN are you using? DNN doesn't support including jQuery unless you're using DNN version 5. [See here for more information](http://blog.theaccidentalgeek.com/post/2008/10/02/DotNetNuke-50-Now-with-jQuery.aspx) | Adding jquery include to a DotNetNuke 4.8 skin does nothing | [
"",
"javascript",
"jquery",
"dotnetnuke",
"skinning",
""
] |
I'm looking to handle image uploads on a site I'm building. All the behind the scenes stuff is fine, but creating an intuitive front-end is causing me head pains.
The problem with handling photos in a world where most people have asynchronous internet connections is the photos' size. I want each user to upload (at lea... | <http://www.jumploader.com/demo_control.html> - Free | we use this:
<http://www.aurigma.com/>
runs perfactly since a few years! (both java and activex) | Best batch photo upload applet | [
"",
"java",
"flash",
""
] |
I'm having problems deploying a simple WebServices app (like "Hello World" simple) to OC4J. The same code works fine under Jetty, but breaks in OC4J, and I'm wondering if anyone else has faced the same issue. I'm using Enterprise Manager to deploy the app, but the deployment fails with this message:
```
[Jan 23, 2... | I hate to ask the obvious, but have you looked at all the stuff for configuring OS4J and CXF together from the CXF web site?
<http://cwiki.apache.org/CXF20DOC/appserverguide.html#AppServerGuide-OC4J> | I would think its a CLASSPATH issue.
I'm not that familiar with OC4J, but how are you packaging/deploying your web-application?
You need to ensure that the CXF jar is in the `WEB-INF/lib` directory of your WAR?
Update: A little confused by your comments - if your spring config is in the `META-INF` directory of your ... | Java WebServices with Spring and OAS/OC4J | [
"",
"java",
"web-services",
"oc4j",
""
] |
I have a java script code that works fine when run through a browser, is there a way i can use that code in flash without much editing, i want the to get the input from user through flash and have the code do the computing and display the result in flash, any clues? | Well, ActionScript 1 is essentially javascript, and 2 is just some syntactical sugar on top of it. If you're creating a Flash 8 or earlier movie then you should be able to use the javascript code without much tweaking (preferably switching to use classes instead of prototype). Moving it to ActionScript 3 (for Flash 9 o... | Check out [ExternalInterface](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html), which lets you call javascript functions from actionscript, and vice versa. We use it without a problem at my work. | JavaScript in Flash | [
"",
"javascript",
"flash",
"actionscript",
""
] |
I'm working in a project where we develop php on Zend using a mySQL database and the project is about to get to a point where it will be necessary to use version control not only for the actual code but also for the database.
Also we are getting a good production server (and the actual production server will be a test... | No, I would not force standardization on IDE for all developers. You should be standardizing on coding style, not IDEs.
Having a PHP/Apache/MySQL install on a developer's machine is a good idea. The only issue you may run into is the developer's machines will probably not have the exact same configuration/runtime envi... | The thing you'd version with MySQL would be DDL and DML SQL scripts to create, alter, and load the database. Scott Ambler of "Agile Database" fame has some nice ideas about how this should be done.
Standardizing the IDE is a good thing if you have one that everyone can use. But I think the version control is necessary... | How to version control, deploy and develop php and mySQL | [
"",
"php",
"mysql",
"version-control",
""
] |
I am looking to create a video training program which records videos - via webcam, user screen capture and captures sound. Now the main problem is that I need a cross-platform (mac and windows) solutions.
I know its possible to use flash to record webcam + audio. But its not possible to record the user's screen via fl... | This is by no means a simple project. Lets get that said and out the way. There are open source (and cross-platform) options for each element, but nothing (I know of) that will do everything for you.
I think the "cleanest" option would be to use Flash for webcam and audio, as you said, and run a VNC server to send the... | This is not an answer to your question, but I strongly recommend against using video for educational programmes. Our company delivers university courses on-line, and we long ago learned that video feeds are only effective under particular scenarios. In general, a talking head is a waste of bandwidth. You're much better... | Video training program | [
"",
"java",
"apache-flex",
"flash",
"video-capture",
""
] |
After having a search around I could not find exactly what I want, I am looking to validate a form client side using the Jquery library and some form of validation plugin. I was hoping that some one could advise me on whether there are any validation plugins out there that do not use generic error messages, as my form ... | I don't know what you searched for, but the [Validation plugin](http://bassistance.de/jquery-plugins/jquery-plugin-validation/) (first google result for "jquery validation") does exactly what you want... Read [the docs that come with it](http://docs.jquery.com/Plugins/Validation). | Heres a jQuery plugin that I created and has live form validation also.
<http://www.geektantra.com/2009/09/jquery-live-form-validation/> | Jquery Live Validation | [
"",
"javascript",
"jquery",
"ajax",
"validation",
"jquery-plugins",
""
] |
I keep getting a "PermGen" error on my Tomcat 6 server.
I know what application is causing the problem, but I am not sure why it is doing so. The application is using MySQL 5 and running on JDK 6.
Are there any tools/suggestions to diagnosis or analyze the underlying issue(s) with the specific application?
Thanks | The PermGen is used to store class definitions and the interned string pool. Your code could be filling it (if it calls intern needlessly), but more likely is that the default is undersized for your application.
This is because Tomcat will load new classes every time you deploy a WAR -- or, if you are working in a dev... | Try the following JVM switches:
```
-XX:+UseConcMarkSweepGC
-XX:+CMSPermGenSweepingEnabled
-XX:+CMSClassUnloadingEnabled
```
Upping the permgen space with `-XX:MaxPermSize` just delays the problem.
Please see this comment:
[How to deal with “java.lang.OutOfMemoryError: PermGen space” error](https://stackoverflow.com... | Recurring "PermGen" in Tomcat 6 | [
"",
"java",
"memory",
"tomcat",
""
] |
I've played with boost::pool a few times in places where it seemed to me I was seriously hammering the heap with a lot of object "churn". Generally I've used `boost::object_pool`, or `boost::pool_alloc` as an STL template parameter. However the result is invariably that performance is virtually unchanged, or significan... | Memory pools are most effective imo for transaction style processing where you can allocate to the pool and then when the transaction is done, just dump it into oblivion. The real speed up isn't that each allocation is going to be much faster its that you will have near zero memory fragmentation in an extremely long ru... | Yes, 500% speed increase. The application (rather stupidly, but sometimes you have to work with what you got) copied elements from 1 std::map to another in a loop (there was some decision making in the loop), and the resulting allocations on multithreaded/process servers resulted in heap contention. I added the boost p... | Have you ever obtained a significant speedup by using boost::pool? | [
"",
"c++",
"optimization",
"memory-management",
"boost",
"malloc",
""
] |
Here's what I've been trying to do, in a nutshell:
```
class example <T extends Number>
{
private int function(T number)
{
int x = (int) number;
...
}
...
}
```
Basically, I'm trying to make it so that T is a number so I can convert it to an int inside that function. The problem is tha... | Considering that the abstract class `Number` is the superclass of classes
\* `BigDecimal`, `BigInteger`,
\* `Byte`, `Double`, `Float`,
\* `Integer`, `Long`, and `Short`...
if you want to have an int representation, you should use the `.intValue()` function.
If that is what you want to do. | For your example, I don't think you need generics. I think you can just:
```
private int func(Number n) {
return n.intValue();
}
```
If you're trying to do something with generics, I'd take that out at the moment and get just the above working, first. | Converting a generic argument to an int in java, provided that it is a number | [
"",
"java",
"generics",
""
] |
---
## The Question
My question is: **Does C# nativly support late-binding IDispatch?**
---
*Pretend* i'm trying to automate Office, while being compatible with whatever version the customer has installed.
In the .NET world if you developed with Office 2000 installed, every developer, and every customer, from now ... | You can, relativly, use late-binding IDispatch binding in C#.
<http://support.microsoft.com/kb/302902>
Here's some sample for using Excel. This way you don't need to add a needless dependancy on Microsoft's bloaty PIA:
```
//Create XL
Object xl = Activator.CreateInstance(Type.GetTypeFromProgID("Excel.Application"));... | You gotta wait for C# 4.0 to come out to get the late binding that you are looking for. Any time I need interop capabilities I switch back to VB.Net mode so I can take advantage of the COM capabilities that C# seems to lack.
The simple method that I use is creating a class in VB.Net that does the IDispatch work and th... | Does C# .NET support IDispatch late binding? | [
"",
"c#",
"late-binding",
"idispatch",
""
] |
I don't understand why `IList` implements `IEnumerable` taking in consideration that `IList` implements `ICollection` that implements `IEnumerable` also. | I assume you want to know why it declares that it implements `ICollection` as well as `IEnumerable`, when the first implies the second. I suspect the main reason is clarity: it means people don't need to look back to `ICollection` to check that that already extends `IEnumerable`.
There are other times when you need to... | `IList` only implements `IEnumerable` by associaton; i.e. it implements `IEnumerable` precisely **because** it inherits `ICollection` which is `IEnumerable`. You'd get the same with type hierarchies (although only single inheritance:
```
class Enumerable {}
class Collection : Enumerable {}
class List : Collection {}
`... | IEnumerable interface | [
"",
"c#",
"inheritance",
"ienumerable",
""
] |
I misremembered what the key was for this Templates table and therefore I added the wrong field as a foreign key. Now I need to add the foreign key and I want to populate its values based on this other field that is already populated. I started trying to do this with an update statement, but I'm not sure how to do it.
... | You can do it with a simple UPDATE query
```
UPDATE Products
SET Products.TemplateID = Templates.TemplateID
FROM Templates
WHERE Templates.TemplateName = Products.TemplateName
```
You do not need to specify the Products table in the FROM clause, nor a JOIN clause.
Just specify the Templates table in the FROM clause.
... | Here's a join solution. It's significant in that only the matched rows will be updated.
```
Update p
Set p.TemplateId = t.TemplateId
From Products p
join Templates t
On p.TemplateName = t.TemplateName
```
Here's the subquery solution. Every row of Products will be updated, even when there is no match.
```
Update... | Update Subquery Question, with foreign key | [
"",
"sql",
"stored-procedures",
"foreign-keys",
"subquery",
""
] |
Java has a lot of frameworks / APIs that help you do logging in your application:
1. The Java API has java.util.logging package.
2. Apache's Log4j.
3. Apache's Commons Logging.
4. SLF4J (logging Facade).
5. jLo.
and many many more...
I've always used the log4j library, i found it sufficient most of the time, and e... | This question seems identical to [354837](https://stackoverflow.com/questions/354837/whats-up-with-logging-in-java).
The simple answer is that you'd go for Commons Logging if you're writing a library that may be dropped into applications where you have no control over the logging, one of the other choices if not. I pe... | Commons Logging is [source of strange classloading problems](http://www.qos.ch/logging/classloader.jsp). Avoid it if you can. I prefer log4j when developing application. If you develop library/framework and you don't want to enforce logging library, choose slf4j. | Find a way in the java logging frameworks scene | [
"",
"java",
"logging",
"log4j",
"apache-commons",
""
] |
Can anyone tell me the difference between `break` and `continue` statements? | `break` leaves a loop, `continue` jumps to the next iteration. | See [**Branching Statements**](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/branch.html) for more details and code samples:
### `break`
> The break statement has two forms: labeled and unlabeled. You saw the
> unlabeled form in the previous discussion of the switch statement. You
> can also use an unlabel... | Difference between break and continue statement | [
"",
"java",
"break",
"continue",
""
] |
We have 5mb of typical text (just plain words). We have 1000 words/phrases to use as terms to search for in this text.
What's the most efficient way to do this in .NET (ideally C#)?
Our ideas include regex's (a single one, lots of them) plus even the String.Contains stuff.
The input is a 2mb to 5mb text string - all... | A naive string.Contains with 762 words (the final page) of War and Peace (3.13MB) runs in about 10s for me. Switching to 1000 GUIDs runs in about 5.5 secs.
Regex.IsMatch found the 762 words (much of which were probably in earlier pages as well) in about .5 seconds, and ruled out the GUIDs in 2.5 seconds.
I'd suggest ... | Why reinvent the wheel? Why not just leverage something like [Lucene.NET](http://incubator.apache.org/lucene.net/)? | C# Code/Algorithm to Search Text for Terms | [
"",
"c#",
".net",
"algorithm",
"search",
""
] |
I'm using the following code on Windows Vista Ultimate SP1 to query our active directory server to check the user name and password of a user on a domain.
```
public Object IsAuthenticated()
{
String domainAndUsername = strDomain + "\\" + strUser;
DirectoryEntry entry = new DirectoryEntry(_path, domainAndUsern... | If you're using .net 3.5 use this code instead.
To authenticate a user:
```
PrincipalContext adContext = new PrincipalContext(ContextType.Domain);
using (adContext)
{
return adContext.ValidateCredentials(UserName, Password);
}
```
If you need to find the user to R/W attributes to the object do this:
```
Princ... | I found that same code floating around the Internet on multiple websites and it didn't work for me. Steve Evans is probably right that if you're on .NET 3.5, you should not use this code. But if you ARE still on .NET 2.0 you can try this to Authenticate to your AD services:
```
DirectoryEntry entry = new DirectoryEntr... | Active Directory - Check username / password | [
"",
"c#",
"windows-vista",
"active-directory",
"ldap",
""
] |
I'm using the CPoint class from MFC. There is no explicitly defined assignment operator or copy constructor (AFAIK). Yet, this works:
```
CPoint p1(1, 2), p2;
p2 = p1; // p2 now is equal to p1
```
I'm assuming this is working automagically because of a compiler generated assignment operator. Correct?
If so, can I be... | This is safe - if an assignment operator wasn't meant to be supplied then the MFC designers could have made sure it wasn't available (by making it private for example).
IIRC the compiler will perform a member-by-member copy, so for a class containing POD like this, you won't have a problem. It can get messy if you hav... | Look up default copy constructor:
<http://www.fredosaurus.com/notes-cpp/oop-condestructors/copyconstructors.html>
This isn't a special thing about CPoint. | Safe to use the compiler generated assignment operator? | [
"",
"c++",
"mfc",
"variable-assignment",
""
] |
Lets say I have 5 pages: A, B, C, D, and E. I also have a horizontal menu, and each item has a light gray background.
Each menu item has a:hover that gives it a medium-gray background, but I want the active page to have a black background, so I define
```
#black {
background-color: #000;
}
```
Now when the user ... | A suggestion; don't define what your style "is", define what your style "does". Don't call it #black, instead call it .current.
Another thing to note is that ID's are meant for identifying unique elements (#header, #footer, #main, #sidebar, #navbar, etc.). Defining a repeatable item as current should be done with a cl... | When I can use PHP for a project (that is not powered by a CMS), I usually use a PHP array to construct the menu(s). It's quite easy to add, move or delete pages from an array, and by letting PHP output this as a real menu, you don't have to rewrite the same code over and over.
To specify what page should be considere... | What is the most efficient way to give the active page's menu item a "selected" id to change the CSS? | [
"",
"php",
"css",
"xhtml",
"menu",
""
] |
I am writing a program in Python, and I realized that a problem I need to solve requires me, given a set `S` with `n` elements (|S|=n), to test a function on all possible subsets of a certain order `m` (i.e. with *m* number of elements). To use the answer to produce a partial solution, and then try again with the next ... | [itertools.combinations](http://docs.python.org/library/itertools.html#itertools.combinations) is your friend if you have Python 2.6 or greater. Otherwise, check the link for an implementation of an equivalent function.
```
import itertools
def findsubsets(S,m):
return set(itertools.combinations(S, m))
```
S: The... | Using the canonical function to get the [powerset](http://en.wikipedia.org/wiki/Power_set) from the [the itertools recipe](https://docs.python.org/library/itertools.html#recipes) page:
```
from itertools import chain, combinations
def powerset(iterable):
"""
powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3)... | How can I find all the subsets of a set, with exactly n elements? | [
"",
"python",
""
] |
I've been tinkering with small functions on my own time, trying to find ways to refactor them (I recently read Martin Fowler's book *[Refactoring: Improving the Design of Existing Code](https://rads.stackoverflow.com/amzn/click/com/0201485672)*). I found the following function `MakeNiceString()` while updating another ... | 1) Use a StringBuilder, preferrably set with a reasonable initial capacity (e.g. string length \* 5/4, to allow one extra space per four characters).
2) Try using a foreach loop instead of a for loop - it may well be simpler
3) You don't need to convert the string into a char array first - foreach will work over a st... | You might want to try instantiating a `Regex` object as a class member and using the `RegexOptions.Compiled` option when you create it.
Currently, you're using the static `Split` member of `Regex`, and that doesn't cache the regular expression. Using an instanced member object instead of the static method should impro... | String Benchmarks in C# - Refactoring for Speed/Maintainability | [
"",
"c#",
"string",
"refactoring",
""
] |
Just listening to this week's [podcast](https://blog.stackoverflow.com/2009/01/podcast-38/) and thought it would be nice to group together some of your experiences where you've seen the "architecture" side of design dominate things a little more than it should.
Java often gets a bad press in this respect, and an incre... | A really good parable appeared on Joel's discussion group on this topic a few years ago. The story is called [Why I Hate Frameworks](http://discuss.joelonsoftware.com/default.asp?joel.3.219431.12). | Oh yes !
In my last job, working on a quite large project, we had an architecture team which put in place the whole framework we used. They designed a custom ORM (circa 2000, Hibernate wasnt as ubiquitous as today) and a custom RCP framework based on Swing.
The ORM wasnt all that bad. They were just overly concerned ... | Do you have any good examples of "architecture for architecture's sake"? | [
"",
"java",
"database",
"architecture",
""
] |
I am trying to have a table header, in a seperate div stay in place while a div undernearth is able to scroll al arge list of records. Both divs are in a div named Layer 3. Hereis the css file I am using:
```
#Layer3
{
position:absolute;
width: 89%;
height: 40%;
left: 10%;
top: 56%;
background-... | div name does not equal div id. #Layer3 is referencing an element with an id of Layer3. Only one element is allowed to have a given id; all ids must be unique.
Don't forget to close your tags (table).
If div#Layer3 is scrolling everything inside it then it has some overflow set. Redefine it to overflow:hidden in the ... | You've forgotten to close the `<table>` tag after your main foreach() loop. | Fixed header above scrollable table | [
"",
"php",
"html",
"css",
""
] |
I would like to write a Java terminal application that does screen manipulation. Are there any good libraries out there that allow you to manipulate the screen like curses in the \*nix/C world?
Minimal features I'm looking for are windowing and user input support.
In feature-speak, I'd like to have a region of the te... | There is [Charva](http://www.pitman.co.za/projects/charva/), which links to native code but has an api based on Swing.
The [screenshots](http://www.pitman.co.za/projects/charva/Screenshots.html) show lots of text windows, so that looks useful. | # Lanterna
I found the [*Lanterna*](https://github.com/mabe02/lanterna) library recently. Haven't had the opportunity to use it yet but it looks like a more up-to-date alternative to the others.
[](https://i.stack.imgur.com/hAB5e.png) | What's a good Java, curses-like, library for terminal applications? | [
"",
"java",
"terminal",
"console",
"console-application",
"gnu-screen",
""
] |
How do I find out if a key in a dictionary has already been set to a non-None value?
I want to increment the value if there's already one there, or set it to 1 otherwise:
```
my_dict = {}
if my_dict[key] is not None:
my_dict[key] = 1
else:
my_dict[key] += 1
``` | You are looking for [`collections.defaultdict`](https://docs.python.org/3/library/collections.html#collections.defaultdict) (available for Python 2.5+). This
```
from collections import defaultdict
my_dict = defaultdict(int)
my_dict[key] += 1
```
will do what you want.
For regular Python `dict`s, if there is no val... | I prefer to do this in one line of code.
```
my_dict = {}
my_dict[some_key] = my_dict.get(some_key, 0) + 1
```
Dictionaries have a function, get, which takes two parameters - the key you want, and a default value if it doesn't exist. I prefer this method to defaultdict as you only want to handle the case where the k... | Check if a given key already exists in a dictionary and increment it | [
"",
"python",
"dictionary",
""
] |
I was worrying about race conditions in an application I'm designing, when I was wondering about this question.
Let's say I have a large array or collection of some sort that is managed by one component of my program, let's call that component Monitor. Its job is to regularly check if the collection is "dirty", i. e. ... | No. For instance, long variables in Java are not atomic on 32-bit machines.
In addition, there's a "thread caching" issue - unless your variable is volatile or inside synchronized block, another thread may not see the change to variable value. This is true for all types of variables, not just long.
Read here: <http:/... | No, it's not atomic. [See this question](https://stackoverflow.com/questions/409688/multithreaded-paranoia#409715) for why and what to do about it. | In a multithreaded (Java or .Net) program, can I assume that copying a variable is atomic? | [
"",
"java",
".net",
"multithreading",
"race-condition",
""
] |
How could I restart or shutdown Windows using the .NET framework? | The following code will execute the shutdown command from the shell:
```
// using System.Diagnostics;
class Shutdown
{
/// <summary>
/// Windows restart
/// </summary>
public static void Restart()
{
StartShutDown("-f -r -t 5");
}
/// <summary>
/// Log off.
/// </summary>
... | I don't know a pure .NET way to do it. Your options include:
* P/Invoke the [ExitWindowsEx Win32 function](http://msdn.microsoft.com/en-us/library/aa376868(VS.85).aspx)
* Use Process.Start to run shutdown.exe as already suggested. | Restarting Windows from within a .NET application | [
"",
"c#",
".net",
"winforms",
""
] |
I have a regular .NET [Windows Forms](http://en.wikipedia.org/wiki/Windows_Forms) treeview control. The nodes are setup like this:
```
Group
--child
--child
```
If I double-click a collapsed Group node, it expands (as you'd expect) and the `NodeMouseDoubleClick` event is fired off, where my code does something if t... | The `NodeDoubleClick` is fine, but instead of using the `e.Node`, use `this.treeView1.SelectedNode`. | Double-clicking a TreeNode is a mouse gesture that is already "used" by the TreeView to collapse/expand nodes Microsoft doesn't push the UI standards as much as Apple does, and on some level it is disappointing that Microsoft has exposed NodeDoubleClick, because they are encouraging you to amend the TreeView with your ... | TreeView double-click behaviour in .NET / C# | [
"",
"c#",
".net",
"winforms",
"treeview",
"double-click",
""
] |
Are there any heap data structure implementations out there, fibonacci, binary, or binomial?
Reference: These are data structures used to implement priority queues, not the ones used to allocate dynamic memory. See <http://en.wikipedia.org/wiki/Heap_(data_structure)>
Thanks,
Dave | I don't know of any native framework implementation.
I found two implementations of binary heap ([link 1](http://www.koders.com/csharp/fidA3988613D26F26CB5D806CF1FD320C0FDA54C389.aspx?s=file:semaphore.cs), [link 2](http://weblogs.asp.net/cumpsd/archive/2005/02/13/371719.aspx)) and one implementation of binomial heap i... | Free C# implementation of heaps and many other data structures:
* [The C5 Generic Collection Library for C# and CLI](http://www.itu.dk/research/c5/)
* [Wintellect's Power Collections for .NET](http://powercollections.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=6863) | Fibonacci, Binary, or Binomial heap in c#? | [
"",
"c#",
".net",
"algorithm",
"data-structures",
""
] |
I'm trying to deserialize an array of an type unknown at compile time. At runtime I've discovered the type, but I don't know how to create an instance.
Something like:
```
Object o = Activator.CreateInstance(type);
```
which doesn't work because there is no parameterless constructor, Array doesn't seem to have any c... | Use [Array.CreateInstance](http://msdn.microsoft.com/en-us/library/system.array.createinstance.aspx). | You can use one of Array's CreateInstance overloads e.g.:-
```
object o = Array.CreateInstance(type, 10);
``` | How can I create an instance of an arbitrary Array type at runtime? | [
"",
"c#",
"reflection",
"compact-framework",
".net-2.0",
""
] |
I'm having a rather perplexing problem with the Escape key handler on a dialog box in Borland C++ Builder 5. Are there any other requirements for the Escape key to fire a cancel event (other than those I've listed below)?
1. The "Cancel" button (a TBitBtn) has its Cancel property set to true.
2. The "Cancel" button ha... | You should check all possible ways the cancel event could be blocked:
1. First of all, check if clicking the cancel button actually closes the form.
2. Then check if any other button has its Cancel property set to true.
3. After that check all key event handlers, don't forget the event handlers of the form, especially... | It may be that the Form's KeyPreview property has been set to true.
This is where the Escape key is often/likely to have been disabled.
The KeyPreview property is is also often enabled to capture [Return] key press (I.e. OnKeyPress) to advance to the next field rather than closing the form. | Borland C++ Builder 5 - Cancel Via Escape Key Not Working | [
"",
"c++",
"event-handling",
"c++builder",
""
] |
I have a Window with my user control and I would like to make usercontrol width equals window width. How to do that?
The user control is a horizontal menu and contains a grid with three columns:
```
<ColumnDefinition Name="LeftSideMenu" Width="433"/>
<ColumnDefinition Name="Middle" Width="*"/>
<ColumnDefinition Name=... | You need to make sure your usercontrol hasn't set it's width in the usercontrol's xaml file. Just delete the Width="..." from it and you're good to go!
**EDIT:** This is the code I tested it with:
*SOUserAnswerTest.xaml:*
```
<UserControl x:Class="WpfApplication1.SOAnswerTest"
xmlns="http://schemas.microsoft.com... | The Canvas in WPF doesn't provide much automatic layout support. I try to steer clear of them for this reason (HorizontalAlignment and VerticalAlignment don't work as expected), but I got your code to work with these minor modifications (binding the Width and Height of the control to the canvas's ActualWidth/ActualHeig... | How to stretch in width a WPF user control to its window? | [
"",
"c#",
".net",
"wpf",
"xaml",
"wpf-controls",
""
] |
I hope to find a way to get the value in the Nth column of a dataset.
Thus, for N = 6 I want
```
SELECT (Column6Value) from MyTable where MyTable.RowID = 14
```
Is there a way to do this in TSQL as implemented in SQL Server 2005? Thanks. | You should be able to join with the system catalog (Information\_Schema.Columns) to get the column number. | Not sure if you're at liberty to redesign the table, but if the ordinal position of the column is significant, your data is not normalized and you're going to have to jump through lots of hoops for many common tasks.
Instead of having table MyTable with Column1... ColumnN you'd have a child table of those values you f... | Help with TSQL - a way to get the value in the Nth column of a row? | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
This simple code is not producing any sound on a couple of machines that I've used to test it. I'm running the code from within Eclipse, but I've also tried using the command line to no avail.
```
public static void main(String[] args)
{
try {
Synthesizer synthesizer = MidiSystem.getSynthesizer();
... | Some installs of the JRE do not include the JavaSound soundbank.gm (in order to save space) so your code would not have a sound source to trigger on those machines.
Check for the existence of the soundbank on the machines that don't work. You can also put the soundbank in the same directory as your .class file and it ... | Have you tried to use different channel ?
May be [this discusson](http://forums.sun.com/thread.jspa?threadID=5237086) will get you closer to a solution... | Simple Java MIDI example not producing any sound | [
"",
"java",
"midi",
""
] |
I'm working on a WordPress template and need to add a hyperlink to the cartoon bubble at the top of the page. The bubble, as far as I can tell, is php. Where do I insert the href?
```
<h1><a href="<?php bloginfo('url'); ?>/"><?php bloginfo('name'); ?></a></h1>
```
The href should point to [www.ojaivalleynews.com](htt... | rashneon, look for the following HTML (search header.php for 'bubble')
```
<div id="bubble">
<p>Click for OVN Homepage!</p>
</div>
```
replace that with
```
<div id="bubble">
<p><a href="http://www.ojaivalleynews.com/">Click for OVN Homepage!</a></p>
</div>
```
@Endlessdeath - no, delightfully WordPress mixes a... | just replace the
```
<?php bloginfo('url'); ?>/
```
with
```
http://www.ojaivalleynews.com
``` | hyperlink on php | [
"",
"php",
"wordpress",
"href",
""
] |
Is C# true to C++, needing a `break;` per `case:`? *..**Default is fall-thru** - Unlike VB*
OR will it automatically break out of a case once found? *..**Default is break** - Like VB*
---
**Edit:** So it is a combination of both, ***Default is none*** - You have to specify either break; or goto; | Every *case* needs to have either a *break;* or *goto case* statement in C# | You use a `break` in C#, just like in C++. However, if you *omit* the break you must replace it with another other control transfer (e.g. `goto case 1;`).
See <http://msdn.microsoft.com/en-us/library/06tc147t(VS.71).aspx> | Does the C# switch statment need a break; | [
"",
"c#",
"switch-statement",
""
] |
I always work in windows environment and most often to write the program in C/C++.
Is it necessary to a Windows Application Programmer to remember Win32 APIs as more
as possible??
Dazza | Well, I can't say it would hurt, but I think that it's better to remember how to quickly reference the API documentation instead of actually remebering the documentation itself. That mental currency (of which there is a limited amount, of course) could be better used remembering other things to make you a better develo... | You shouldn't worry about brute memorization. You probably want to understand the basics though such as message pumps, posting messages, resource files, posting to threads, and just the general gist of how to do things in Win32. You'll probably know this after writing your first Win32 program.
In general, though, conc... | Is it necessary to remember lots of Win32 Api for a C++ programmer? | [
"",
"c++",
"windows",
""
] |
In java a class can implement Iterable which lets you use the foreach() statement and the iteration syntatic sugar:
```
for(T t:ts) ...
```
However, this does not allow you to throw exceptions on the construction for an Iterator. If you were iterating off a network, file, database etc it would be nice to be able to t... | Unfortunately you can't. There are two problems:
* The Iterator API doesn't declare any exceptions to be thrown, so you'd have to throw RuntimeExceptions (or non-Exception throwables)
* The enhanced for loop doesn't do anything to try to release resources at the end of the loop
This is very annoying. In C#, for insta... | Streams like a network aren't really iterable in the traditional sense. Data can come through at any time, so it doesn't make sense to have a for each loop.
For a file read, or a DB snapshot (like a select query) there's no reason you can't take that data, segment it into logical chunks and implement an iterable inter... | In Java how would you write the equivalent of Iterable which could throw exceptions? | [
"",
"java",
"exception",
""
] |
I'm trying get values from a GridView using the following code:
```
foreach (GridViewRow row in this.dgvEstudios.Rows)
{
var xy = row.Cells[1].Text;
}
```
Always get a an empty string (`""`) as the value returned from `.Text`, why does this happen? I have set `EnableViewState` to `true` | The cell might have controls inside it (e.g. LiteralControl or an HyperLink). This is what you should be looking for.
`row.Cells[1].Controls` collection, you should look for. | If there are controls in each cell you will need to get the value like this:
```
Label lblEmailAddress = GridView.Rows[e.CommandArgument].FindControl("lblEmailAddress");
string Email = lblEmailAddress.Text;
```
in that case it it the control in the cell that has the value not the cell iteslf. | Can't get values from rows/cells in GridView | [
"",
"c#",
"asp.net",
"gridview",
""
] |
By default when Django runs against sqlite backend it creates a new in memory database for a test. That means for every class that derives from unittest.TestCase, I get a new database. Can this be changed so that it is cleared before every test method is run?
Example: I am testing a manager class that provides additio... | Use `django.test.TestCase` not `unittest.TestCase`. And it works in all major versions of Django! | You can use the `tearDown` method. It will be called after your test is run. You can delete all Blahs there. | Cleaning up a database in django before every test method | [
"",
"python",
"django",
"unit-testing",
"django-models",
""
] |
I'm porting an existing (mostly) cross-platform application to WinCE 4.2. The current entry point for the function is
```
int main(int argc, char *argv[]){}
```
I would like to keep this part as-is, and have the WinCE entry point simply call it. I believe something like the following should work:
```
int WINAPI WinM... | Thank you both for your helpful answers. I wrote the following, which works as well as we need it for now. Only our code will be calling this executable, and never with quotes, although that wouldn't be too hard to add. Also, it might not do well if there is more than one space between arguments, but again, we don't ha... | The really simple way to do this is to just change the linker entry point for your project and use the main(...) function.
Open up the project Properties dialog then go down to "Linker->Advancedd" and set the "Entry Point" value based on the following:
if your entry point is this:
```
int main(int argc, char *argv[]... | Normal main to WinCE main | [
"",
"c++",
"windows-ce",
"evc4",
""
] |
I'm trying to formalise the usage of the "out" keyword in c# for a project I'm on, particularly with respect to any public methods. I can't seem to find any best practices out there and would like to know what is good or bad.
Sometimes I'm seeing some methods signatures that look like this:
```
public decimal CalcSom... | There is a reason that one of the static code analysis (=FxCop) rules points at you when you use `out` parameters. I'd say: only use `out` when really needed in interop type scenarios. In all other cases, simply do not use `out`. But perhaps that's just me? | This is what the [.NET Framework Developer's Guide](http://msdn.microsoft.com/en-us/library/ms229053(VS.80).aspx) has to say about out parameters:
> **Avoid using out or reference parameters.**
>
> Working with members
> that define out or reference
> parameters requires that the developer
> understand pointers, subtl... | Best practice of using the "out" keyword in C# | [
"",
"c#",
".net",
""
] |
I'm setting up a public site and the first thing on my mind is SQL injection. I have some text fields I'm saving and am using linq to update/write to the database. Am I safe using linq?
This example is creating the user account.
```
Data.MemberRegistrationDataContext context = new MemberRegistrationDataContext();
Dat... | Yes, LINQ will help stop SQL injection.
> LINQ to SQL passes all data to the
> database via SQL parameters. So,
> although the SQL query is composed
> dynamically, the values are substitued
> server side through parameters
> safeguarding against the most common
> cause of SQL injection attacks.
Also, see [Eliminate S... | You're good to go. Linq does parameterize the data it sends to the database.
Use the Log property to check out what's happening: `dc.Log = Console.Out;` | Will using LINQ to SQL help prevent SQL injection | [
"",
"c#",
"asp.net",
"linq",
"linq-to-sql",
""
] |
I have a simple question related to one-line programming. First an example:
```
function test(a)
{
var b=a.toString();
return b.replace("a","b");
}
```
It's very simple (this function is, of course, useless), but the question here is little more complicated: What if I was to do this in one line? I have my thoug... | Your example may be over-complicating a simple operation but the technique you are demonstrating is called method 'chaining'. It's a perfectly valid form and can actually be used to make code more readable when the intermediate results are not needed or meaningful.
My current favorite example of this is the wonderful ... | You're needlessly complicating the operation. You don't need to declare anything at all.
```
function test(a) {
return a.toString().replace("a","b");
}
```
There shouldn't be a hit to performance or memory with this.
However, if you were to use a closure, you could potentially run into memory issues.
Assigning a va... | Javascript local variable technique | [
"",
"javascript",
"variables",
"local",
""
] |
What is the best way to sniff network packets using Python?
I've heard from several places that the best module for this is a module called Scapy, unfortunately, it makes python.exe crash on my system. I would assume that it's just a problem with how I installed it, except that many other people have told me that it d... | Using [pypcap](http://code.google.com/p/pypcap/):
```
import dpkt, pcap
pc = pcap.pcap() # construct pcap object
pc.setfilter('icmp') # filter out unwanted packets
for timestamp, packet in pc:
print dpkt.ethernet.Ethernet(packet)
```
output sample:
```
Ethernet(src='\x00\x03G\xb2M\xe4', dst='\x00\x03G\x06h\x... | # The hard way
You can sniff all of the IP packets using a raw socket.
Raw socket is a socket the sends and receives data in binary.
Binary in python is represented in a string which looks like this `\x00\xff`... every `\x..` is a byte.
To read an IP packet you need to analyze the received packet in binary accor... | Packet sniffing in Python (Windows) | [
"",
"python",
"sniffing",
"sniffer",
""
] |
On my computer, I'm using a custom adblock based on HOSTS redirection (so I can have adblock in Chrome). I'm running IIS on my machine, so I have a custom blank 404 error that displays when an `iframe`-based ad is displayed on a page.
I've modified my 404 error to inherit its background color from its parent so that t... | Shouldn't be possible, as sites within iframes can be external site. Allowing them to manipulate the environment they're displayed in would be a browser security risk.
You'd be better off using an adblocking proxy. | If I understand you correctly, you're saying you want your 404 page to trigger a collapse of the iframe when it loads inside it. The easiest way to do this is to create a function in the parent page, and then call it from the 404 when it loads.
For example, if your iframe has the id "advertFrame" you could add the fol... | Altering IFrame attributes from within the IFrame source. Is it possible? | [
"",
"javascript",
"iframe",
"adblock",
""
] |
I am looking for a light-web embeddable web server for .NET.
I need it to fake a SOAP web-service for automated testing, so it is a big plus if it supports ASP.NET web-services or another easy way to create SOAP web-services. Extra bonus points for quick startup and shutdown and multiple simultaneous instances on diff... | You can try the [Cassini Web Server](https://code.google.com/p/cassini/).
---
Edit
And now 6 1/2 years later, I'd recommend [IIS Express](http://www.iis.net/learn/extensions/introduction-to-iis-express/iis-express-overview) instead. | Check out the [XSP web server](http://www.mono-project.com/ASP.NET) that is bundled with mono. | Embedded (ASP.NET) web server | [
"",
"c#",
".net",
"asp.net",
"automated-tests",
"embeddedwebserver",
""
] |
I need a WeifenLuo replacement that'll run on both .NET and Mono, on Windows, Linux and Mac, preferrably licensed under the MIT license.
I'd appreciate if the API was similar to WeifenLuo's, but I understand that such may not be available.
Also, since I couldn't find anything on Google, I believe this might not exist.... | I have been wanting the same thing. I have been testing a basic layout system for win forms and found that the mono Mac version of WinForms is not 100% complete like drag and drop has not been implemented and is slow.
From my own searching GTK# has the best support across all platforms. The other way is to split the U... | It is possible to disable all PInvoke to Win32 API when running on Mono. The price you pay is to lose drag and drop support on Mono/Linux, which may be acceptable in some cases.
**Edited: <http://www.lextm.com/2012/05/a-call-to-the-community-dockpanel-suite-history-and-future-2/> A fork of DPS is now hosted on GitHub,... | Looking for fully managed WeifenLuo(DockPanel Suite) replacement or hints on implementing one | [
"",
"c#",
"winforms",
"mono",
"dockpanel-suite",
""
] |
I have a search query that I'm inheriting and attempting to optimize. I am curious to hear if anyone has any best practices and recommendations for such. The production server is still SQL Server 2000 also.
The query is an advanced customer search stored procedure that accepts 5 different search criteria parameters (i... | isn't this whole line
```
AND (@Zip = '' OR a.Zip = @Zip OR a.Zip LIKE @Zip + '%')
```
the same as this
```
AND (a.Zip LIKE @Zip + '%')
```
for sure
```
AND (a.Zip LIKE @Zip + '%')
```
it is the same as
```
a.Zip = @Zip OR a.Zip LIKE @Zip + '%'
``` | You can definitely clean up a lot of the redundancy in your code as SQLMenace pointed out as a start.
Another thing is, ORDER BY shouldn't be used with an INSERT..SELECT. ORDER BY is meaningless in this context. People occasionally use it to force an IDENTITY column to behave a certain way, but that's a bad habit IMO.... | What are some best practices for optimizing multiple column LIKE SQL queries? | [
"",
"sql",
"search",
"optimization",
"sql-like",
""
] |
I'm working in C++ and I need to know if a scalar value (for instance a `double`) is "defined" or not. I also need to be able to "undef" it if needed:
```
class Foo {
public:
double get_bar();
private:
double bar;
void calculate_bar() {
bar = something();
}
};
double Foo::get_bar() {
if (... | As the other answers says, C++ doesn't have this concept. You can easily work around it though.
Either you can have an undefined value which you initialize bar to in the constructor, typically -1.0 or something similar.
If you know that calculate\_bar never returns negative values you can implement the undefined func... | As others pointed out, there is nothing like an "undefined" state. But you may want to look into [boost.optional](http://www.boost.org/doc/libs/1_35_0/libs/optional/doc/html/boost_optional/examples.html#boost_optional.examples.optional_local_variables) | Check for value definedness in C++ | [
"",
"c++",
"undef",
""
] |
I've got alot of projects and I don't have a master solution with everything in it. The reason I want one is for refactoring.
So I was wondering if anybody knew an automatic way to build a solution file. Manually adding all the projects just isn't feasible. | And I have now updated my utility (mentioned above) to support creation of solution folders:
<http://bloggingabout.net/blogs/vagif/archive/2009/12/03/utility-to-generate-solution-files-can-now-create-solution-folders.aspx> | In 2018, you can use [`dotnet sln`](https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-sln) command to add project to an existing solution and [`dotnet new sln`](https://learn.microsoft.com/en-us/dotnet/core/tools/dotnet-new) to create a new one.
To add all projects from current folder use these commands in Po... | Generate Solution File From List of CSProj | [
"",
"c#",
"visual-studio-2008",
""
] |
Does anybody know of an easy to implement site search engine for asp.net? The less complicated the better.
Probably just needs a crawler and backend to store results. Some sort of API to get the search results back would be handy but I can get it straight from the DB as well. | [Dot Lucene](http://incubator.apache.org/lucene.net/) (AKA Lucene.net)
You can find a good sample and explanation in [CodeProject](http://www.codeproject.com/KB/aspnet/DotLuceneSearch.aspx) | Take a look at [Lucene.Net](http://incubator.apache.org/lucene.net/). It is a .Net port of a very mature Java search engine. I've heard very good things about the .Net version. | Open Source (Free) ASP.NET Site Seacrch | [
"",
"c#",
"asp.net",
"search",
""
] |
I'm tasked with creating a datawarehouse for a client. The tables involved don't really follow the traditional examples out there (product/orders), so I need some help getting started. The client is essentially a processing center for cases (similar to a legal case). Each day, new cases are entered into the DB under th... | I suggest you check out Kimball's books, particularly [this one](https://rads.stackoverflow.com/amzn/click/com/0471200247), which should have some examples to get you thinking about applications to your problem domain.
In any case, you need to decide if a dimensional model is even appropriate. It is quite possible to ... | The fact table is the case event and it is 'factless' in that it has no numerical value. The dimensions would be time, event type, case and maybe some others depending on what other data is in the system.
You need to consolidate the event tables into a single fact table, labelled with an 'event type' dimension. The th... | Setting up Dim and Fact tables for a Data Warehouse | [
"",
"sql",
"multidimensional-array",
"data-warehouse",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.