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 remix).
I want to pass in a string in this format `{getThis}`, and be returned the string `getThis`. Could anyone be of assistance in helping to stick to my new year's resolution?
---
Related questions on Stack Overflow:
* [How can one turn regular quotes (i.e. ', ") into LaTeX/TeX quotes (i.e. `', ``'')](https://stackoverflow.com/questions/346567/how-can-one-turn-regular-quotes-i-e-into-latex-tex-quotes-i-e)
* [Regex: To pull out a sub-string between two tags in a string](https://stackoverflow.com/questions/1237/regex-to-pull-out-a-section-a-substing-from-a-string-between-two-tags)
* [Regex to replace all \n in a String, but no those inside [code] [/code] tag](https://stackoverflow.com/questions/328387/regex-to-replace-all-n-in-a-string-but-no-those-inside-code-code-tag) | 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 minus one. This works because the position is zero-based, i.e. `g.length-1` is the last position.
For readers other than the original poster: If it *has* to be a regex, use `/{([^}]*)}/` if you want to allow empty strings, or `/{([^}]+)}/` if you want to only match when there is at least one character between the curly braces. Breakdown:
* `/`: start the regex pattern
+ `{`: a literal curly brace
- `(`: start capturing
* `[`: start defining a class of characters to capture
+ `^}`: "anything other than `}`"
* `]`: OK, that's our whole class definition
* `*`: any number of characters matching that class we just defined
- `)`: done capturing
+ `}`: a literal curly brace must immediately follow what we captured
* `/`: end the regex pattern | 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 way of not being greedy) | 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 results in some very subtle, hard-to-find bugs. Especially during development, when class layout changes often. But if it has not been explicitly specified, it will change and the deserialization will break loudly, mostly likely solved by purging the repository.
Changing it when should not have would occur almost only when it is implicit. This is the rare case where class layout has changed but we still want to deserialize from the old serialized blobs. This will likely be caught during QA (*Strange errors after upgrade from 5.2 to 5.2.1, see attached stack trace*) and can be trivially fixed by setting a explicit value.
Comments? | 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.Vouchers') IS NOT NULL
DROP TABLE dbo.Vouchers
IF OBJECT_ID('dbo.Employees') IS NOT NULL
DROP TABLE dbo.Employees
GO
CREATE TABLE Employees
(
ObjectID INT NOT NULL PRIMARY KEY IDENTITY
)
CREATE TABLE Vouchers
(
ObjectID INT NOT NULL PRIMARY KEY IDENTITY,
IssuedBy INT,
ReceivedBy INT,
ApprovedBy INT,
CONSTRAINT fk_Vouchers_Employees_IssuedBy FOREIGN KEY (IssuedBy)
REFERENCES Employees (ObjectID)
ON UPDATE CASCADE
ON DELETE NO ACTION,
CONSTRAINT fk_Vouchers_Employees_ReceivedBy FOREIGN KEY (ReceivedBy)
REFERENCES Employees (ObjectID)
ON UPDATE CASCADE
ON DELETE NO ACTION,
CONSTRAINT fk_Vouchers_Employees_ApprovedBy FOREIGN KEY (ApprovedBy)
REFERENCES Employees (ObjectID)
ON UPDATE CASCADE
ON DELETE NO ACTION
)
```
But an error is thrown:
```
Msg 1785, Level 16, State 0, Line 7
Introducing FOREIGN KEY constraint 'fk_Vouchers_Employees_ReceivedBy' on table 'Vouchers' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
```
I don't have an idea of what efficient solution is available here. The requirements on the relationship is that: whenever an Employee is deleted, the Voucher that references some of its columns to the Employee does not get deleted (ON DELETE CASCADE is not an option). Instead, the values of the columns (IssuedBy, ReceivedBy and/or ApprovedBy) that are referenced to the deleted Employee should be set to NULL (since the columns are NULLABLE).
Many thanks! | 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 matching record needs to exist. Or not. It's an implementation issue as to whether or not you care to enforce the design.
However, the violations you describe are assumed at your peril. The fact that you're asking this question suggests you may not fully appreciate all the ways these choices can lead into the swamp.
I think the error may be a consequence of the fact that more than one of the three might refer to the same employee.
BTW, I've in very few cases ever found it necessary to delete records in such a fashion that CASCADES are useful. Usually that would be used to prevent the database from being too big; and database capacity is less and less an issue over time. | 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 independant get\_ set\_ as a general solution. Thanks all for the sanity test.* | 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 are created, so you could simply show those methods (to make your UML language independent - e.g. make your UML equally applicable to a VB.NET developer)
... or as you have suggested, introduce your own stereotype! | 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 |
+------------------------+
```
«property» being a custom stereotype derived from «operator».
Ugly, I know. But it works, and it's clear. I do constructors the same way. | 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 I edit the code, it creates an ambiguity between those extensions, so that I cannot use `OrderBy`, for instance. How could I solve this? I would like to use the core [LINQ](http://en.wikipedia.org/wiki/Language_Integrated_Query) extensions, and not the ones from ReSharper.
I get the following error when trying to compile:
> The call is ambiguous between the
> following methods or properties:
> '`System.Linq.Enumerable.OrderBy<string,int>(System.Collections.Generic.IEnumerable<string>`,
> `System.Func<string,int>)' and
> 'System.Linq.Enumerable.OrderBy<string,int>(System.Collections.Generic.IEnumerable<string>,
> System.Func<string,int>`)'
**EDIT:** I tried the suggestion below, unfortunately without luck. In the meanwhile, I "solved" the problem by removing references to `System.Core`. This way I could use the extensions provided by ReSharper DLL files.
I [uploaded a sample program](http://a.imagehost.org/download/0589/ClassLibrary1) where I just imported the ReSharper DLL files I needed. I changed the alias of `System.Core` to `SystemCore`, added the `extern alias` directive, but it still didn't work. If I missed something, please let me know.
P.S. The references are to ReSharper v4.1 DLL files installed in the default directroy in `"C:\Program Files\JetBrains\ReSharper\v4.1\..."`. | 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,SystemCore" (or just "SystemCore" if it's blank to start with).
Then in your code, write:
```
extern alias SystemCore;
using SystemCore::System.Linq;
```
That will make all the relevant types etc in System.Core.dll's System.Linq namespace available. The name "SystemCore" here is arbitrary - you could call it "DotNet" or something else if that would make it clearer for you. | 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(startRemovingAtThisIndex, numberOfItemsToRemove);
```
Or, you can perform a "remove" using the [jQuery.grep](http://docs.jquery.com/Utilities/jQuery.grep) util:
```
var valueToRemove = 'someval';
theArray = $.grep(theArray, function(val) { return val != valueToRemove; });
``` | 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`, but it's a many to many relationship and `CompanyRolesToUsers` is the junction table.
We already have most of our site built, and we already have most of the filtering working by building Expressions using a PredicateExtensions class.
The code for the straightforward filters looks something like this:
```
if (!string.IsNullOrEmpty(TextBoxLastName.Text))
{
predicateAnd = predicateAnd.And(c => c.LastName.Contains(
TextBoxLastName.Text.Trim()));
}
e.Result = context.Users.Where(predicateAnd);
```
I'm trying to add a predicate for a subselect in another table. (`CompanyRolesToUsers`)
What I'd like to be able to add is something that does this:
```
int[] selectedRoles = GetSelectedRoles();
if( selectedRoles.Length > 0 )
{
//somehow only select the userid from here ???:
var subquery = from u in CompanyRolesToUsers
where u.RoleID in selectedRoles
select u.UserId;
//somehow transform this into an Expression ???:
var subExpression = Expression.Invoke(subquery);
//and add it on to the existing expressions ???:
predicateAnd = predicateAnd.And(subExpression);
}
```
Is there any way to do this? It's frustrating because I can write the stored procedure easily, but I'm new to this LINQ thing and I have a deadline. I haven't been able to find an example that matches up, but I'm sure it's there somewhere. | 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 portion of the question:
```
predicateAnd = predicateAnd.And(c => c.LastName.Contains(
TextBoxLastName.Text.Trim()));
```
I strongly recommend extracting the string from the textbox before authoring the query.
```
string searchString = TextBoxLastName.Text.Trim();
predicateAnd = predicateAnd.And(c => c.LastName.Contains( searchString));
```
You want to maintain good control over what gets sent to the database. In the original code, one possible reading is that an untrimmed string gets sent into the database for trimming - which is not good work for the database to be doing. | 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 CompanyRolesToUsers c
on u.Id = c.UserId --explicit "join" statement, no diff from above, just preference
where u.lastname like '%fra%'
and c.CompanyRoleId in (2,3,4)
```
That being said, in LINQ it would be
```
from u in Users
from c in CompanyRolesToUsers
where u.Id == c.UserId &&
u.LastName.Contains("fra") &&
selectedRoles.Contains(c.CompanyRoleId)
select u
```
or
```
from u in Users
join c in CompanyRolesToUsers
on u.Id equals c.UserId
where u.LastName.Contains("fra") &&
selectedRoles.Contains(c.CompanyRoleId)
select u
```
Which again, are both respectable ways to represent this. I prefer the explicit "join" syntax in both cases myself, but there it is... | 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 clarified your question to say that you come from a C background. In Python, there are no increment operators like `++` and `--` in C, which was probably the source of your confusion. To increment or decrement a variable `i` or `j` in Python use this style:
```
i += 1
j -= 1
``` | 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.
```
+1
```
-> 1
```
++1
```
-> 1
This is the same as +(+(1))
```
1+++2
```
-> 3
Because it's the same as 1 + (+(+(2))
Likewise you can do --1 to mean - (-1) which is +1.
```
--1
```
-> 1
For completeness there is no \* unary opeartor. So \*1 is an error. But there is a \*\*
operator which is power of, it takes 2 arguments.
```
2**3
```
-> 8 | 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 if I want the method to be extended and it makes it clear which methods are extended by base classes.
On the other hand, is using private somehow antisocial, in that it impedes a theoretical future developer from extending my code without modification? | 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 that you should expose only what you really need to. The exception would be a library or toolkit, where you'll expect users to want to extend (in the general sense) your code in ways which you would never foresee. In which case making well-chosen methods protected can be seen as providing flex-points. | 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 mainly that of lazy loading. Since there can be several HTTP requests between the initialization and actually loading lazy collections, a session per transaction is out of the question. A long-lived session (one per application) doesn't work well either, because once a transaction hits a snag and throws an exception, the whole session is invalidated, thus the lazy loaded objects break. Then there's all kinds of stuff that just don't work for us (like implicit data persisting of data from outside an initialized transaction).
My poor explanations aside, the bottom line is that Hibernate does magic we don't like. It seems like TopLink isn't any better, it also being written on top of EJB.
So, a stateless persistence layer (or even bright-enough object-oriented database abstraction layer) is what we would need the most.
Any thoughts, or am I asking for something that doesn't exist?
**Edit:** I'm sorry for my ambiguous terminology, and thank you all for your corrections and insightful answers. Those who corrected me, you are all correct, I meant JPA, not EJB. | 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 framework.
Specifically, you're trying to keep transactions alive over several HTTP requests.
Naturally, most every common idiom is that each request is in itself one or more transactions, rather than each request being a portion of a larger transaction.
There is also obvious confusion when you used the term "stateless" and "transaction" in the same discussion, as transactions are inherently stateful.
Your big issue is simply managing your transactions manually.
If you transaction is occurring over several HTTP requests, AND those HTTP requests happen to be running "very quicky", right after one another, then you shouldn't really be having any real problem, save that you WILL have to ensure that your HTTP requests are using the same DB connection in order to leverage the Databases transaction facility.
That is, in simple terms, you get a connection to the DB, stuff it in the session, and make sure that for the duration of the transaction, all of your HTTP requests go through not only that same session, but in such a way that the actual Connection is still valid. Specifically, I don't believe there is an off the shelf JDBC connection that will actually survive failover or load balancing from one machine to another.
So, simply, if you want to use DB transactions, you need to ensure that your using the same DB Connection.
Now, if your long running transaction has "user interactions" within it, i.e. you start the DB transaction and wait for the user to "do something", then, quite simply, that design is all wrong. You DO NOT want to do that, as long lived transactions, especially in interactive environments, are just simply Bad. Like "Crossing The Streams" Bad. Don't do it. Batch transactions are different, but interactive long lived transactions are Bad.
You want to keep your interactive transactions as short lived as practical.
Now, if you can NOT ensure you will be able to use the same DB connection for your transaction, then, congratulations, you get to implement your own transactions. That means you get to design your system and data flows as if you have no transactional capability on the back end.
That essentially means that you will need to come up with your own mechanism to "commit" your data.
A good way to do this would be where you build up your data incrementally into a single "transaction" document, then feed that document to a "save" routine that does much of the real work. Like, you could store a row in the database, and flag it as "unsaved". You do that with all of your rows, and finally call a routine that runs through all of the data you just stored, and marks it all as "saved" in a single transaction mini-batch process.
Meanwhile, all of your other SQL "ignores" data that is not "saved". Throw in some time stamps and have a reaper process scavenging (if you really want to bother -- it may well be actually cheaper to just leave dead rows in the DB, depends on volume), these dead "unsaved" rows, as these are "uncomitted" transactions.
It's not as bad as it sounds. If you truly want a stateless environment, which is what it sounds like to me, then you'll need to do something like this.
Mind, in all of this the persistence tech really has nothing to do with it. The problem is how you use your transactions, rather than the tech so much. | 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 V3 Final.
JPA is good because you can use it both inside and outside a container. I've written Swing clients that use JPA to good effect. It doesn't have the same stigma and XML baggage that EJB 2.0/2.1 came with.
If you're after an even lighter weight solution then look no further than [ibatis](http://ibatis.apache.org/), which I consider to be my persistence technology of choice for the Java platform. It's lightweight, relies on SQL (it's amazing how much time ORM users spend trying to make their ORM produce good SQL) and does 90-95% of what JPA does (including lazy loading of related entities if you want).
Just to correct a couple of points:
* JPA is the peristence layer of EJB, not built on EJB;
* Any decent JPA provider has a whole lot of caching going on and it can be hard to figure it all out (this would be a good example of "Why is Simplicity So Complex?"). Unless you're doing something you haven't indicatd, exceptions shouldn't be an issue for your managed objects. Runtime exceptions typically rollback transactions (if you use Spring's transaction management and who doesn't do that?). The provider will maintain cached copies of loaded or persisted objects. This can be problematic if you want to update outside of the entity manager (requiring an explicit cache flush or use of `EntityManager.refresh()`). | 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 way to do this with checkboxes?
Can the normal ASP Validators handle this, or would I need to create an integer value like mentioned above, hidden somewhere and use a RangeValidator do a test to make sure THAT value is never zero? | 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 are below average mark?
How many more than average mark?
And reverse.
How many students' names start with T and end with T in a file?
(all results should be placed in an out file)
---
I've done it all with no errors but its not writing on the file can any one tell me why
and please I don't want to use any new methods as (LINQ and other advance stuff).
```
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace Exam_Ex
{
class Program
{
public static int[] ReadFile(string FileName, out string[] Name, out char[] Gender)
{
Name = new string[1];
int[] Mark = new int[1];
Gender = new char[1];
if (File.Exists(FileName))
{
FileStream Input = new FileStream(FileName, FileMode.Open, FileAccess.Read);
StreamReader SR = new StreamReader(Input);
string[] Current;
int Counter = 0;
string Str = SR.ReadLine();
while (Str != null)
{
Current = Str.Split(',');
Name[Counter] = Current[0];
Mark[Counter] = int.Parse(Current[2]);
Gender[Counter] = char.Parse(Current[1].ToUpper());
Counter++;
Array.Resize(ref Name, Counter + 1);
Array.Resize(ref Mark, Counter + 1);
Array.Resize(ref Gender, Counter + 1);
Str = SR.ReadLine();
}
}
return Mark;
}
public static int MostFreq(int[] M, out int Frequency)
{
int Counter = 0;
int Frequent = 0;
Frequency = 0;
for (int i = 0; i < M.Length; i++)
{
Counter = 0;
for (int j = 0; j < M.Length; j++)
if (M[i] == M[j])
Counter++;
if (Counter > Frequency)
{
Frequency = Counter;
Frequent = M[i];
}
}
return Frequent;
}
public static int Avg(int[] M)
{
int total = 0;
for (int i = 0; i < M.Length; i++)
total += M[i];
return total / M.Length;
}
public static int AvgCond(char[] G, int[] M, char S)
{
int total = 0;
int counter = 0;
for (int i = 0; i < G.Length; i++)
if (G[i] == S)
{
total += M[i];
counter++;
}
return total / counter;
}
public static int BelowAvg(int[] M, out int AboveAvg)
{
int Bcounter = 0;
AboveAvg = 0;
for (int i = 0; i < M.Length; i++)
{
if (M[i] < Avg(M))
Bcounter++;
else
AboveAvg++;
}
return Bcounter;
}
public static int CheckNames(string[] Name, char C)
{
C = char.Parse(C.ToString().ToLower());
int counter = 0;
string Str;
for (int i = 0; i < Name.Length - 1; i++)
{
Str = Name[i].ToLower();
if (Str[0] == C || Str[Str.Length - 1] == C)
counter++;
}
return counter;
}
public static void WriteFile(string FileName, string[] Output)
{
FileStream FS = new FileStream(FileName, FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter SW = new StreamWriter(FS);
for (int i = 0; i < Output.Length; i++)
SW.WriteLine(Output[i]);
}
static void Main(string[] args)
{
int[] Mark;
char[] Gender;
string[] Name;
string[] Output = new string[8];
int Frequent, Frequency, AvgAll, MaleAvg, FemaleAvg, BelowAverage, AboveAverage, NamesCheck;
Mark = ReadFile("c:\\IUST1.txt", out Name, out Gender);
Frequent = MostFreq(Mark, out Frequency);
AvgAll = Avg(Mark);
MaleAvg = AvgCond(Gender, Mark, 'M');
FemaleAvg = AvgCond(Gender, Mark, 'F');
BelowAverage = BelowAvg(Mark, out AboveAverage);
NamesCheck = CheckNames(Name, 'T');
Output[0] = "Frequent Mark = " + Frequent.ToString();
Output[1] = "Frequency = " + Frequency.ToString();
Output[2] = "Average Of All = " + AvgAll.ToString();
Output[3] = "Average Of Males = " + MaleAvg.ToString();
Output[4] = "Average Of Females = " + FemaleAvg.ToString();
Output[5] = "Below Average = " + BelowAverage.ToString();
Output[6] = "Above Average = " + AboveAverage.ToString();
Output[7] = "Names With \"T\" = " + NamesCheck.ToString();
WriteFile("d:\\output.txt", Output);
}
}
}
``` | 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.WriteLine(Output[i]);
}
}
```
This will call `Dispose` automatically, which will close the appropriate resource. Manually calling `Close` just at the end of the method is vulnerable to exceptions - you'd normally want to put it in a `finally` block, but that's what the `using` statement does automatically. | 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 for "generic array creation".
A good explanation I've seen regarding disallowing generic arrays is [this one](http://www.ibm.com/developerworks/java/library/j-jtp01255.html), arguing that since arrays are covariant and generics are not you could subvert the generic typing if you allowed generic arrays.
Leaving aside the argument over whether the language should go to the extreme lengths of creating this kind of complicated inconsistency in the treatment of generics to keep you from shooting yourself no matter how hard you try (and if anyone knows of any good discussions on the relative merits/demerits of the issue please post, I'd be interested to see the arguments), why should statement (1) be allowed if (2) isn't? | 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=324.msg1131.html> | 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
lists[0].add(new String(""));
}
}
```
Statement 3 is possible, statement 4 will lead to a compiler error. | 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 to count the number of times that the event WOULD have fired, and then letting the last iteration do all the actual work.
Here's the code I started with. **The big catch:** I need the "do fancy calculations" to be in the same thread as the calling events due to items out of my control.
EDIT: I *know* that this code doesn't work. The Join() blocks the current thread which negates the entire purpose of creating the thread. My question is : How do I do something LIKE this.
My biggest problem isn't creating the thread. It's that my "do fancy" has to be in the same thread.
```
void IncrPaintQueue()
{
PaintQueue++;
Thread.Sleep(100);
}
int PaintQueue = 0;
private void SegmentList_SelectedIndexChanged(object sender, EventArgs e)
{
// We need to know how many threads this may possibly spawn.
int MyQueue = PaintQueue;
// Start a thread to increment the counter.
Thread Th = new Thread(IncrPaintQueue);
Th.IsBackground = true;
Th.Start();
Th.Join();
// if I'm not the last thread, then just exit.
// The last thread will do the right calculations.
if (MyQueue != PaintQueue - 1)
return;
// Reset the PaintQueue counter.
PaintQueue = 0;
// ... do fancy calculations here...
}
``` | 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 than once
> within the delay period, then the
> original is ignored, but after the
> delay has expired, the logic is
> executed.
>
> Like this:
```
public class SelectionEndListView : ListView
{
private System.Windows.Forms.Timer m_timer;
private const int SELECTION_DELAY = 50;
public SelectionEndListView()
{
m_timer = new Timer();
m_timer.Interval = SELECTION_DELAY;
m_timer.Tick += new EventHandler(m_timer_Tick);
}
protected override void OnSelectedIndexChanged(EventArgs e)
{
base.OnSelectedIndexChanged(e);
// restart delay timer
m_timer.Stop();
m_timer.Start();
}
private void m_timer_Tick(object sender, EventArgs e)
{
m_timer.Stop();
// Perform selection end logic.
Console.WriteLine("Selection Has Ended");
}
}
``` | 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 the timer is already running, do nothing. In this way the user should perceive no difference, but the actions will not hang.
You could also do the work on another thread, but have a flag to indicate work is being done. If, when the selection event fires, work is still being done you set a flag that indicates the work should be repeated. Setting 'repeat\_work' to true 5000 times is not expensive. | 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 want the server strained, so i thought that putting the emails that need to be sent and the files that need to be zipped in a queue. Put them in table and then use a cron job to check every second and execute them (x rows at a time).
Is the above a good idea? Or is there a better approach? I really need help to get this done properly to save myself headaches later on :)
Thanks all | 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 machine which may not even have access to the DB, so this tiny investment up front will give you options later. | 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 the zipping intelligent and use no compression when you're zipping large already compressed files (MP3, ZIP, DOCX, XLSX, JPG, GIF, etc) and using high compression when you have simple text files (TXT, XML, DOC, XLS, etc) as they will zip very quickly even with heavy compression. | 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:
```
string someText = (dbInfo.IsIdentity) ? "First Option" : "Second Option";
```
Trying to duplicate the same thing inside a StringBuilder method, but this isn't working..
```
script.Append("sometext" + (dbInfo.IsIdentity) ? " IDENTITY(1,1)" : "");
``` | 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 return
/// immediately as canceled.</param>
/// <returns>A Task representing waiting for the process to end.</returns>
public static Task WaitForExitAsync(this Process process,
CancellationToken cancellationToken = default(CancellationToken))
{
if (process.HasExited) return Task.CompletedTask;
var tcs = new TaskCompletionSource<object>();
process.EnableRaisingEvents = true;
process.Exited += (sender, args) => tcs.TrySetResult(null);
if(cancellationToken != default(CancellationToken))
cancellationToken.Register(() => tcs.SetCanceled());
return process.HasExited ? Task.CompletedTask : tcs.Task;
}
```
Usage:
```
public async void Test()
{
var process = new Process("processName");
process.Start();
await process.WaitForExitAsync();
//Do some fun stuff here...
}
``` | 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 interfaces cannot be instantiated...
How would you design this system?
**EDIT** the current inheritance chain looks like this:
```
topLevelClass -> baseObject -> IBaseObject (which is implemented in topLevelClass)
```
so if i added a new class to the chain it would need to do the inheriting and implementing which would be impossible (afaik) | 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 });
something.ListOfT.Add(new T() { SomeProperty = 14 });
}
}
``` | 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 I've examined the output html on the page and it looks reasonable. Any thoughts/suggestions would be greatly appreciated. | 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 things now work correctly. Thanks for your suggestions everyone. | 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, IXMLDOMDocument2 stylesheet)
{
return doc.TransformNode(stylesheet);
}
```
I'm trying to find the managed equivalent. I've already discovered [XmlDocument](http://msdn.microsoft.com/en-us/library/system.xml.xmldocument.aspx) object:
```
public string TransformDocument(XmlDocument doc, XmlDocument stylesheet)
{
//return doc.TransformNode(stylesheet); //TransformNode not supported
}
```
So what is the managed way to transform xml?
I've stumbled across the **deprecated** [XslTransform](http://msdn.microsoft.com/en-us/library/system.xml.xsl.xsltransform.aspx) object, but none of the 18 overloads takes an xml document, or an xml stylesheet.
The replacement Microsoft indicates is the mouthful: [System.Xml.Xsl.XslCompiledTransform](http://msdn.microsoft.com/en-us/library/system.xml.xsl.xslcompiledtransform.aspx). But like it's deprecated cousin, none of XslCompiledTransform's 14 overloads takes xml in an input parameter.
So what's the accepted method to transform xml in C# .NET 2.0?
Put it another way: complete the following helper method:
```
public string TransformDocument(XmlDocument doc, XmlDocument stylesheet)
{
//todo: figure out how to transform xml in C#
}
```
---
## Answer
[Waqas](https://stackoverflow.com/questions/470286/-net-xml-what-is-the-net-equivalent-of-xmldocument-transformnode#470405) had the answer. Here is another, very similar, solution:
```
/// <summary>
/// This method simulates the XMLDOMDocument.TransformNode method
/// </summary>
/// <param name="doc">XML document to be transformed</param>
/// <param name="stylesheet">The stylesheet to transform with</param>
/// <returns></returns>
public static string Transform(XmlDocument doc, XmlDocument stylesheet)
{
XslCompiledTransform transform = new XslCompiledTransform();
transform.Load(stylesheet); // compiled stylesheet
System.IO.StringWriter writer = new System.IO.StringWriter();
transform.Transform(doc, XmlWriter.Create(writer));
return writer.ToString();
}
```
**Note:** If you're a performance weenie, you might want to create an overload to pass the pre-compiled transform, if you're going to transforming more than once.
```
public static string Transform(XmlDocument doc, XslCompiledTransform stylesheet)
{
...
}
``` | 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); // compiled stylesheet
System.IO.StringWriter writer = new System.IO.StringWriter();
transform.Transform(doc, null, writer);
return writer.ToString();
}
```
Optimizations and improvements:
* Cache the compiled stylesheet if you use it more than once.
* Load the XSL directly into the XslCompiledTransform instead of building an XmlDocument first.
* Use XmlNode instead of XmlDocument to make the function more generic. | 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 into a memorystream that can be read.
```
MemoryStream ms = new MemoryStream();
xsldoctrans.Transform(xmldoc, (XsltArgumentList)null, ms);
```
Then get the transformed data:
```
byte[] bTransformeddata = ms.ToArray();
string sTransformeddata = xsldoctrans.OutputSettings.Encoding.GetString(bTransformeddata);
``` | .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 fancy code, just Firefox's `innerHTML` assignment. You should be able to duplicate the error in Firebug like so:
```
>>> document.body.innerHTML = "<embed></embed>"
"<embed></embed>"
>>> document.body.innerHTML
"<embed>"
```
Is there a workaround for this? I need the tag, but I can't justify rebuilding/replacing the entire rich text editor because of one crappy edge case.
I can't convert this to something like `document.createElement('embed')`, because real-world input to this editor can easily include a few paragraphs of text wrapped around the `<embed>`; innerHTML is, on paper, perfect for this use case, I just can't get it to work with an `<embed>`. | 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 value of innerHTML. The idea here is to break up the initial string into multiple concatenated strings. Stupid, but a possible work-around. | 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 unaltered.
So I came up with the following construction (which was inspired on the jQuery source code) :
```
var arrayFunction = window.arrayFunction = function(array) {
return new arrayFunction.fn.init(array);
}
arrayFunction.fn = arrayFunction.prototype = {
init: function(array){
this.a = array;
//should I return something here?
},
someSpecialArrayFunction: function(){
//Super cool custom stuff here.
}
}
```
However this does not work (obviously). What should happen in the init function()?
The error right now is that when I try:
```
arrayFunction(array).someSpecialArrayFunction();
```
it says that someSpecialArrayFunction() is not a function?
How should one do this?
**edit**
Yes, this is indeed a simpliefied example. The actual thing has way more methods.
Also, I just though of how awesome it would be if it also supported chaning, how would you do that? | 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 you end up with too many methods It's probably better to use the prototype. | 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 = {
init: function(array){
var a = array;
return {
someSpecialArrayFunction: function(){
alert (a.join(' - ') ); //Super cool custom stuff here.
}
};
},
}
arrayFunction( [1, 2, 3] ).someSpecialArrayFunction();
``` | 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.Range(1, 10).Aggregate(0, (acc, x) => acc + x);
```
* Filter is `Where`:
```
Enumerable.Range(1, 10).Where(x => x % 2 == 0);
```
<https://www.justinshield.com/2011/06/mapreduce-in-c/> | 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 acting as the map, while the Select method does the job of reducing the intermediate results into the final list of results.
```
var wordOccurrences = words
.GroupBy(w => w)
.Select(intermediate => new
{
Word = intermediate.Key,
Frequency = intermediate.Sum(w => 1)
})
.Where(w => w.Frequency > 10)
.OrderBy(w => w.Frequency);
```
For the distributed portion, you could check out DryadLINQ: <http://research.microsoft.com/en-us/projects/dryadlinq/default.aspx> | 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 type.
I tried to change my designer file in my DBML and add in: `CanBeNull= true` to the Column mapping of the Stored Procedures Result.
I'm can seem to figure out the correct way to handle this, not sure if I can change my LINQ/C# code to account for the null (which would be preferable) or if I will have to update my Stored Procedure in some fashion. | 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 only numeric characters.
So far I have come up with this, but the performance seems poor.
```
/// <summary>
/// Formats a string as a UK phone number
/// </summary>
/// <remarks>
/// 02012345678 becomes 020 1234 5678
/// 01311234567 becomes 0131 123 4567
/// 01905123456 becomes 01905 123456
/// 07816123456 becomes 07816 123456
/// </remarks>
public static string FormatPhoneNumber(string phoneNumber)
{
string formattedPhoneNumber = null;
if (!string.IsNullOrEmpty(phoneNumber))
{
System.Text.RegularExpressions.Regex area1 = new System.Text.RegularExpressions.Regex(@"^0[1-9]0");
System.Text.RegularExpressions.Regex area2 = new System.Text.RegularExpressions.Regex(@"^01[1-9]1");
string formatString;
if (area1.Match(phoneNumber).Success)
{
formatString = "0{0:00 0000 0000}";
}
else if (area2.Match(phoneNumber).Success)
{
formatString = "0{0:000 000 0000}";
}
else
{
formatString = "0{0:0000 000000}";
}
formattedPhoneNumber = string.Format(formatString, Int64.Parse(phoneNumber));
}
return formattedPhoneNumber;
}
```
Thoughts welcomed on how to improve this...
## Edit
My initial thoughts are that I should store phone numbers as numeric fields in the database, then I can go without the Int64.Parse and *know* that they are truly numeric.
## Edit 2
The phone numbers will all be UK geographic or UK mobile numbers, so special cases like 0800 do not need to be considered | 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/static/numbering/). NB: These tables are **very** long.
Also, there's no standard for exactly where spaces are put. Some people might put them in difference places depending on how "readable" it makes the resulting text. | \*\* 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 format: 0+10, 2+8, 3+7, 4+6, 4+5, 5+5, or 5+4 for each range.
There are a small number of errors in the database (especially for 01697 and 0169 77 codes), but they number less than ten errors in more than a quarter of a million entries.
There are four files covering 01 and 02 numbers, and separate files for various non-geographic number ranges.
0+10 numbers are 'National Dialling Only' and are written without parentheses around the area code part. The area code will be 02x for all 02 numbers, 01xx for all 011x and 01x1 numbers, and 01xxx for most other 01 numbers (a very small number - about a dozen - will be 01xx xx though).
Parentheses surround the area code on all other 01 and 02 numbers (that is, use parentheses on 01 and 02 numbers where the local number part does *not* begin with a 0 or a 1). Parentheses show that local dialling is possible within the same area by omitting the digits enclosed by the parentheses.
The 2+8 nomenclature shows the area code and local number length, with the entry 2075 : 2+8 meaning the number is formatted as (020) 75xx xxxx. Remember the leading zero is not 'counted' in the 2+8 determination.
\*\* UK telephone numbers vary in length from 8 digits to 12 digits \*\*
No. Since 2000, most have 10 digits after the '0' trunk code. A few still have 9 digits after the '0' trunk code.
There are also a few special numbers such as 0800 1111 and 0845 4647 to consider.
\*\* "area" codes can vary between 2 and 4 digits. \*\*
Area codes can vary between 2 and 5 digits (the leading zero is not counted). To be clear, '020' is classed as a 2-digit area code because the leading 0 is actually the trunk code. There are also 011x and 01x1 area codes, and most numbers others have 01xxx area codes. The latter may have local numbers that are only 5 digits long instead of the more widely found 6 digit local numbers. A very small number have an 01xx xx area code and these have 5 or 4 digit local numbers.
\*\* Also, there's no standard for exactly where spaces are put. \*\*
There is always a space between the area code part and the local number part for all 01 and 02 numbers.
It is also traditional for (01xx xx) area codes to have a space within the area code as shown. This represents the old local exchange groupings where this system is still in use. Other (shorter) area codes are not split.
Local numbers with 7 or 8 digits have a split before the fourth digit from the end. Local numbers with 4, 5, or 6 digits are not split. This applies to geographic and non-geographic numbers alike.
For most 03, 08, and 09 numbers, the number is written as 0xxx xxx xxxx.
Some 0800 and all 0500 numbers are written 0xxx xxxxxx.
For 055, 056, and 070 numbers the number is written 0xx xxxx xxxx.
For mobile and pager numbers, use 07xxx xxxxxx.
\*\* except some people use '08000 abc def' instead of '0800 0abc def' \*\*
That usage is incorrect. Do be aware that some 0800 numbers have 9 digits after the 0 trunk code, whilst others have 10 digits after the 0 trunk code.
So, both 0800 xxxxxx and 0800 xxx xxxx are correct.
0500 numbers use only 0500 xxxxxx.
Most 03, 08, and 09 numbers are written written as 0xxx xxx xxxx.
See also:
<http://en.wikipedia.org/wiki/Local_conventions_for_writing_telephone_numbers#United_Kingdom> | 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 other purposes as well.
The first thing that came to my mind is to have an internal wiki site that we could build up and change easily over time but I've never used a wiki-based engine before and would like some recommendations.
If possible the engine should be in C# so we're able to tweak it to our needs if required.
If you think a wiki solution is the wrong way to go about this then please give an alternative :)
---
**Update**
I've just been informed, although we do have a php server it wont be staying, so I'm afraid php-based wiki ideas are off the table.
---
**Update 2**
Could you also (if possible) let me know if any of these solutions work with Active Directory?
Cheers
Tony | [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 Directory. | ## 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 correctly if the XML elements in the request are given in alphabetical order, and the values for any elements that are out of order are not populated.
[This behaviour has been reported elsewhere](http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/8ad43a3f-affd-45e9-91fb-fe8a8d9c66f7/).
I find this to be quite unsatisfactory; I consider the requirement to construct the XML in a specific order to be unnecessary, and a major headache. This is a major requirement to add to all clients of the service, and a source of potentially difficult problems to debug.
***Is it possible to direct WCF to be XML element order agnostic?***
---
**Some further details for clarification purposes:**
My operation contract looks like this:
```
[OperationContract]
[WebInvoke(Method="POST", UriTemplate = "/{username}/bookmarks", ResponseFormat = WebMessageFormat.Xml)]
public void PostBookmark(string username, RestBookmark newBookmark);
```
The RestMessage looks as follows:
```
[DataContract(Name = "Bookmark", Namespace = "")]
public class RestBookmark
{
[DataMember]
public string BookmarkMd5 { get; set; }
[DataMember]
public string Url { get; set; }
[DataMember]
public string UserName { get; set; }
[DataMember]
public string Title { get; set; }
[DataMember]
public string Description { get; set; }
}
```
If I send the following XML message, then only the UserName property of the RestMessage object will be populated when PostBookmark() is invoked:
```
<?xml version="1.0"?><Bookmark><UserName>nick.street</UserName><Url>http://www.stackoverflow.com</Url><BookmarkMd5>f184eb3347cf94f6ce5f5fc2844e3bdd</BookmarkMd5><Description>Developer Forum</Description><Title>Stack Overflow</Title></Bookmark>
``` | 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 your services.
3. develop HTTP raw XML message process
service instead.
4. pass the object as a dictionary (not
recommended) | 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's Programming WCF Services 2nd Edition, that's covered starting on page 107.
[Here's the MSDN help page](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.ondeserializingattribute.aspx). | 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 = e.Date.ToString("d")
} into anon
orderby anon.User descending
select anon;
```
That way the string concatenation only has to be done once.
I don't know what that would do in LINQ to SQL though... | 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.Format("{0:d}", e.Date)
}
``` | 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 this is a really bad way to go about organizing my code. I want to get better at organizing my code and abstracting out responsibilities to different classes. Here's an example of where I'd like to start - I want to write a Minesweeper clone, just sort of as practice and to try to improve my software engineering skills. How would I go about making this nice and object-oriented? For the sake of discussion, let's just say I'm using Java (because I probably will, either that or C#). Here's some things I would think about:
* should each tile inherit from JButton or JComponent and handle drawing itself?
* or should the tiles just be stored as some non-graphical MinesweeperTile object and some other class handles drawing them?
* is the 8-segment display countdown timer (pre-Vista, at least) a separate class that handles drawing itself?
* when the user clicks, do the tiles have mouse event listeners or does some other collision detection method loop through the tiles and check each one to see if it's been hit?
I realize that there's not just one way to write a GUI application, but what are some pretty basic things I can start doing to make my code more organized, manageable, object-oriented, and just over all write better programs?
---
edit: I guess I should add that I'm familiar with MVC, and I was originally going to incorporate that into my question, but I guess I didn't want to shoehorn myself into MVC if that's not necessarily what I need. I did searched for topics on MVC with GUI apps but didn't really find anything that answers my specific question.
---
edit2: Thanks to everyone who answered. I wish I could accept more than one answer.. | 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 keeps track of "Number of turns", "Score" etc. You will also need a Timer object to keep track of the game time.
Then create a separate UI object that doesn't know anything about the Game object. It is completely stand alone and completely platform dependent. It has its own UIBoard, UITile, UITimer etc. and can be told how to change its states. The UI object is responsible for the User Interface (output to the screen/sound and input from the user).
And finally, add the top level Application object that reads input from the UI object, tells the Game what to do based on the input, is notified by the Game about state changes and then turns around and tells the UI how to update itself.
This is (by the way) an adaption of the MVP (Model, View, Presenter) pattern. And (oh by the way) the MVP pattern is really just a specialization of the Mediator pattern. And (another oh by the way) the MVP pattern is basically the MVC (Model, View, Control) pattern where the View does NOT have access to the model. Which is a big improvement IMHO.
Have fun! | 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 bytes the string has been stored in? Why is there a dependency on character encodings? | **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 honestly do *not* understand why people keep telling you that you need the encodings. You certainly do NOT need to worry about encodings for this.**
Just do this instead:
```
static byte[] GetBytes(string str)
{
byte[] bytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
return bytes;
}
// Do NOT use on arbitrary bytes; only use on GetBytes's output on the SAME system
static string GetString(byte[] bytes)
{
char[] chars = new char[bytes.Length / sizeof(char)];
System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
return new string(chars);
}
```
As long as your program (or other programs) don't try to *interpret* the bytes somehow, which you obviously didn't mention you intend to do, then there is **nothing** wrong with this approach! Worrying about encodings just makes your life more complicated for no real reason.
**Additional benefit to this approach: It doesn't matter if the string contains invalid characters, because you can still get the data and reconstruct the original string anyway!**
It will be encoded and decoded just the same, because you are *just looking at the bytes*.
If you used a specific encoding, though, it would've given you trouble with encoding/decoding invalid characters. | 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:
```
string pi = "\u03a0";
byte[] ascii = System.Text.Encoding.ASCII.GetBytes (pi);
byte[] utf8 = System.Text.Encoding.UTF8.GetBytes (pi);
Console.WriteLine (ascii.Length); //Will print 1
Console.WriteLine (utf8.Length); //Will print 2
Console.WriteLine (System.Text.Encoding.ASCII.GetString (ascii)); //Will print '?'
```
ASCII simply isn't equipped to deal with special characters.
Internally, the .NET framework uses [UTF-16](https://en.wikipedia.org/wiki/UTF-16) to represent strings, so if you simply want to get the exact bytes that .NET uses, use `System.Text.Encoding.Unicode.GetBytes (...)`.
See *[Character Encoding in the .NET Framework](http://msdn.microsoft.com/en-us/library/ms404377.aspx)* (MSDN) for more information. | 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";
System.Text.UnicodeEncoding Encoding = new System.Text.UnicodeEncoding();
byte[] unicodeBytes = {255,254};
int length = 2 + Encoding.GetByteCount(_exportContent); // _exportContent is string.
response.AddHeader("Content-Length", length.ToString());
response.OutputStream.Write(unicodeBytes, 0, 2);
unicodeBytes = Encoding.GetBytes(_exportContent);
response.OutputStream.Write(unicodeBytes, 2, unicodeBytes.Length);
response.End();
```
I am opening the aspx page with js (window.open()) and execute the above code in the Page\_Load().
The strange thing is that the window pops up, tries to load/show the file dialog and then you hear the sound like a popup window has been blocked (although popup blocker is deactivated!).
Extra information:
- The behavior happens both on XP and W2k3 (which is a real web server without anything else installed but IE7 & FW 3.5 SP1 & latest service packs.)
- The same code works fine with FW 2.0
- Firefox has no problems to display a file dialog.
I would be curious if anyone else has ran into the same problem and could provide a solution for getting the thing working in IE7.
Cheers,
Dimi | 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 'Local intranet' adjust the security settings by clicking the button, 'Custom level ...'
Go to the 'Downloads' node '> Automatic prompting for file downloads' > check 'Enable'
That fixed it for my users.
Hope that helps. | 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';//session_id()
$string2 = '5d41402abc4b2a76b9719d911017c592';//md5()
```
Thank you for any help.
EDIT: Ah sorry Rob. It would be great if there is a solution where it was just a function I could pass two strings to, and it returned a string.
The returned string must contain both of the previous strings. Not just a concatination, but the characters of each string are mingled into one bigger one. | 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 a string which cannot be read by humans, encrypt it - check out the [mcrypt](http://www.php.net/manual/en/ref.mcrypt.php) extension which offers a variety of options. | 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;
INSERT INTO table2 (`number`) VALUES (@var_name);
```
I can't get past the first statement, though, as I get the error "Undeclared variable var\_name". I've also tried putting the statement in a BEGIN/END block, and a stored procedure, but then I encounter other errors which state only that there is an error on the SELECT line. What am I doing wrong? | 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 way to do it:
```
insert into table2 ('number')
select id
from table1
where some_column = 'something' LIMIT 1;
```
This negates the need for a variable and will be a lot faster and easier to understand down the road. | 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 from a client class, then at times need to nullify it through my application by the creating class.
Can I do something like the following
```
public class ClientClass
{
MyObject obj;
CreatingClass creatingClass = new CreatingClass();
private void AFunctionToCreateMyClass()
{
obj = creatingClass.CreateObject<MyClass>(parameters);
}
private void AFunctionToDeleteMyObject()
{
CreatingClass.DestroyObject(obj);
Assert.IsNull(obj);//Doesn't fail
}
}
```
I had tried objectToDestroy = null, but didn't think it would work (and it didn't) | 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 could get confusing, since that works on the *variable* - i.e. if you do:
```
var tmp = obj;
DestroyObject(ref tmp);
```
then `obj` will still be the original value. Unless you have a good reason, I don't recommend the `ref` approach. | 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 the record's status field to indicate that processing is completed (or In Error, with an error count).
This operation sounds very similar to a queue. What are the benefits and tradeoffs of using MSMQ over a SQL Table in this situation, and why should I choose one over the other?
It is our software that is adding and updating records in the table.
It is a new piece of work (a Windows Service) that will be performing the asynchronous processing. This needs to be "always up". | 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 local machine). As far as the application is concerned it delivered the message to MSMQ, even though MSMQ will possibly deliver the message later.
You can only insert a record to a table when you can connect to the database.
A table approach is better when a workflow approach is required, and the process will move through various stages, and these stages need persisting in the DB. | 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 process reading and writing to the same region of the bookings table, then consider introducing MSMQ. | 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 work in Safari/Chrome.
Thanks
Andrew | 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.focus();
ifWin.printPage();
return false;
}
```
**Update**: Many people seem to be having problems with this in versions of IE released since I had this problem. I do not have the time to re-investigate this right now, but, if you are stuck I suggest you read all the comments in this entire thread! | 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/questions/384587/c-im-stuck-filling-this-bst-with-its-proper-values)
I need two search functions to be able to properly fill in the words of the dictionary and later define its synonyms/antonyms.
This is the search function:
```
//--- Definition of findId()
template <typename DataType>
DataType& BST<DataType>::findId(const int id ) const
{
typename BST<DataType>::BinNodePointer locptr = myRoot;
typename BST<DataType>::BinNodePointer parent =0;
bool found = false;
while (!found && locptr != 0)
{
if (locptr->data > id) // descend left
locptr = locptr->left;
else if (locptr->data < id) // descend right
locptr = locptr->right;
else // item found
found = true;
}
return found ? locptr->data : NULL;
}
```
And my attempt so far..
```
template <typename DataType>
bool BST<DataType>::operator >(const int anotherId)const
{
typename BST<DataType>::BinNodePointer locptr;
//undefined pointer, what should I make it point at?
return (locptr->data > anotherId);
}
```
The whole template:
```
#include <iostream>
#include <iomanip>
#include <stdlib.h>
#ifndef BINARY_SEARCH_TREE
#define BINARY_SEARCH_TREE
template <typename DataType>
class BST
{
public:
/***** Function Members *****/
BST();
bool empty() const;
DataType& findId (const int id)const;
bool operator >(const int anotherId)const;
bool operator < (const int anotherId)const;
bool search(const DataType & item) const;
void insert(const DataType & item);
void remove(const DataType & item);
void inorder(std::ostream & out) const;
void graph(std::ostream & out) const;
private:
/***** Node class *****/
class BinNode
{
public:
DataType data;
BinNode * left;
BinNode * right;
// BinNode constructors
// Default -- data part is default DataType value; both links are null.
BinNode()
: left(0), right(0)
{}
// Explicit Value -- data part contains item; both links are null.
BinNode(DataType item)
: data(item), left(0), right(0)
{}
}; //end inner class
typedef BinNode * BinNodePointer;
/***** Private Function Members *****/
void search2(const DataType & item, bool & found,
BinNodePointer & locptr, BinNodePointer & parent) const;
/*------------------------------------------------------------------------
Locate a node containing item and its parent.
Precondition: None.
Postcondition: locptr points to node containing item or is null if
not found, and parent points to its parent.#include <iostream>
------------------------------------------------------------------------*/
void inorderAux(std::ostream & out,
BST<DataType>::BinNodePointer subtreePtr) const;
/*------------------------------------------------------------------------
Inorder traversal auxiliary function.
Precondition: ostream out is open; subtreePtr points to a subtree
of this BST.
Postcondition: Subtree with root pointed to by subtreePtr has been
output to out.
------------------------------------------------------------------------*/
void graphAux(std::ostream & out, int indent,
BST<DataType>::BinNodePointer subtreeRoot) const;
/*------------------------------------------------------------------------
Graph auxiliary function.
Precondition: ostream out is open; subtreePtr points to a subtree
of this BST.
Postcondition: Graphical representation of subtree with root pointed
to by subtreePtr has been output to out, indented indent spaces.
------------------------------------------------------------------------*/
/***** Data Members *****/
BinNodePointer myRoot;
}; // end of class template declaration
//--- Definition of constructor
template <typename DataType>
inline BST<DataType>::BST()
: myRoot(0)
{}
//--- Definition of empty()
template <typename DataType>
inline bool BST<DataType>::empty() const
{ return myRoot == 0; }
//--- Definition of findId()
template <typename DataType>
DataType& BST<DataType>::findId(const int id ) const
{
typename BST<DataType>::BinNodePointer locptr = myRoot;
typename BST<DataType>::BinNodePointer parent =0;
bool found = false;
while (!found && locptr != 0)
{
if (locptr->data > id) // descend left
locptr = locptr->left;
else if (locptr->data < id) // descend right
locptr = locptr->right;
else // item found
found = true;
}
return found ? locptr->data : NULL;
}
template <typename DataType>
bool BST<DataType>::operator >(const int anotherId)const
{
typename BST<DataType>::BinNodePointer locptr;
return (locptr->data > anotherId);
}
template <typename DataType>
bool BST<DataType>::operator < (const int anotherId)const
{
typename BST<DataType>::BinNodePointer locptr;
return (locptr->data < anotherId);
}
//--- Definition of search()
template <typename DataType>
bool BST<DataType>::search(const DataType & item) const
{
typename BST<DataType>::BinNodePointer locptr = myRoot;
typename BST<DataType>::BinNodePointer parent =0;
/* BST<DataType>::BinNodePointer locptr = myRoot;
parent = 0; */ //falta el typename en la declaracion original
bool found = false;
while (!found && locptr != 0)
{
if (item < locptr->data) // descend left
locptr = locptr->left;
else if (locptr->data < item) // descend right
locptr = locptr->right;
else // item found
found = true;
}
return found;
}
//--- Definition of insert()
template <typename DataType>
inline void BST<DataType>::insert(const DataType & item)
{
typename BST<DataType>::BinNodePointer
locptr = myRoot, // search pointer
parent = 0; // pointer to parent of current node
bool found = false; // indicates if item already in BST
while (!found && locptr != 0)
{
parent = locptr;
if (item < locptr->data) // descend left
locptr = locptr->left;
else if (locptr->data < item) // descend right
locptr = locptr->right;
else // item found
found = true;
}
if (!found)
{ // construct node containing item
locptr = new typename BST<DataType>::BinNode(item);
if (parent == 0) // empty tree
myRoot = locptr;
else if (item < parent->data ) // insert to left of parent
parent->left = locptr;
else // insert to right of parent
parent->right = locptr;
}
else
std::cout << "Item already in the tree\n";
}
//--- Definition of remove()
template <typename DataType>
void BST<DataType>::remove(const DataType & item)
{
bool found; // signals if item is found
typename BST<DataType>::BinNodePointer
x, // points to node to be deleted
parent; // " " parent of x and xSucc
search2(item, found, x, parent);
if (!found)
{
std::cout << "Item not in the BST\n";
return;
}
//else
if (x->left != 0 && x->right != 0)
{ // node has 2 children
// Find x's inorder successor and its parent
typename BST<DataType>::BinNodePointer xSucc = x->right;
parent = x;
while (xSucc->left != 0) // descend left
{
parent = xSucc;
xSucc = xSucc->left;
}
// Move contents of xSucc to x and change x
// to point to successor, which will be removed.
x->data = xSucc->data;
x = xSucc;
} // end if node has 2 children
// Now proceed with case where node has 0 or 2 child
typename BST<DataType>::BinNodePointer
subtree = x->left; // pointer to a subtree of x
if (subtree == 0)
subtree = x->right;
if (parent == 0) // root being removed
myRoot = subtree;
else if (parent->left == x) // left child of parent
parent->left = subtree;
else // right child of parent
parent->right = subtree;
delete x;
}
//--- Definition of inorder()
template <typename DataType>
inline void BST<DataType>::inorder(std::ostream & out) const
{
inorderAux(out, myRoot);
}
//--- Definition of graph()
template <typename DataType>
inline void BST<DataType>::graph(std::ostream & out) const
{ graphAux(out, 0, myRoot); }
//--- Definition of search2()
template <typename DataType>
void BST<DataType>::search2(const DataType & item, bool & found,
BST<DataType>::BinNodePointer & locptr,
BST<DataType>::BinNodePointer & parent) const
{
locptr = myRoot;
parent = 0;
found = false;
while (!found && locptr != 0)
{
if (item < locptr->data) // descend left
{
parent = locptr;
locptr = locptr->left;
}
else if (locptr->data < item) // descend right
{
parent = locptr;
locptr = locptr->right;
}
else // item found
found = true;
}
}
//--- Definition of inorderAux()
template <typename DataType>
void BST<DataType>::inorderAux(std::ostream & out,
BST<DataType>::BinNodePointer subtreeRoot) const
{
if (subtreeRoot != 0)
{
inorderAux(out, subtreeRoot->left); // L operation
out << subtreeRoot->data << " "; // V operation
inorderAux(out, subtreeRoot->right); // R operation
}
}
//--- Definition of graphAux()
template <typename DataType>
void BST<DataType>::graphAux(std::ostream & out, int indent,
BST<DataType>::BinNodePointer subtreeRoot) const
{
if (subtreeRoot != 0)
{
graphAux(out, indent + 8, subtreeRoot->right);
out << std::setw(indent) << " " << subtreeRoot->data << std::endl;
graphAux(out, indent + 8, subtreeRoot->left);
}
}
#endif
``` | 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:
```
class DataType
{
private:
mutable int internalID;
// ...
public:
const int id() const { return internalID; }
// ...
virtual ~DataType();
};
```
Now, in your `findID` loop, you can simply use:
```
while (!found && locptr != 0)
{
if (locptr->data.id() > id)
{
locptr = locptr->left;
}
else if (locptr->data.id() < id)
{
locptr = locptr->right;
}
else
{
found = true;
}
}
```
And you don't have to go through all of the unnecessary hassle of operator overloading. | 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 node class something like
```
template<typename type>
friend bool operator>(const BST<type>::node&, BST<type>::const node&);
```
My two cents at least. | 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 possible to run a "asp.net web administration tool-services" on IIS? | 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://blogs.msdn.com/rahulso/archive/2006/03/09/547402.aspx>
Update: here's a very basic example in MVC3/Razor:
<http://www.mikepope.com/blog/DisplayBlog.aspx?permalink=2240#Create_a_page_to_manage_roles> | 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 hash table and how do I access it?
```
<script type="text/javascript">
function Hash()
{
this.length = 0;
this.items = new Array();
for (var i = 0; i < arguments.length; i += 2) {
if (typeof(arguments[i + 1]) != 'undefined') {
this.items[arguments[i]] = arguments[i + 1];
this.length++;
}
}
this.removeItem = function(in_key)
{
var tmp_value;
if (typeof(this.items[in_key]) != 'undefined') {
this.length--;
var tmp_value = this.items[in_key];
delete this.items[in_key];
}
return tmp_value;
}
this.getItem = function(in_key) {
return this.items[in_key];
}
this.setItem = function(in_key, in_value)
{
if (typeof(in_value) != 'undefined') {
if (typeof(this.items[in_key]) == 'undefined') {
this.length++;
}
this.items[in_key] = in_value;
}
return in_value;
}
this.hasItem = function(in_key)
{
return typeof(this.items[in_key]) != 'undefined';
}
}
var myHash = new Hash('one',1,'two', 2, 'three',3 );
for (var i in myHash.items) {
alert('key is: ' + i + ', value is: ' + myHash.items[i]);
}
</script>
```
How do I do it? | 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 hash tables! It would, however, be harder to iterate over since using `foreach(var item in object)` would also get you all its functions, etc., but that might be enough depending on your needs. | 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: [2], three: [3, 30, 300] }
```
And then access them using JavaScript's associative array syntax:
```
alert(table['one']); // Will alert with [1,10,5]
alert(table['one'][1]); // Will alert with 10
``` | 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:
```
function selectOne() {
var e = document.getElementById('test');
e.options[0] = new Option('— Select One —', '');
}
```
However, as you will see if you test this, the — becomes escaped. I had the same outcome when I tried:
```
e.options[o].text = '— Select One —';
```
(Observed behavior was in Internet Explorer 7 ... did not test with Firefox, Safari, etc. -- Internet Explorer 7 is the only browser I need at the moment.) | 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 is recommended? `boost::interprocess::unique_pointer` looks like a good candidate, but is this really the best solution out there? | `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 usage of `std::unique_ptr`, which requires rvalue references and move semantics to be implemented (that's a fairly complicated feature).
Until the new standard is released, I would simply try to disable the warning if possible, or ignore it, for maximum portability.
If you want to already switch to the next language standard, it is possible since rvalue references have been implemented (see <http://russ.yanofsky.org/rref/>), so also `std::unique_ptr` should be supported.
On of the advantages of the new semantics is that you can pass to the move constructor also a temporary or any rvalue; in other cases, this allows avoiding to copy (for instance) objects contained inside a `std::vector` (during reallocation) before destroying the original ones. | `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 support movable types, where `boost::interprocess::unique_ptr` is one of them. They resemble movable types in pre C++0x by using some of the "normal" boost-template wizardry, and use r-value references where they are supported.
I didn't know about the `auto_ptr` dedicated deprecation, though, but I've not followed the new standard evolution closely.
(**edit**) The implementation of `boost::interprocess::unique_ptr` is indeed not a "public" smart-pointer like `boost::shared_ptr` or `boost::scoped_ptr`, but it is (see [boost.interprocess's site](http://www.boost.org/doc/libs/1_35_0/boost/interprocess/smart_ptr/unique_ptr.hpp)) not just for shared-memory, but can also be used for general-purpose.
However, I'm quite sure that if GCC deprecates the `auto_ptr` template, they already provide their own `unique_ptr` implementation (not much use to deprecate if you not have a viable alternative yet).
However, that all being said, if you're working on a C++0x platform, use `unique_ptr`, available from the compiler's lib, if not, stick with `auto_ptr`. | 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 update with each click.
Thanks | [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` MSDN article has an example that sounds like exactly what you are doing.) | 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() {
//stuff
}
```
and
```
public void someMethod() {
synchronized (this) {
//stuff
}
}
```
Are they equivalent? | 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
MONITOREXIT
RETURN
```
(Thanks to [ASM](http://asm.objectweb.org/) for the bytecode printing).
So the difference between them persists to the bytecode level, and it's up to the JVM to make their behavior the same. However, they do have the same functional effect - see the [example](http://web.archive.org/web/20120212170310/http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.3.6) in the Java Language Specification.
It should be noted, that if the method is overridden in a subclass, that it is not necessarily synchronized - so there is no difference in that respect either.
I also ran a test to block a thread trying access the monitor in each case to compare what their stack traces would look like in a thread dump, and they both contained the method in question, so there is no difference there either. | 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% identical.
**EDIT:** i'm going to clarify this as some people here got it wrong. Consider:
```
public class A {
public synchronized void doStuff()
{
// do stuff
}
}
public class B extends A {
public void doStuff()
{
// do stuff
// THIS IS OVERRIDE!
}
}
```
In this case `doStuff()` in class B still overrides `doStuff()` in class A even though it is not synchronized.
**Synchronized keyword is never part of the contract!** Not for subclasses, not for interfaces, not for abstract classes. | 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.
Only a complete restart of the software works.
Suggestions?
---
I can't use the using keyword because TpcClient is only defined in one location, but used throughout the library. (And there is only one connection at any given time)
It's a library that handles communication. The software itself can call the ResetConnection() method of the Controller class (which represents the hardware).
It currently looks like
```
if (tcpClient != null)
{
tcpClient.Close();
tcpClient = null;
}
```
Now from what I've read here I should use tcpClient.Dispose() instead of " = null"
I'll give that a try and see if it makes a difference. | 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](https://msdn.microsoft.com/en-us/library/system.net.sockets.tcpclient.close(v=vs.110).aspx) a call to the method `Close` closes both the connection and the stream
*EDIT according to Microsoft Docs*
> The Close method marks the instance as disposed and requests that the
> associated Socket close the TCP connection. Based on the LingerState
> property, the TCP connection may stay open for some time after the
> Close method is called when data remains to be sent. There is no
> notification provided when the underlying connection has completed
> closing.
Calling this method will eventually result in the close of the associated Socket and will also close the associated NetworkStream that is used to send and receive data if one was created. | 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 what I need, but I was hoping there was a simplier solution. | 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
> programmatically.
This won't work when you have set your combobox to allow the user to type in the textbox though. Also, it won't tell you what the 'last' selected item was. You will have to cache this information. However, you don't need to store your information in a textbox. You can use a string. | 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 MyComboBox : ComboBox {
public event CancelEventHandler BeforeUpdate;
public MyComboBox() {
this.DropDownStyle = ComboBoxStyle.DropDownList;
}
private bool mBusy;
private int mPrevIndex = -1;
protected virtual void OnBeforeUpdate(CancelEventArgs cea) {
if (BeforeUpdate != null) BeforeUpdate(this, cea);
}
protected override void OnSelectedIndexChanged(EventArgs e) {
if (mBusy) return;
mBusy = true;
try {
CancelEventArgs cea = new CancelEventArgs();
OnBeforeUpdate(cea);
if (cea.Cancel) {
// Restore previous index
this.SelectedIndex = mPrevIndex;
return;
}
mPrevIndex = this.SelectedIndex;
base.OnSelectedIndexChanged(e);
}
finally {
mBusy = false;
}
}
}
``` | 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) or IEnumerable<> (to use a foreach loop on the collection)
for example
```
private void PrintAll<T>(IEnumerable<T> items)
{
foreach(T item in items)
Console.WriteLine(item.ToString());
}
```
now i can pass in any container which uses the IEnumerable<> interface, including List<> and the normal array
example
```
List<Person> people = new List<Person>();
//add some people to the list
PrintAll<Person>(people);
```
[a sample n-tier app with Buiness objects](http://www.dofactory.com/Framework/Framework.aspx)
HTH
bones | 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 code. Additionally you can inject business logic wherever you need/want it. | 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.GetType(), "jQueryNoConflict", "jQuery.noConflict()", True)
%>
```
Sadly, when I view source on my page, I don't see the appropriate tag referencing jquery.min.js anywhere. Is DotNetNuke somehow flushing out my requests to add script to my pages here? What am I missing? I'm somewhat of a DNN newbie. | 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.Load
Page.ClientScript.RegisterClientScriptInclude("jquery", "http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js")
Page.ClientScript.RegisterStartupScript(Me.GetType(), "jQueryNoConflict", "jQuery.noConflict();", True)
End Sub
</script>
``` | 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 least) 10-20 images of an event. On modern cameras, 10-20 images translates to 50-200megs.
If people have 256kbps upload speed, it's already ~15 minutes just in transfer. My experience is that people are just not *that* patient when it comes to waiting for something to happen... So I need to do something about it.
I'm looking for a Flash/Java (no Silverlight, please) applet that can resize images on the **client-side** to a specified width and upload that much smaller file. If I can get images down to a few hundred KB, it might be a usable system.
Edit: This is for a personal project. The one suggestion so far is for something that costs $184. I wish I had that much disposable cash for these days! My max budget is around $40 though I'd naturally prefer something free and open source =) | <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, 2009 8:46:20 AM] Binding TestWs web-module for application TestWs to site default-web-site under context root /TestWs
[Jan 23, 2009 8:46:22 AM] Operation failed with error: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
Offending resource: ServletContext resource [/WEB-INF/beans.xml]
```
Looking at the beans.xml, the offending code seems to be the XML namespace declarations:
```
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<import resource="classpath:META-INF/cxf/cxf.xml" />
<import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" />
<import resource="classpath:META-INF/cxf/cxf-servlet.xml" />
<jaxws:endpoint
id="helloService"
implementor="com.test.endpoint.HelloImpl"
address="/HelloWorld" />
</beans>
```
The stack trace is not terribly illuminating:
```
09/01/23 08:57:28 oracle.oc4j.admin.internal.DeployerException: Configuration problem: Unable to locate Spring NamespaceHandler for XML schema namespace [http://cxf.apache.org/jaxws]
Offending resource: ServletContext resource [/WEB-INF/beans.xml]
09/01/23 08:57:28 at org.springframework.beans.factory.parsing.FailFastProblemReporter.error(FailFastProblemReporter.java:68)
09/01/23 08:57:28 at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:85)
09/01/23 08:57:28 at org.springframework.beans.factory.parsing.ReaderContext.error(ReaderContext.java:80)
09/01/23 08:57:28 at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.error(BeanDefinitionParserDelegate.java:261)
09/01/23 08:57:28 at org.springframework.beans.factory.xml.BeanDefinitionParserDelegate.parseCustomElement(BeanDefinitionParserDelegate.java:1120)
...
```
Has anyone else run into similar problems? And if so, what's the best way to go about fixing it? My XML skills are middling, and I'm a complete noob with WebServices. But this may be an OC4J issue.
Thanks in advance for your help!
**EDIT**: This is not, as far as I can tell, a classpath issue, unless OC4J is odd about what jars it want to see where (as I know Tomcat can be). My WEB-INF/lib folder has the CXF jar, the Spring jars (beans, context, core, and web), xml-resolver-1.2.jar, and XmlSchema-1.4.2.jar. If I need to list everything in the WEB-INF/lib folder, I will. But again, the program works in Jetty.
**Another Edit:** Based on what I'm reading [here](http://forum.springframework.org/showthread.php?t=46975), this appears to be an issue between Spring and the CXF jar -- there's a NamespaceHandler class in the CXF jar (in `org.apache.cxf.frontend.spring` to be precise), but there seems to be a configuration issue preventing Spring from seeing it.
**Last Edit:** Thank you everyone for your help. I never ended up getting CXF working in OC4J, because my client is on version 10.1.3.3.0. It's not J2EE 5 compliant, and I'm pretty sure they're not going to go for unpacking their oc4j.jar in order to change the boot.xml. But without the document Daniel pointed me to, I never would have known that.
So I switched to XFire version 1.2.6, and got my test app working after a few hiccups. Along the way I learned some interesting things about OC4J:
* When deploying in Enterprise Manager, make sure you choose to load the local classpath first.
* OC4J uses non-standard XML files, so make sure your app is not using any of OC4J's native XML files (in the Deployment Settings, uncheck all the currently selected imports -- that way, you can ensure that the app is using only files you provide in WEB-INF/lib)
* If you can, use another app server. :P
Thank you all again! | 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 EAR, then this is not the same classpath as that used by your web-app. So, in fact, sticking the CXF jar in `WEB-INF/lib` isn't going to work. You will either need to stick the JAR in the top-level of your EAR, or in some lib shared by all classloaders of OC4J. I suggest studying the enterprise-app/web-app classloader hierarchy documentation of OC4J to see if this can give more advice? | 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 or later) would be a little more work as it's more strict about types and such, but still probably not too difficult.
As others have mentioned, the UI-related stuff is quite different in Flash than Javascript, as there is no DOM. I assumed the methods you were talking about are for doing calculations and not really related to the UI at all. If your javascript methods are actually doing UI stuff then moving them to Flash would be much more involved.
Another possibility, if you want to keep your code in javascript (perhaps so you can reuse it with other javascript stuff) then you could create a Flash movie that takes the input, passes it to javascript, and then have javascript report the results back to Flash. Take a look at the Flash [ExternalInterface](http://livedocs.adobe.com/flash/8/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00002200.html#232104) documentation (see also [here](http://livedocs.adobe.com/flash/8/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001600.html)). | 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 server).
So i was wondering if you guys think its a good idea to standardize the IDE the programmers use and make them have a apache/php/mySQL installed in their boxes to test the code thus having a developers environment in each computer, a test server and a production server.
If so, what set up would you recommend to each part of this process, especially mysql version control (I've never done that) and how to make the deployment?
I know its a very big question and most have been answered in different questions, but I would like a global answer about how is the faster, better (harder and stronger) set-up for this and how much time would we have to stop programming to actually have all this working! (and yes, hiring an expert in the subject is pretty much a no-no)
Thanks! | 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 environment as the test and production server. Using a virtual image can fix this.
As far as MySQL version control, put your schema in your source code management system (CVS, SVN, Perforce, whatever). To deal with changes, you might want to look into Rails migrations for inspiration.
Deployment is a huge question. All I can say is there are tons of tools out there that you can use. [Capistrano](http://www.capify.org/), [Phing](http://phing.info/trac/), etc. | 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 whether you have a standard IDE or not.
Test and production on the same server? I think that's a bad idea. They should be identical but separate. | 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 flash.
So am wonder if I should use Java (which i believe will work on mac & windows). I do not want to develop to separate versions because of the cost involved in developing two versions.
Please guide me as I am new to this.
Thank you.
**UPDATE**
Hello again,
I had a look at the following site: www.screencast-o-matic.com or www.screentoaster.com. I see that they have developed a java applet which helps interact with Windows/Mac to record the screen.
I am wondering how to go about developing something like that and integrating it with Flash (for webcam and audio recording).
Is this a better idea? | 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 screen video... The only closed-platform code will be the VNC launching code. That should be pretty simple to maintain!
That raises a problem because most people are behind NAT firewalls these days. Setting up port forwarding is a pain in the behind. I've used an app called Gitso before which allows people to connect to me and send their desktop to my screen (for tech support). Its VNC-based and all it really does is add another layer on top of the VNC connection so rather than me connecting to them, they connect to me. That makes the whole business of port forwarding a non-issue.
And once you've recorded everything, there's the final issue of syncing it all back together... Might not be so hard. | 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 off to put together a well designed powerpoint presentation, record a voice-over (and edit it!) and then assemble the whole thing as a flash presentation. This is a non-trivial amount of work, but it provides a much more interesting product for the student.
When to use video:
1) When you are demonstrating something dynamic - Mechanics or Chemistry for example.
2) When you are acting out a scenario or case as an illustration -- For example, threat de-escalation techniques for high school teachers.
When you solve the screen recording problem, seriously consider whether you need full motion or if you can get away with stills. Often the motion is distracting, and a still with good voice over can be more effective. (Hint: Replace mouse pointers with something HUGE before recording -- Like Fox did with hockey pucks) | 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 is laid out with no room for these errors, and I also I want the validator to to for correct content as well.
Basically I want to be able to check the field on each key press and blur and if the fields validates for it to gain a green border, and if it does not validate for it to gain a red border, any one know of a plugin that can do this?
Thanks
sico87 | 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 development environment, every time you edit a JSP. Those should eventually get cleaned up, but in an active development environment you can have periods where there are both old and new instances loaded. Or, if you're in a production environment and have a large web-app, you might simply need more space.
To set the permgen size, use `-XX:MaxPermSize=SIZE`
The following links may be helpful: [tuning GC](http://java.sun.com/docs/hotspot/gc5.0/gc_tuning_5.html) (this is the 1.5 edition), [GC FAQ](http://java.sun.com/docs/hotspot/gc1.4.2/faq.html) (1.4.2 edition), [Hotspot VM options](http://java.sun.com/javase/technologies/hotspot/vmoptions.jsp) (I believe this is 1.6) | 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/questions/88235/how-to-deal-with-java-lang-outofmemoryerror-permgen-space-error/88262#88262)
That indirectly pointed me to these two posts: [problem](http://blogs.oracle.com/fkieviet/entry/classloader%5Fleaks%5Fthe%5Fdreaded%5Fjava), [solution](http://blogs.oracle.com/fkieviet/entry/how%5Fto%5Ffix%5Fthe%5Fdreaded) | 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 significantly worsened.
I'm curious to hear of any success stories with it.
What sort of things should I look for in profiling output which might indicate boost::pool is likely to help ?
Is it just actually pretty hard to improve on good old malloc ? | 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 running application.
In sort, it sounds like your applications do not warrant using memory pools | 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 pool as an allocator on the second map and the result was a 500% increase in application execution speed. | 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 that I'm getting an "incovertible types" error, so I must be doing something wrong. | 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 until the end of time, is required to have Office 2000.
In the world before .NET, we used **COM** to talk to Office applications.
For example:
1) Use the version independant ProgID
```
"Excel.Application"
```
which resolves to:
```
clsid = {00024500-0000-0000-C000-000000000046}
```
and then using COM, we ask for one of these classes to be instantiated into an object:
```
IUnknown unk;
CoCreateInstance(
clsid,
null,
CLSCTX_INPROC_SERVER | CLSCTX_LOCAL_SERVER,
IUnknown,
out unk);
```
And now we're off to the races - able to use Excel from inside my application. Of course, if *really* you want to use the object, you have to call have some way of calling methods.
We *could* get ahold of the various **interface** declarations, translated into our language. This technique is good because we get
* early binding
* code-insight
* compile type syntax checking
and some example code might be:
```
Application xl = (IExcelApplication)unk;
ExcelWorkbook workbook = xl.Workbooks.Add(template, lcid);
Worksheet worksheet = workbook.ActiveSheet;
```
---
But there is a downside of using interfaces: we have to get ahold of the various interface declarations, transated into our language. And we're stuck using method-based invocations, having to specify all parameters, e.g.:
```
ExcelWorkbook workbook = xl.Workbooks.Add(template, lcid);
xl.Worksheets.Add(before, after, count, type, lcid);
```
This has proved, in the real world, to have such downsides that we would willingly give up:
* early binding
* code-insight
* compile time syntax checking
and instead use **IDispatch** late binding:
```
Variant xl = (IDispatch)unk;
Variant newWorksheet = xl.Worksheets.Add();
```
Because Excel automation was designed for VB Script, a lot of parameters can be ommitted, even when there is no overload without them.
**Note:** Don't confuse my example of Excel with a reason of why i want to use IDispatch. Not every COM object is Excel. Some COM objects have no support other than through IDispatch. | 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"));
//Get the workbooks collection.
// books = xl.Workbooks;
Object books = xl.GetType().InvokeMember( "Workbooks",
BindingFlags.GetProperty, null, xl, null);
//Add a new workbook.
// book = books.Add();
Objet book = books.GetType().InvokeMember( "Add",
BindingFlags.InvokeMethod, null, books, null );
//Get the worksheets collection.
// sheets = book.Worksheets;
Object sheets = book.GetType().InvokeMember( "Worksheets",
BindingFlags.GetProperty, null, book, null );
Object[] parameters;
//Get the first worksheet.
// sheet = sheets.Item[1]
parameters = new Object[1];
parameters[0] = 1;
Object sheet = sheets.GetType().InvokeMember( "Item",
BindingFlags.GetProperty, null, sheets, parameters );
//Get a range object that contains cell A1.
// range = sheet.Range["A1];
parameters = new Object[2];
parameters[0] = "A1";
parameters[1] = Missing.Value;
Object range = sheet.GetType().InvokeMember( "Range",
BindingFlags.GetProperty, null, sheet, parameters );
//Write "Hello, World!" in cell A1.
// range.Value = "Hello, World!";
parameters = new Object[1];
parameters[0] = "Hello, World!";
objRange_Late.GetType().InvokeMember( "Value", BindingFlags.SetProperty,
null, range, parameters );
//Return control of Excel to the user.
// xl.Visible = true;
// xl.UserControl = true;
parameters = new Object[1];
parameters[0] = true;
xl.GetType().InvokeMember( "Visible", BindingFlags.SetProperty,
null, xl, Parameters );
xl.GetType().InvokeMember( "UserControl", BindingFlags.SetProperty,
null, xl, Parameters );
``` | 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 then exposing the methods that I want to use as methods of my wrapper and then I can call them at will from my C# code. Not the most elegant of solutions, but it has gotten me out of a jam or two over the past few months. | 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 redeclare an interface implementation, if you want to re-implement an interface method which was previously explicitly implemented in a base class - but I don't think that's the reason in this case.
EDIT: I've been assuming that the source code that the docs are built from has the declaration including both interfaces. Another possible alternative is that *all* interfaces in the hierarchy are automatically pulled in by the doc generator. In which case the question becomes "why does the doc generator do that" - and the answer is almost certainly still "clarity". | `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 {}
```
so `List` is an `Enumerable`; in the same way, `IList` is `IEnumerable`.
For example, if I write:
```
interface IA {}
interface IB : IA { }
interface IC : IB { }
```
And look at the metadata, then it appears that `IC : IA, IB` - but this is only indirect; here's the IL:
```
.class private interface abstract auto ansi IA
{
}
.class private interface abstract auto ansi IB
implements IA
{
}
.class private interface abstract auto ansi IC
implements IB, IA
{
}
``` | 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.
Part of my schema:
Products Table:
```
ProductName (key)
TemplateName
TemplateID
...
```
I've added TemplateID, but it has no data in it yet and is nullable.
Templates Table:
```
TemplateID (key)
TemplateName
...
```
I want to use the Templates table to find the matching TemplateID for each TemplateName in the Products table and fill that in the foreign key reference in the Products table.
Can I do this with a subquery in Update, or do I need to write some kind of Stored Proc? I'm using Sql Server 2008 | 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.
You can use the tablename you use in the UPDATE clause in the WHERE clause, to correlate recordds from both tables. | 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 p
Set p.TemplateId =
(
Select t.TemplateId
From Templates t
Where p.TemplateName = t.TemplateName
)
From Products p
``` | 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 extensible when i needed more control.
Anyone who had experience with more than one framework can share his experience? when is it better to use one framework over the other and from application architecture point of view? Why would i prefer one over other?
Thanks | 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 personally use CL in all cases, simply because it's common -- I don't need to remember the differences between frameworks. | 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 unlabeled break to terminate a for, while, or do-while
> loop [...]
>
> An unlabeled break statement terminates the innermost switch, for,
> while, or do-while statement, but a labeled break terminates an outer
> statement.
### `continue`
> The continue statement skips the current iteration of a for, while ,
> or do-while loop. The unlabeled form skips to the end of the innermost
> loop's body and evaluates the boolean expression that controls the
> loop. [...]
>
> A labeled continue statement skips the current iteration of an outer loop marked with the given label. | 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 text. Multiple hits are good, as in each term (of the 1000) that matches then we do want to know about it. Performance in terms of entire time to execute, don't care about footprint. Current algorithm gives about 60 seconds+ using naive string.contains. We don't want 'cat' to provide a match with 'category' or even 'cats' (i.e. entire term word must hit, no stemming).
We expect a <5% hit ratio in the text. The results would ideally just be the terms that matched (dont need position or frequency just yet). We get a new 2-5mb string every 10 seconds, so can't assume we can index the input. The 1000 terms are dynamic, although have a change rate of about 1 change an hour. | 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 your problem lies elsewhere...Or you just need some decent hardware. | 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, domainAndUsername, strPass);
SearchResult result;
try
{
//Bind to the native AdsObject to force authentication.
DirectorySearcher search = new DirectorySearcher(entry) { Filter = ("(SAMAccountName=" + strUser + ")") };
search.PropertiesToLoad.Add("givenName"); // First Name
search.PropertiesToLoad.Add("sn"); // Last Name
search.PropertiesToLoad.Add("cn"); // Last Name
result = search.FindOne();
if (null == result)
{
return null;
}
//Update the new path to the user in the directory.
_path = result.Path;
_filterAttribute = (String)result.Properties["cn"][0];
}
catch (Exception ex)
{
return new Exception("Error authenticating user. " + ex.Message);
}
return user;
}
```
the target is using .NET 3.5, and compiled with VS 2008 standard
I'm logged in under a domain account that is a domain admin where the application is running.
The code works perfectly on windows XP; but i get the following exception when running it on Vista:
```
System.DirectoryServices.DirectoryServicesCOMException (0x8007052E): Logon failure: unknown user name or bad password.
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject()
at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne)
at System.DirectoryServices.DirectorySearcher.FindOne()
at Chain_Of_Custody.Classes.Authentication.LdapAuthentication.IsAuthenticated()
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject()
at System.DirectoryServices.DirectorySearcher.FindAll(Boolean findMoreThanOne)
at System.DirectoryServices.DirectorySearcher.FindOne()
at Chain_Of_Custody.Classes.Authentication.LdapAuthentication.IsAuthenticated()
```
I've tried changing the authentication types, I'm not sure what's going on.
---
**See also**: [[Validate a username and password against Active Directory?](https://stackoverflow.com/questions/290548/c-validate-a-username-and-password-against-active-directory)](https://stackoverflow.com/questions/290548/c-validate-a-username-and-password-against-active-directory) | 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:
```
PrincipalContext context = new PrincipalContext(ContextType.Domain);
UserPrincipal foundUser =
UserPrincipal.FindByIdentity(context, "jdoe");
```
This is using the System.DirectoryServices.AccountManagement namespace so you'll need to add it to your using statements.
If you need to convert a UserPrincipal object to a DirectoryEntry object to work with legacy code you can do this:
```
DirectoryEntry userDE = (DirectoryEntry)foundUser.GetUnderlyingObject();
``` | 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 DirectoryEntry("LDAP://" + domain,
userName, password,
AuthenticationTypes.Secure | AuthenticationTypes.SecureSocketsLayer);
object nativeObject = entry.NativeObject;
```
The first line creates a DirectoryEntry object using domain, username, and password. It also sets the AuthenticationTypes. Notice how I'm setting both Secure (Kerberos) Authentication and SSL using the "Bitwise OR" ( '|' ) operator between the two parameters.
The second line forces the NativeObject of "entry" to Bind to the AD services using the information from the first line.
If an exception is thrown, then the credentials (or settings) were bad. If no exception, you're authenticated. The exception message will usually indicate what went wrong.
This code is pretty similar to what you already have, but the domain is used where you have "path", and the username is not combined with the domain. Be sure to set your AuthenticationTypes properly, too. This can make or break the ability to authenticate. | 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 confident that this isn't doing anything unexpected? In this case CPoint is so simple I think all is well, but in general this is something that worries me a bit. Is it better form to do:
```
p2.SetPoint(p1.x, p2.x);
```
-cr | 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 have a class that allocates memory and neglects to override operator= and perform a deep-copy.
FWIW I asked a question about what the compiler can and cannot do a while back:
[Why don't C++ compilers define operator== and operator!=?](https://stackoverflow.com/questions/217911/why-dont-c-compilers-define-operator-and-operator)
Some of the answers make for interesting reading. | 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 is on B.php, I want the B menu item to carry the #black id. What is the best way of doing this? | 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 class, since you can have multiple classes associated with an element, but only one ID. Again, that ID is reserved for unique naming.
```
.current
{
background-color: #000;
}
```
To associate this with a page you could set a variable on the page that indicates which page its on, then use an if block, or switch case, to add the style to the element that relates to the current page:
**(pseudo code, my PHP syntax is rusty)**
```
$current_page = "B"
// -- snip --
<ul>
<li id="navigation-a" <? if ($current_page == "A") { ?> class="current" <? } ?> >Page A</li>
<li id="navigation-b" <? if ($current_page == "B") { ?> class="current" <? } ?> >Page B</li>
</ul>
```
Optionally you could try deriving $current\_page from the page url in the request. | 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 considered as active, you can use a code similar to this:
```
$currentPage = "b.php";
```
Note that I use a full file name on purpose. I'll explain in a short bit why.
As each menu item requires at least two variables (name, url), I use an array *inside* the menu's array for each entry. An example:
```
$menu = array(array("a.php", "A Title"), array("b.php", "B Title"), array("c.php", "C Title"));
```
Now, in order to let PHP work it's magic, I use a foreach loop that runs through each item and displays it in whichever way I want.
```
foreach($menu as $num => $options){
$s = ((isset($activePage) && $options[0] == $activePage) OR ($options[0] == basename($_SERVER['PHP_SELF'])) ? " class=\"active\"" : "";
echo "\n\t<li{$s}><a href=\"" . $options[0] . "\">" . $options[1] . "</a></li>";
}
```
You can expand this concept to include targets, title tags, etc.
The beauty of this way is that you don't have to write all that much for every project. You can just copy/paste it all, and change the little bits in the $menu array, and if needed (ie. for sub-menu items) specify $currentPage. If $currentPage is not specified, it'll fall back to checking what the current page is (through $\_SERVER['PHP\_SELF']) and base the active state on that.
I hope I explained it well enough, and that it's good enough for you to use!
(Small disclaimer, I *just* woke up and wrote this code from scratch. While the concept works –I've been using it for years–, I might've made a typo here and there. Apologies if this is the case!) | 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 order m=m+1, until m=n.
I am on my way to write a solution of the form:
```
def findsubsets(S, m):
subsets = set([])
...
return subsets
```
But knowing Python I expected a solution to be already there.
What is the best way to accomplish this? | [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 set for which you want to find subsets
m: The number of elements in the subset | 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) (2,3) (1,2,3)
"""
xs = list(iterable)
# note we return an iterator rather than a list
return chain.from_iterable(combinations(xs,n) for n in range(len(xs)+1))
```
Used like:
```
>>> list(powerset("abc"))
[(), ('a',), ('b',), ('c',), ('a', 'b'), ('a', 'c'), ('b', 'c'), ('a', 'b', 'c')]
>>> list(powerset(set([1,2,3])))
[(), (1,), (2,), (3,), (1, 2), (1, 3), (2, 3), (1, 2, 3)]
```
map to sets if you want so you can use union, intersection, etc...:
```
>>> map(set, powerset(set([1,2,3])))
[set([]), set([1]), set([2]), set([3]), set([1, 2]), set([1, 3]), set([2, 3]), set([1, 2, 3])]
>>> reduce(lambda x,y: x.union(y), map(set, powerset(set([1,2,3]))))
set([1, 2, 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 part of the codebase near it, and it looked like a good candidate to mess with. As it is, there's no real reason to replace it, but it's small enough and does something small so it's easy to follow and yet still get a 'good' experience from.
```
private static string MakeNiceString(string str)
{
char[] ca = str.ToCharArray();
string result = null;
int i = 0;
result += System.Convert.ToString(ca[0]);
for (i = 1; i <= ca.Length - 1; i++)
{
if (!(char.IsLower(ca[i])))
{
result += " ";
}
result += System.Convert.ToString(ca[i]);
}
return result;
}
static string SplitCamelCase(string str)
{
string[] temp = Regex.Split(str, @"(?<!^)(?=[A-Z])");
string result = String.Join(" ", temp);
return result;
}
```
The first function `MakeNiceString()` is the function I found in some code I was updating at work. The purpose of the function is to translate **ThisIsAString** to **This Is A String**. It's used in a half-dozen places in the code, and is pretty insignificant in the whole scheme of things.
I built the second function purely as an academic exercise to see if using a regular expression would take longer or not.
Well, here are the results:
With 10 Iterations:
> ```
> MakeNiceString took 2649 ticks
> SplitCamelCase took 2502 ticks
> ```
However, it changes drastically over the longhaul:
With 10,000 Iterations:
```
MakeNiceString took 121625 ticks
SplitCamelCase took 443001 ticks
```
---
### Refactoring `MakeNiceString()`
> The process of refactoring `MakeNiceString()` started with simply removing the conversions that were taking place. Doing that yielded the following results:
```
MakeNiceString took 124716 ticks
ImprovedMakeNiceString took 118486
```
Here's the code after Refactor #1:
```
private static string ImprovedMakeNiceString(string str)
{ //Removed Convert.ToString()
char[] ca = str.ToCharArray();
string result = null;
int i = 0;
result += ca[0];
for (i = 1; i <= ca.Length - 1; i++)
{
if (!(char.IsLower(ca[i])))
{
result += " ";
}
result += ca[i];
}
return result;
}
```
### Refactor#2 - Use `StringBuilder`
> My second task was to use `StringBuilder` instead of `String`. Since `String` is immutable, unnecessary copies were being created throughout the loop. The benchmark for using that is below, as is the code:
```
static string RefactoredMakeNiceString(string str)
{
char[] ca = str.ToCharArray();
StringBuilder sb = new StringBuilder((str.Length * 5 / 4));
int i = 0;
sb.Append(ca[0]);
for (i = 1; i <= ca.Length - 1; i++)
{
if (!(char.IsLower(ca[i])))
{
sb.Append(" ");
}
sb.Append(ca[i]);
}
return sb.ToString();
}
```
This results in the following Benchmark:
> ```
> MakeNiceString Took: 124497 Ticks //Original
> SplitCamelCase Took: 464459 Ticks //Regex
> ImprovedMakeNiceString Took: 117369 Ticks //Remove Conversion
> RefactoredMakeNiceString Took: 38542 Ticks //Using StringBuilder
> ```
Changing the `for` loop to a `foreach` loop resulted in the following benchmark result:
```
static string RefactoredForEachMakeNiceString(string str)
{
char[] ca = str.ToCharArray();
StringBuilder sb1 = new StringBuilder((str.Length * 5 / 4));
sb1.Append(ca[0]);
foreach (char c in ca)
{
if (!(char.IsLower(c)))
{
sb1.Append(" ");
}
sb1.Append(c);
}
return sb1.ToString();
}
```
> ```
> RefactoredForEachMakeNiceString Took: 45163 Ticks
> ```
As you can see, maintenance-wise, the `foreach` loop will be the easiest to maintain and have the 'cleanest' look. It is slightly slower than the `for` loop, but infinitely easier to follow.
### Alternate Refactor: Use Compiled `Regex`
I moved the Regex to right before the loop is begun, in hopes that since it only compiles it once, it'll execute faster. What I found out (and I'm sure I have a bug somewhere) is that that doesn't happen like it ought to:
```
static void runTest5()
{
Regex rg = new Regex(@"(?<!^)(?=[A-Z])", RegexOptions.Compiled);
for (int i = 0; i < 10000; i++)
{
CompiledRegex(rg, myString);
}
}
static string CompiledRegex(Regex regex, string str)
{
string result = null;
Regex rg1 = regex;
string[] temp = rg1.Split(str);
result = String.Join(" ", temp);
return result;
}
```
### Final Benchmark Results:
```
MakeNiceString Took 139363 Ticks
SplitCamelCase Took 489174 Ticks
ImprovedMakeNiceString Took 115478 Ticks
RefactoredMakeNiceString Took 38819 Ticks
RefactoredForEachMakeNiceString Took 44700 Ticks
CompiledRegex Took 227021 Ticks
```
Or, if you prefer milliseconds:
```
MakeNiceString Took 38 ms
SplitCamelCase Took 123 ms
ImprovedMakeNiceString Took 33 ms
RefactoredMakeNiceString Took 11 ms
RefactoredForEachMakeNiceString Took 12 ms
CompiledRegex Took 63 ms
```
So the percentage gains are:
```
MakeNiceString 38 ms Baseline
SplitCamelCase 123 ms 223% slower
ImprovedMakeNiceString 33 ms 13.15% faster
RefactoredMakeNiceString 11 ms 71.05% faster
RefactoredForEachMakeNiceString 12 ms 68.42% faster
CompiledRegex 63 ms 65.79% slower
```
(Please check my math)
In the end, I'm going to replace what's there with the `RefactoredForEachMakeNiceString()` and while I'm at it, I'm going to rename it to something useful, like `SplitStringOnUpperCase`.
### Benchmark Test:
To benchmark, I simply invoke a new `Stopwatch` for each method call:
```
string myString = "ThisIsAUpperCaseString";
Stopwatch sw = new Stopwatch();
sw.Start();
runTest();
sw.Stop();
static void runTest()
{
for (int i = 0; i < 10000; i++)
{
MakeNiceString(myString);
}
}
```
---
### Questions
* What causes these functions to be so different 'over the long haul', and
* How can I improve this function
a) to be more maintainable or
b) to run faster?
* How would I do memory benchmarks on these to see which used less memory?
---
**Thank you for your responses thus far. I've inserted all of the suggestions made by @Jon Skeet, and would like feedback on the updated questions I've asked as a result.**
> **NB**: This question is meant to explore ways to refactor string handling functions in C#. I copied/pasted the first code `as is`. I'm well aware you can remove the `System.Convert.ToString()` in the first method, and I did just that. If anyone is aware of any implications of removing the `System.Convert.ToString()`, that would also be helpful to know. | 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 string already, or use the indexer.
4) Don't do extra string conversions everywhere - calling Convert.ToString(char) and then appending that string is pointless; there's no need for the single character string
5) For the second option, just build the regex once, outside the method. Try it with RegexOptions.Compiled as well.
EDIT: Okay, full benchmark results. I've tried a few more things, and also executed the code with rather more iterations to get a more accurate result. This is only running on an Eee PC, so no doubt it'll run faster on "real" PCs, but I suspect the broad results are appropriate. First the code:
```
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
class Benchmark
{
const string TestData = "ThisIsAUpperCaseString";
const string ValidResult = "This Is A Upper Case String";
const int Iterations = 1000000;
static void Main(string[] args)
{
Test(BenchmarkOverhead);
Test(MakeNiceString);
Test(ImprovedMakeNiceString);
Test(RefactoredMakeNiceString);
Test(MakeNiceStringWithStringIndexer);
Test(MakeNiceStringWithForeach);
Test(MakeNiceStringWithForeachAndLinqSkip);
Test(MakeNiceStringWithForeachAndCustomSkip);
Test(SplitCamelCase);
Test(SplitCamelCaseCachedRegex);
Test(SplitCamelCaseCompiledRegex);
}
static void Test(Func<string,string> function)
{
Console.Write("{0}... ", function.Method.Name);
Stopwatch sw = Stopwatch.StartNew();
for (int i=0; i < Iterations; i++)
{
string result = function(TestData);
if (result.Length != ValidResult.Length)
{
throw new Exception("Bad result: " + result);
}
}
sw.Stop();
Console.WriteLine(" {0}ms", sw.ElapsedMilliseconds);
GC.Collect();
}
private static string BenchmarkOverhead(string str)
{
return ValidResult;
}
private static string MakeNiceString(string str)
{
char[] ca = str.ToCharArray();
string result = null;
int i = 0;
result += System.Convert.ToString(ca[0]);
for (i = 1; i <= ca.Length - 1; i++)
{
if (!(char.IsLower(ca[i])))
{
result += " ";
}
result += System.Convert.ToString(ca[i]);
}
return result;
}
private static string ImprovedMakeNiceString(string str)
{ //Removed Convert.ToString()
char[] ca = str.ToCharArray();
string result = null;
int i = 0;
result += ca[0];
for (i = 1; i <= ca.Length - 1; i++)
{
if (!(char.IsLower(ca[i])))
{
result += " ";
}
result += ca[i];
}
return result;
}
private static string RefactoredMakeNiceString(string str)
{
char[] ca = str.ToCharArray();
StringBuilder sb = new StringBuilder((str.Length * 5 / 4));
int i = 0;
sb.Append(ca[0]);
for (i = 1; i <= ca.Length - 1; i++)
{
if (!(char.IsLower(ca[i])))
{
sb.Append(" ");
}
sb.Append(ca[i]);
}
return sb.ToString();
}
private static string MakeNiceStringWithStringIndexer(string str)
{
StringBuilder sb = new StringBuilder((str.Length * 5 / 4));
sb.Append(str[0]);
for (int i = 1; i < str.Length; i++)
{
char c = str[i];
if (!(char.IsLower(c)))
{
sb.Append(" ");
}
sb.Append(c);
}
return sb.ToString();
}
private static string MakeNiceStringWithForeach(string str)
{
StringBuilder sb = new StringBuilder(str.Length * 5 / 4);
bool first = true;
foreach (char c in str)
{
if (!first && char.IsUpper(c))
{
sb.Append(" ");
}
sb.Append(c);
first = false;
}
return sb.ToString();
}
private static string MakeNiceStringWithForeachAndLinqSkip(string str)
{
StringBuilder sb = new StringBuilder(str.Length * 5 / 4);
sb.Append(str[0]);
foreach (char c in str.Skip(1))
{
if (char.IsUpper(c))
{
sb.Append(" ");
}
sb.Append(c);
}
return sb.ToString();
}
private static string MakeNiceStringWithForeachAndCustomSkip(string str)
{
StringBuilder sb = new StringBuilder(str.Length * 5 / 4);
sb.Append(str[0]);
foreach (char c in new SkipEnumerable<char>(str, 1))
{
if (char.IsUpper(c))
{
sb.Append(" ");
}
sb.Append(c);
}
return sb.ToString();
}
private static string SplitCamelCase(string str)
{
string[] temp = Regex.Split(str, @"(?<!^)(?=[A-Z])");
string result = String.Join(" ", temp);
return result;
}
private static readonly Regex CachedRegex = new Regex("(?<!^)(?=[A-Z])");
private static string SplitCamelCaseCachedRegex(string str)
{
string[] temp = CachedRegex.Split(str);
string result = String.Join(" ", temp);
return result;
}
private static readonly Regex CompiledRegex =
new Regex("(?<!^)(?=[A-Z])", RegexOptions.Compiled);
private static string SplitCamelCaseCompiledRegex(string str)
{
string[] temp = CompiledRegex.Split(str);
string result = String.Join(" ", temp);
return result;
}
private class SkipEnumerable<T> : IEnumerable<T>
{
private readonly IEnumerable<T> original;
private readonly int skip;
public SkipEnumerable(IEnumerable<T> original, int skip)
{
this.original = original;
this.skip = skip;
}
public IEnumerator<T> GetEnumerator()
{
IEnumerator<T> ret = original.GetEnumerator();
for (int i=0; i < skip; i++)
{
ret.MoveNext();
}
return ret;
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
```
Now the results:
```
BenchmarkOverhead... 22ms
MakeNiceString... 10062ms
ImprovedMakeNiceString... 12367ms
RefactoredMakeNiceString... 3489ms
MakeNiceStringWithStringIndexer... 3115ms
MakeNiceStringWithForeach... 3292ms
MakeNiceStringWithForeachAndLinqSkip... 5702ms
MakeNiceStringWithForeachAndCustomSkip... 4490ms
SplitCamelCase... 68267ms
SplitCamelCaseCachedRegex... 52529ms
SplitCamelCaseCompiledRegex... 26806ms
```
As you can see, the string indexer version is the winner - it's also pretty simple code.
Hope this helps... and don't forget, there are bound to be other options I haven't thought of! | 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 improve your performance even more (over the long run). | 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 increasingly bad press as the perceived complexity of Java EE increases. My Java experience against time graph nose-dives significantly after 2004 so I don't feel qualified to comment.
My most recent experience is with an architect desperately trying to accurately represent an object model in a set of (relational) database tables (happened to be Oracle). The result is a database schema that's impossible to query efficiently without first pre-joining a bunch of tables (in materialized views). | 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 about circular dependencies so in some cases we had a pretty bad time to express our domain model, as the business did require circular dependencies (business objects could flow both ways between different administrative units).
The Swing framework was hell. They tried to implement a component model, with something looking a bit like a hierarchical controller. It looked really good on paper : you can have component that can be reused. Model, views and controller were clearly separated. But in reality, the framework didnt provide enough flexibility, so we had to keep references to JComboBox to get the data through the abstraction layers. We had to write 4-5 classes for every little piece of UI. In some cases it took days to add a checkbox on a form. Debugging was awful as the process flow was going through 15-20 classes for every simple operation. Amazingly, performances were OK.
Worst thing, every Swing component was wrapped in an abstraction layer "in case we want to change the UI toolkit" ! | 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-color: #f1ffff;
}
#Layer3 h1 {
font-size: medium;
color: #000033;
text-decoration: none;
text-align: center;
}
.tableheader {
}
.tablecontent {
overflow: auto;
}
```
and part of the php code I am using to generate the html:
```
echo '<div id="tableheader" class="tableheader">';
echo "<h1>{$query} Auctions</h1>" . "\n";
echo "</div>";
echo '<div id="tablecontent" class="tablecontent">';
echo "<table border='0' width='100%'><tr>" . "\n";
echo "<td width='15%'>Seller ID</td>" . "\n";
echo "<td width='10%'>Start Date</td>" . "\n";
echo "<td width='75%'>Description</td>" . "\n";
echo "</tr>\n";
// printing table rows
foreach ($rows as $row)
{
$pk = $row['ARTICLE_NO'];
echo '<tr>' . "\n";
// table contens generated in here
echo '</tr>' . "\n";
}
}
echo "</div>";
```
I am not sure what I have missed, but tableheader does not seem to be stationary, or even separate from tablecontent. | 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 #Layer3 style. You may need to try playing with margins and floats to get things positioned right, but ill leave that to you. | 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 terminal where some data is regularly updated while (at the same time) the user can enter commands/text in some other part of the screen. | 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 value for a given key, you will *not* get `None` when accessing the dict -- a `KeyError` will be raised. So if you want to use a regular `dict`, instead of your code you would use
```
if key in my_dict:
my_dict[key] += 1
else:
my_dict[key] = 1
``` | 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 key doesn't exist in this one line of code, not everywhere. | 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. has changed recently, and if so, write a snapshot to disk (this is to checkpoint the application in case a crash occurs) and mark it as clean again.
Other components of the same program, running in a different thread, call the Monitor's methods to add data to or modify data in the array/collection. Those methods mark the collection as dirty.
Now, the altering methods run in the other components' threads, right? And if I'm not so lucky, they might be called while the snapshot is written to disk, change data that has already been written, set the dirty flag and the Monitor's thread unsets it just after that, without having saved the changes (it was already past the element when it changed). So I have a dirty collection that's marked as clean.
For a while, I thought that I could maybe solve the problem by making a temporary copy of the collection, mark it clean and then go and serialize the copy. But would the copying be atomic, i. e. can I be sure that the collection will not change while I'm copying it?
Meanwhile, I think I have found better solutions, like
* setting a lock flag before beginning the write to disk and make the data altering methods wait until the flag is unset
* have the data altering methods write to a "change queue" instead of directly to the collection and have the thread that does the disk writing process that queue
and I think the lock flag might be the best way to go. **But I'm still curious: Is copying a variable atomic?**
---
**Follow-up**: Maybe this should go in a question of its own, but actually it's very much the same. According to the answers below, my "lock flag" approach might also not work, right? Because the data altering method might check the lock flag while it is being set to the "locked" value and decide it's not locked. So I need a special construction like a mutex if I really want to do this right, correct?
---
Kudos to [erickson](https://stackoverflow.com/users/3474/erickson) for his [very helpful answer](https://stackoverflow.com/questions/473111/in-a-multithreaded-java-or-net-program-can-i-assume-that-copying-a-variable-i#473382) on my follow-up. I really should have made this two questions so I could have accepted two answers. Please, vote him up, too. | 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://gee.cs.oswego.edu/dl/cpj/jmm.html>, especially "atomicity" and "visibility" paragraphs. | 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>
public static void LogOff()
{
StartShutDown("-l");
}
/// <summary>
/// Shutting Down Windows
/// </summary>
public static void Shut()
{
StartShutDown("-f -s -t 5");
}
private static void StartShutDown(string param)
{
ProcessStartInfo proc = new ProcessStartInfo();
proc.FileName = "cmd";
proc.WindowStyle = ProcessWindowStyle.Hidden;
proc.Arguments = "/C shutdown " + param;
Process.Start(proc);
}
}
```
(Source: <http://dotnet-snippets.de/dns/c-windows-herrunterfahren-ausloggen-neustarten-SID455.aspx> | 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 the selected node is NOT a group node.
The problem arises when the Group is located near the bottom of the treeview, so that when I double-click the Group node it would require the treeview to expand vertically to fit the child nodes into view. In such cases, if I double-click the Group node, by the time it expands and adjusts the treeview, my mouse cursor is over a child node (it had to push everything up), and that causes the `NodeMouseDoubleClick` to think the child node is selected, which causes very odd behaviour.
How can I get around this? Should I not be using `NodeMouseDoubleClick` or..?
I see it was also explained in the feedback report *[Problem with TreeView DoubleClick event after expanding/collapsing caused change of scroll](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=304958)*. | 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 own custom behavior. This can be misleading to end users, who expect common behavior from common controls.
From ***[Designing the User Interface](https://rads.stackoverflow.com/amzn/click/com/0201694972)*** by *Ben Shneiderman*, the first of **Eight Golden Rules of Interface Design**:
> 1. Strive for consistency.
>
> Consistent sequences of actions should be
> required in similar situations;
> identical terminology should be used
> in prompts, menus, and help screens;
> and consistent commands should be
> employed throughout.
Long story short, maybe you should not be using NodeMouseDoubleClick. | 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 in f# ([link](http://cs.hubfs.net/forums/thread/244.aspx)). | 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 constructor. | 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 has its Default property set to false.
3. The "Cancel" button has its modalResult set to mrCancel.
Note:
I'm working with an old legacy app that is still being compiled in Borland C++ Builder 5. We have a separate project to replace it - I'm just doing end of life maintenance.
**Update**
Four months later I've finally stopped scratching my head...it turns out that the parent form for the application had a run-time OnShortCut handler defined. I just needed to disable that for the Esc handler to work on the child dialog. | 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 if you have KeyPreview enabled.
4. If you still don't find the problem, check if another component has its ShortCut property set to handle the escape key.
5. Also check if there are any keyboard hooks active. | 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="RightSideMenu" Width="90"/>
```
That is the reason I want the window width, to stretch the user control to 100% width, with the second column relative.
EDIT:
I am using a grid, there is the code for Window:
```
<Window x:Class="TCI.Indexer.UI.Operacao"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tci="clr-namespace:TCI.Indexer.UI.Controles"
Title=" " MinHeight="550" MinWidth="675" Loaded="Load" ResizeMode="NoResize" WindowStyle="None" WindowStartupLocation="CenterScreen" WindowState="Maximized" Focusable="True"
x:Name="windowOperacao">
<Canvas x:Name="canv">
<Grid>
<tci:Status x:Name="ucStatus"/> <!-- the control which I want to stretch in width -->
</Grid>
</Canvas>
</Window>
``` | 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/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Height="300">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Name="LeftSideMenu" Width="100"/>
<ColumnDefinition Name="Middle" Width="*"/>
<ColumnDefinition Name="RightSideMenu" Width="90"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0">a</TextBlock>
<TextBlock Grid.Column="1">b</TextBlock>
<TextBlock Grid.Column="2">c</TextBlock>
</Grid>
</UserControl>
```
*Window1.xaml:*
```
<Window x:Class="WpfApplication1.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication1"
Title="Window1" Height="300" Width="415">
<Grid>
<local:SOAnswerTest Grid.Column="0" Grid.Row="5" Grid.ColumnSpan="2"/>
</Grid>
</Window>
``` | 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/ActualHeight).
```
<Window x:Class="TCI.Indexer.UI.Operacao"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:tci="clr-namespace:TCI.Indexer.UI.Controles"
Title=" " MinHeight="550" MinWidth="675" Loaded="Load"
ResizeMode="NoResize" WindowStyle="None" WindowStartupLocation="CenterScreen"
WindowState="Maximized" Focusable="True" x:Name="windowOperacao">
<Canvas x:Name="canv">
<Grid>
<tci:Status x:Name="ucStatus" Width="{Binding ElementName=canv
, Path=ActualWidth}"
Height="{Binding ElementName=canv
, Path=ActualHeight}"/>
<!-- the control which I want to stretch in width -->
</Grid>
</Canvas>
```
The Canvas is the problem here. If you're not actually utilizing the features the canvas offers in terms of layout or Z-Order "squashing" (think of the flatten command in PhotoShop), I would consider using a control like a Grid instead so you don't end up having to learn the quirks of a control that works differently than you have come to expect with WPF. | 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 formerly stored in Column1...ColumnN each in their own row.
For those times when you really need those values in a single row, you could then do a PIVOT: [Link](https://web.archive.org/web/20191230182030/http://geekswithblogs.net:80/lorint/archive/2006/08/04/87166.aspx)
Edit: My suggestion is somewhat moot. Ash clarified that it's "de-normalization by design, it's a pivot model where each row can contain one of any four data types." Yeah, that kind of design can be cumbersome when you normalize it. | 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();
synthesizer.open();
MidiChannel[] channels = synthesizer.getChannels();
channels[0].noteOn(60, 60);
Thread.sleep(200);
channels[0].noteOff(60);
synthesizer.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
```
I am able to successfully get sound by getting a Sequencer, adding MIDI events to the sequence, and playing the sequence, but I'm trying to do some real-time music effects, which the sequencer does not support.
Any ideas?
**EDIT WITH SOLUTION:** It turns out the problem is that, by default, the JRE doesn't come with a soundbank (interesting, then, that using the Sequencer worked, but using the Synthesizer didn't). Thanks, [thejmc](https://stackoverflow.com/users/54787/thejmc)!
To solve the problem, I [downloaded a soundbank from java.sun.com](http://java.sun.com/products/java-media/sound/soundbanks.html) and placed it in (on WinXP) C:\Program Files\jre1.6.0\_07\lib\audio (had to make the audio folder). | 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 will find it.
It is possible to add the soundbank or to upgrade the Java install on those machine - the pain of inconsistency, I know :) | 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](http://www.ojaivalleynews.com)
The blog url is [www.ovnblog.com](http://www.ovnblog.com) if you want a visual on the bubble. I've used firebug to ispect, but alas I don't know enough about php to make sense of it.
## Update
I missed the second line of code regarding the above question, and based off of the suggestions here, have made corrections to this line and it works.
```
<h1><a href="<?php bloginfo('url'); ?>/"><?php bloginfo('name'); ?></a></h1>
<div id="bubble"><p><a href="http://www.ojaivalleynews.com/" target="_blank"><?php bloginfo('description'); ?></p></div>
``` | 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 bunch of functions which print with a bunch of functions which return values. So yes, it really is supposed to be `<?php bloginfo('url'); ?>` - see [the default theme file](http://trac.wordpress.org/browser/trunk/wp-content/themes/default/header.php#L43) | 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 developer in your environment. | 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, concern yourself about learning the best way to do something when its needed. Keep good references around, such as
[Programming Windows](http://www.charlespetzold.com/pw5/) by Petzold
As a programmer you have so many other things to learn, ie your problem domain or other technologies you'll have to integrate with, that wasting time on brute memorization is usually a waste of resources and won't work as well as google or a good index in the back of a book. | 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 throw exceptions. Obvious candidates are java.io.InputStream, Reader and the java.nio.Channel code, but none of this can use Generics like the Iterable interface can.
Is there a common idiom or Java API for this situation?
Clarification: This is asking if there is a pattern or alternative interface for iterating for objects off a non-memory source. As responders have said, just throwing RuntimeExceptions to get around the problem is not recommended or what I was looking for.
Edit 2: Thanks to answers so far. The consensus seems to be "you can't". So can I extend the question to "What do you do in this situation, when this situation would be useful?" Just write your own interface? | 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 instance, you can really easily write code to iterate through the lines of a text file:
```
public static IEnumerable<string> ReadLines(string filename)
{
using (TextReader reader = File.OpenText(filename))
{
string line;
while ( (line=reader.ReadLine()) != null)
{
yield return line;
}
}
}
```
Use as:
```
foreach (string line in ReadLines("foo.txt"))
```
The foreach loop calls `Dispose` on the `IEnumerator` in a finally block, which translates to "check if we need to do anything in the iterator block's finally (from the using statement)". Obviously there are no checked exceptions in C#, so that side of things isn't a problem either.
A whole (useful!) idiom is pretty much unworkable in Java due to this. | 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 interface.
You can also call an initialize method first that will catch any exceptions, if that's an issue.
```
try{
ts.initializeIOIterator();
}catch(...)
for(T t:ts)
...
``` | 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 additional abstraction on top of Django persistent objects. The code looks more-less like that
```
class TestForManager(unittest.TestCase):
def testAddingBlah(self):
manager = Manager()
self.assertEquals(manager.getBlahs(), 0)
manager.addBlah(...)
self.assertEquals(manager.getBlahs(), 1)
def testAddingBlahInDifferentWay(self):
manager = Manager()
self.assertEquals(manager.getBlahs(), 0)
manager.addBlahInDifferentWay(...)
self.assertEquals(manager.getBlahs(), 1)
```
Now, the first assertion of second test fails, because the state of the database is preserved between test calls and there already is an instance of `Blah` in the database. | 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 WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
int argc = _tcslen(lpCmdLine);
char *argv = new char[argc];
wcstombs(argv,lpCmdLine,1024);
argc = main(argc,&argv);
delete [] argv;
return argc;
}
```
It compiles, and should run once I figure out why the linker is throwing up, but is it right? | 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 have to worry about other people using this program, it's just for academic purposes. If you think improvements are necessary, edit this post, and justify it in your comment.
```
int WINAPI WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow ) {
assert(lpCmdLine != NULL);
int argc = 1, ret = 0;
std::vector<char*> args;
// Copy the entire array to a regular cstr
int cmdLineLen = _tcslen(lpCmdLine);
char *argv = new char[cmdLineLen];
wcstombs(argv,lpCmdLine,cmdLineLen);
args.push_back(&argv[0]);
// Replace spaces with nulls to effectively create array of cstr
for(int i=0; i<cmdLineLen; i++){
if(argv[i] == ' '){
argv[i] = '\0';
args.push_back(&argv[i+1]); // Keep track of the first char in each word
argc++;
}
}
// argv[argc] should be NULL.
args.push_back(NULL);
try{ // Run the program
ret = main(argc,&args[0]);
}
catch(...){
// TODO: Report error here. Commented code works OK for WinCE .NET
// delete argv;
// throw;
ret = -1;
}
delete argv;
return ret;
}
```
Also, for those interested, running this at the command line
```
>myprogam.exe -a shortargument -b -c
```
will put the following in lpCmdLine
```
"-a shortargument -b -c"
```
Also, my first guess was that argv needed to be delete[]'d (because I new char[]'d), but when I did this, the program had a fatal error. When I switched to the above, it worked. Doesn't that violate the new->delete/new[]->delete[] rule? | 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[])
```
then set the the entry point to `mainACRTStartup`
But if you're starting with:
```
int _tmain(int argc, TCHAR *argv[])
```
then the entry point is `mainWCRTStartup` | 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 CalcSomething(Date start, Date end, out int someOtherNumber){}
```
At this point, it's just a feeling, this doesn't sit well with me. For some reason, I'd prefer to see:
```
public Result CalcSomething(Date start, Date end){}
```
where the result is a type that contains a decimal and the someOtherNumber. I think this makes it easier to read. It allows Result to be extended or have properties added without breaking code. It also means that the caller of this method doesn't have to declare a locally scoped "someOtherNumber" before calling. From usage expectations, not all callers are going to be interested in "someOtherNumber".
As a contrast, the only instances that I can think of right now within the .Net framework where "out" parameters make sense are in methods like TryParse(). These actually make the caller write simpler code, whereby the caller is primarily going to be interested in the out parameter.
```
int i;
if(int.TryParse("1", i)){
DoSomething(i);
}
```
I'm thinking that "out" should only be used if the return type is bool and the expected usages are where the "out" parameters will always be of interest to the caller, by design.
Thoughts? | 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, subtle
> differences between value types and
> reference types, and initialization
> differences between out and reference
> parameters.
But if you do use [them](http://msdn.microsoft.com/en-us/library/ms229015.aspx):
> **Do place all out parameters after all of the pass-by-value and ref
> parameters (excluding parameter
> arrays), even if this results in an
> inconsistency in parameter ordering
> between overloads**.
>
> This convention makes the method
> signature easier to understand. | 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();
Data.tbl_Member_UserProfile profile = new tbl_Member_UserProfile();
profile.SSN = Convert.ToDecimal(Session["tempMemberSSN_Registration"]);
profile.UserName = userName;
profile.Password = password;
profile.EmailAddress = email;
profile.QuestionID = qID;
profile.QuestionResponse = securityAnswer;
profile.LastModDt = DateTime.Now;
profile.LastModBy = "web";
context.tbl_Member_UserProfiles.InsertOnSubmit(profile);
context.SubmitChanges();
```
This example is changing the password
```
MemberRegistrationDataContext dc = new MemberRegistrationDataContext();
var mProfileRecord = dc.tbl_Member_UserProfiles.Single(c => c.SSN == sSSN);
mProfileRecord.Password = sNewPassword;
dc.SubmitChanges();
```
Are these safe? Does LINQ parameterize the SQL it generates automatically? | 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 SQL Injection Attacks Painlessly with LINQ](http://www.devx.com/dotnet/Article/34653) for some info. | 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 thoughts, but tell me does this work properly with respect to memory cleanup:
```
function test(a)
{
return (arguments[1]=a.toString()).doSomething().doSomethingMore(arguments[1]);
}
```
This is, of course, an example, but the idea is simple: use arguments as a container for local variables - I'm not sure, but from what I know, when a function is over, arguments are deleted also? Or does create new elements in arguments makes this element defined globally? From my tests, it seems that I'm correct, but I'm curious to see if anyone has tried this? Is this a safe and clean solution?:) Thanks for any comments.
Here are a more real problem with One-Line script problem:
```
function (number,limiter)
{
return ((arguments[2] = number.toString().replace(
new RegExp("(\\d+)(\\d{3})($|"+limiter+")"),
'$1'+limiter+'$2$3')) == number) ?
arguments[2] :
arguments.callee(arguments[2],limiter);
}
```
This one line function do things with given string and return it or parse it recursively to the same function. (on other thread I show how this could be done without recursion, but this is not a case of a problem). | 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 [DateJs](http://www.datejs.com/):
```
var nextTuesday = DateJs.today().next().tuesday();
var aBitLater = DateJs.now().addHours(1).addMinutes(30);
```
Sure, it's syntactic sugar and could be written more verbosely as separate statements, but with careful method nameing you can actually cause this to read like English.
GC / Memory management is not affected by this style, parameters to functions are cleaned up just as any other. In fact it may actually be safer since the parameters immediately go out of scope after the function calls return and there is no need to create local vars for values just to pass them to the next function call.
Your example may be a little contrived but if you use it where it makes sense, it's a useful pattern. | 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 value to the arguments array like you're doing is pointless, as each function has its own arguments array. To address your question about scope, Javascript scoping is lexical; something declared locally inside a function isn't automatically accessible to things outside the function.
edit: using the arguments array is no cleaner or better than any other method. It's actually worse than being clear. | 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 doesn't work particularly well on Windows. (If anyone is interested, I'm running Windows Vista, which might affect things).
Does anyone know of a better solution?
UPD:
After reading the answer telling me to install PyPcap, I messed around with it a bit and found out that Scapy, which I had tried using, was telling me to install PyPcap as well, except that it's a modified version for it's use. It was this modified PyPcap that was causing the problem, apparently, since the example in the answer also caused a hang.
I installed the original version of PyPcap (from Google's site), and Scapy started working fine (I didn't try many things, but at least it didn't crash as soon as I started sniffing). I sent a new defect ticket to the Scapy developers: <http://trac.secdev.org/scapy/ticket/166>, hope they can do something with it.
Anyways, just thought I'd let y'all know. | 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\x18', data=IP(src='\n\x00\x01\x1c',
dst='\n\x00\x01\x10', sum=39799, len=60, p=1, ttl=128, id=35102, data=ICMP(sum=24667,
type=8, data=Echo(id=512, seq=60160, data='abcdefghijklmnopqrstuvwabcdefghi'))))
Ethernet(src='\x00\x03G\x06h\x18', dst='\x00\x03G\xb2M\xe4', data=IP(src='\n\x00\x01\x10',
dst='\n\x00\x01\x1c', sum=43697, len=60, p=1, ttl=255, id=64227, data=ICMP(sum=26715,
data=Echo(id=512, seq=60160, data='abcdefghijklmnopqrstuvwabcdefghi'))))
``` | # 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 according to the IP protocol.
This is and image of the format of the IP protocol with the sized in bits of every header.
[](https://i.stack.imgur.com/rtM54.jpg)
This tutorial might help you understand the proccess of understanding a raw packet and splitting it to headers: <http://www.binarytides.com/python-packet-sniffer-code-linux/>
# The easy way
Another method to sniff IP packets very easily is to use the scapy module.
```
from scapy.all import *
sniff(filter="ip", prn=lambda x:x.sprintf("{IP:%IP.src% -> %IP.dst%\n}"))
```
This code will print for you the source IP and the destination IP for every IP packet.
You can do much more with scapy by reading it's documentation here: <http://www.secdev.org/projects/scapy/doc/usage.html>
It depends on the goal you are trying to achieve but if you need to build a project the one it's features is sniffing IP packets then I recommend to use scapy for more stable scripts. | 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 the ad doesn't look obnoxious on sites with a non-white background. My next challenge is to use my 404 page to completely collapse the `iframe` so that it doesn't display on the page at all.
Is it possible to alter the containing `<iframe />` tag from within the iframe? I just want to change the height & width attributes if this is possible. If so, how would I go about doing this? | 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 following javascript function to the parent page:
```
function hideAdvertFrame() {
var advertFrame = document.getElementById("advertFrame");
advertFrame.style.height = 0;
advertFrame.style.width = 0;
}
```
Then in the 404 page, you can call the function immediately when it loads:
```
<body onload="window.parent.hideAdvertFrame();">
```
That said, I think you still might want to consider other options besides cross frame scripting that are less prone to security holes. Maybe your parent page can use AJAX to check if the adblock will have a valid URL before it loads, and then dynamically add it to the page once certain. | 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 different ports.
A Google search turns up [aspnetserve](http://code.google.com/p/aspnetserve/), [www-Sharp.Runtime](http://www-sharp.com/) and [Neokernel Web Server](http://www.neokernel.com/content.agent?page_name=Home). Do anyone have any experience with those or other solutions? | 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.
In this case, I'd like some hints regarding how to implement this.
I have some(not much) Windows.Forms experience, and I must not use any P/Invoke. I already know out how to detect window motion and how to create a borderless translucent window on a given position and with a given size.
So here are some problems I am facing:
1. WeifenLuo supports multiple left/right/top/bottom panes, allowing them to be resized and contain more than one panel.
2. It also supports splittable tabs.
Is there anything else I should be aware of before starting? Are there similar open-source projects available? | 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 UI for each platform i.e. WinFoms, GTK# (linux) and Cocoa (cocoa#/monobjc). | 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, <http://github.com/dockpanelsuite/dockpanelsuite>** | 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.e. first name, last name, address, phone, etc.) to search a multi-million record table. There are indexes on all joined columns and columns in the WHERE clause. In addition, the initial query dumps the records into a table variable for paging capacity.
```
INSERT INTO @tempCustTable (CustomerID, FirstName, LastName, City, StateProvince, Zip, PhoneNumber)
SELECT DISTINCT cu.CustomerID, cu.FirstName, cu.LastName, a.City,
a.StateProvince, a.Zip, p.PhoneNumber
FROM Customer cu WITH(NOLOCK)
LEFT OUTER JOIN Address a WITH(NOLOCK) ON cu.CustomerID = a.CustomerID
LEFT OUTER JOIN Phone p WITH(NOLOCK) ON cu.CustomerID = p.CustomerID
WHERE (cu.LastName = @LastName OR cu.LastName LIKE @LastName + '%')
AND (@FirstName IS NULL OR cu.FirstName = @FirstName OR cu.FirstName LIKE @FirstName + '%')
AND (@StateProvince = '' OR a.StateProvince LIKE @StateProvince)
AND (@City = '' OR a.City LIKE @City + '%')
AND (@Zip = '' OR a.Zip = @Zip OR a.Zip LIKE @Zip + '%')
ORDER BY cu.LastName, cu.FirstName
```
Does anyone have any recommendations on how I could improve the performance of the query? | 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.
I don't know if this will help in your situation, but one thing that I came across recently was that in stored procedures SQL Server (I'm using 2005, but probably true for 2000 as well) will not short-circuit an OR condition in many cases. For example, when you use:
```
@my_parameter IS NULL OR my_column = @my_parameter
```
it will still evaluate the second half even if you pass in a NULL value for @my\_parameter. This happened even when I set the stored procedure to recompile (and the SELECT). The trick was to force a short-circuit through the use of a CASE statement. Using that trick (and removing some redundancy) your statement would look like this:
```
INSERT INTO @tempCustTable
(
CustomerID,
FirstName,
LastName,
City,
StateProvince,
Zip,
PhoneNumber
)
SELECT DISTINCT
cu.CustomerID,
cu.FirstName,
cu.LastName,
a.City,
a.StateProvince,
a.Zip,
p.PhoneNumber
FROM Customer cu WITH(NOLOCK)
LEFT OUTER JOIN Address a WITH(NOLOCK) ON cu.CustomerID = a.CustomerID
LEFT OUTER JOIN Phone p WITH(NOLOCK) ON cu.CustomerID = p.CustomerID
WHERE
(cu.LastName LIKE @LastName + '%') AND
(1 =
CASE
WHEN @FirstName IS NULL THEN 1
WHEN cu.FirstName LIKE @FirstName + '%' THEN 1
ELSE 0
END
) AND
(1 =
CASE
WHEN @StateProvince = '' THEN 1
WHEN a.StateProvince = @StateProvince THEN 1
ELSE 0
END
) AND
(1 = CASE
WHEN @City = '' THEN 1
WHEN a.City LIKE @City + '%' THEN 1
ELSE 0
END
) AND
(1 = CASE
WHEN @Zip = '' THEN 1
WHEN a.Zip LIKE @Zip + '%' THEN 1
ELSE 0
END
)
```
It makes the query longer, and possibly a little more complex, but it may be worth it for better performance. This is **particularly** true if your criteria includes a subquery that could otherwise be short-circuited.
Finally... **be consistent** with your parameters. For @FirstName you check for a NULL value to determine if it's used or not, but for the others you are checking for empty strings. Basic coding 101 here that you need to be careful about. | 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 ( undefined(bar) )
calculate_bar();
return bar;
}
```
Is it possible in C++?
Thanks | 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 function as a check for < 0.0.
A more general solution is having a bool saying whether bar is defined yet that you initialized to false in the constructor and when you first set it you change it to true. [boost::optional](http://www.boost.org/doc/libs/1_37_0/libs/optional/doc/html/index.html) does this in an elegant templated way.
This is what the code example you have would look like.
```
class Foo {
public:
double get_bar();
Foo() : barDefined(false) {}
private:
double bar;
bool barDefined;
void calculate_bar() {
bar = something();
}
};
double Foo::get_bar() {
if ( barDefined == false ) {
calculate_bar();
barDefined = true;
}
return bar;
}
``` | 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 PowerShell
```
dotnet new sln
Get-ChildItem -Recurse *.csproj | ForEach { dotnet sln add $_.FullName }
``` | 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 the "cases" table. Each column contains some bit of info related to the case. As the case is being processed, additional one-to-many tables are populated with events related to the case. There are quite a few of these event tables, example tables might be: (case-open, case-dept1, case-dept2, case-dept3, etc.). Each of these tables has a caseid which maps back to the "cases" table. There are also a few lookup tables involved as well.
Currently, the reporting needs relate to exposing bottlenecks in the various stages and the granularity is at the hour level for certain areas of the process.
I may be asking too much here, but I'm looking for some direction as to how I should setup my Dim and Fact tables or any other suggestions you might have. | 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 treat a 3NF database 'enterprise data warehouse' with different indexes or summaries, or whatever.
Without seeing your current schema, it's REALLY hard to say. Sounds like you will end up with several star models with some conformed dimensions tying them together. So you might have a case dimension as one of your conformed dimensions. The facts from each other table would be in fact tables which link both to the conformed dimension and any other dimensions appropriate to the facts, so for instance, if there is an employee id in case-open, that would link to an employee conformed dimension, from the case-open-fact table. This conformed dimension might be linked several times from several of your subsidiary fact tables.
Kimball's modeling method is fairly straightforward, and can be followed like a recipe. You need to start by identifying all your facts, grouping them into fact tables, identifying individual dimensions on each fact table and then grouping them as appropriate into dimension tables, and identifying the type of each dimension. | 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 throughput/bottleneck reports are calculating differences between event times for specific combinations of event types on a given case.
The reports should calculate the event-event times and possibly bin them into a histogram. You could also label certain types of event combinations and apply the label to the events of interest. These events could then have the time recorded against them, which would allow slice-and-dice operations on the times with an OLAP tool.
If you want to benchmark certain stages in the life-cycle progression you would have a table that goes case type, event type1, event type 2, benchmark time.
With a bit of massaging, you might be able to use a data mining toolkit or even a simple regression analysis to spot correlations between case attributes and event-event times (YMMV). | 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.