Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have an `ArrayList` and I want to copy it exactly. I use utility classes when possible on the assumption that someone spent some time making it correct. So naturally, I end up with the `Collections` class which contains a copy method.
Suppose I have the following:
```
List<String> a = new ArrayList<String>();
a.add("a");
a.add("b");
a.add("c");
List<String> b = new ArrayList<String>(a.size());
Collections.copy(b,a);
```
This fails because basically it thinks `b` isn't big enough to hold `a`. Yes I know `b` has size 0, but it should be big enough now shouldn't it? If I have to fill `b` first, then `Collections.copy()` becomes a completely useless function in my mind. So, except for programming a copy function (which I'm going to do now) is there a proper way to do this? | Calling
```
List<String> b = new ArrayList<String>(a);
```
creates a shallow copy of `a` within `b`. All elements will exist within `b` in the exact same order that they were within `a` (assuming it had an order).
Similarly, calling
```
// note: instantiating with a.size() gives `b` enough capacity to hold everything
List<String> b = new ArrayList<String>(a.size());
Collections.copy(b, a);
```
also creates a shallow copy of `a` within `b`. If the first parameter, `b`, does not have enough *capacity* (not size) to contain all of `a`'s elements, then it will throw an `IndexOutOfBoundsException`. The expectation is that no allocations will be required by [`Collections.copy`](http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html#copy%28java.util.List,%20java.util.List%29) to work, and if any are, then it throws that exception. It's an optimization to require the copied collection to be preallocated (`b`), but I generally do not think that the feature is worth it due to the required checks given the constructor-based alternatives like the one shown above that have no weird side effects.
To create a deep copy, the `List`, via either mechanism, would have to have intricate knowledge of the underlying type. In the case of `String`s, which are immutable in Java (and .NET for that matter), you don't even need a deep copy. In the case of `MySpecialObject`, you need to know how to make a deep copy of it and that is not a generic operation.
---
Note: The originally accepted answer was the top result for `Collections.copy` in Google, and it was flat out wrong as pointed out in the comments. | `b` has a *capacity* of 3, but a *size* of 0. The fact that `ArrayList` has some sort of buffer capacity is an implementation detail - it's not part of the `List` interface, so `Collections.copy(List, List)` doesn't use it. It would be ugly for it to special-case `ArrayList`.
As tddmonkey has indicated, using the ArrayList constructor which takes a collection is the way to in the example provided.
For more complicated scenarios (which may well include your real code), you may find the collections within [Guava](https://github.com/google/guava) useful. | How to copy Java Collections list | [
"",
"java",
"list",
"collections",
"copy",
""
] |
I got a `QtWebKit.QWebView` widget in a PyQt application window that I use to display text and stuff for a chat-like application.
```
self.mainWindow = QtWebKit.QWebView()
self.mainWindow.setHtml(self._html)
```
As the conversation gets longer the vertical scrollbar appears.
What I'd like to get, is to scroll the displayed view to the bottom when it's needed. How can I do it? Or, maybe, I shouldn't use `QWebView` widget for this? | kender - The QWebView is made up of a QWebPage and a QWebFrame. The scroll bar properties are stored in the QWebFrame, which has a setScrollBarValue() method, as well as a scrollBarMaximum() method to return the max position.
See these links for details:
[QWebView](http://pyqt.sourceforge.net/Docs/PyQt4/qwebview.html),
[QWebFrame](http://pyqt.sourceforge.net/Docs/PyQt4/qwebframe.html) | For (Py)Qt 4.5, use frame's scroll position, e.g. self.\_html.page().mainFrame().setScrollPosition. See [QWebFrame::setScrollPosition()](http://doc.trolltech.com/4.5/qwebframe.html#scrollPosition-prop) function.. | PyQt4 and QtWebKit - how to auto scroll the view? | [
"",
"python",
"pyqt",
"qwebview",
""
] |
## Application Background
Our platform is a click-once WPF application. We have a "shell" that contains a navigation menu structure and it hosts our own custom "page" classes. When you navigate to a new page, we swap out the content of the shell (essentially).
## Problem
So, I work for a company that is working on a extremely large software project. We have much code that we found memory issues with.
The problem is that there are plenty of places in our application were events are wired and never unwired. I'm not sure why developers were doing this, I'm guessing that they expected the objects to get cleaned up each time a user navigates to a new "page".
We don't have the option of refactoring every page (in this release). Is there a way with C# to remove all references from an object? (Therefore allowing the garbage collector to throw that object away, along with all of it's internal references)
We are trying to get this memory back, but it is quite complicated to find objects are still referencing our pages (object references), when we have WPF to deal with.
We have looked at the visual and logical trees and used profiling applications to help us to manually clean things up (for proving out the idea) and this proved to be extremely hard as well.
I sat back and thought, why are we doing all this work to find object references, can't we just "dereference" this "page" when it is closed?
Which brings me here :)
Any help is greatly appreciated!
---
## UPDATE 1
In the comments the following was asked:
**Q:** Does the app. actually have memory problems? How are these exhibited/detected? Or is this memory hanging around until a GC2 happens? – Mitch Wheat
**A:** It has memory problems. If we leave a page (property that holds the page gets set to a new object) the old object never gets collected by the garbage collector. So memory just keeps on growing. If our company started over, with this application. The first thing we should look at would be implementing WeakEvent Patterns and using more Routed Commands in WPF.
## UPDATE 2
I was able to come up with my own [solution](https://stackoverflow.com/questions/617118/is-there-a-good-way-to-perform-wpf-c-object-dereferencing-for-garbage-collectio/622268#622268). | I implemented [WeakEvents](http://msdn.microsoft.com/en-us/library/aa970850.aspx) to solve this issue.
Unfortunately, Microsoft recommends that you use their WeakEventManager as a base class and create a manager type for EACH event in your application!!! I tried to write a manager that inherits from this base and get it to be more "generic" (not in the C# term for generic). This "common" Event manager was not possible with Microsoft's base class. I had to write a Event manager from scratch.
Thank you for any help posted to this question. | Have you used the CLRProfiler? I find this pretty good at finding objects and also finding what holds a reference to them.
This "How To" page...
<http://msdn.microsoft.com/en-us/library/ms979205.aspx>
... links to the download site.
However, I think the answer to your question is "no". There isn't a way of saying "object foo is no longer required - collect it please regardless of whether it's rooted or not". Collecting a rooted object could introduce all sorts of badness into your app. | Is there a good way to perform WPF/C# object dereferencing, for garbage collection? | [
"",
"c#",
"memory-management",
"pointers",
"object",
"object-reference",
""
] |
I'm using Linq to SQL. I have a DataContext against which I am .SubmitChanges()'ing. There is an error inserting the identity field, and I'd like to see the query it's using to insert this identity field.
I don't see the query itself within the quickwatch; where can I find it from within the debugger? | There is actually a very simple answer to your question
Just paste this in your watch window
```
((System.Data.Objects.ObjectQuery)myLinqQueryVar).ToTraceString()
``` | Lots of people have been writing their own "DebugWriter" and attaching it like so:
```
// Add this class somewhere in your project...
class DebugTextWriter : System.IO.TextWriter {
public override void Write(char[] buffer, int index, int count) {
System.Diagnostics.Debug.Write(new String(buffer, index, count));
}
public override void Write(string value) {
System.Diagnostics.Debug.Write(value);
}
public override Encoding Encoding {
get { return System.Text.Encoding.Default; }
}
}
// Then attach it to the Log property of your DataContext...
myDataContext.Log = new DebugTextWriter()
```
This will output everything that Linq-to-Sql is doing into Visual Studio's debug window. | How to get the TSQL Query from LINQ DataContext.SubmitChanges() | [
"",
"c#",
"linq",
"linq-to-sql",
"datacontext",
"submitchanges",
""
] |
I have a table `balances` with the following columns:
```
bank | account | date | amount
```
I also have a table `accounts` that has `bank` and `account` as its composite primary key.
I want to do a query like the following pseudocode:
```
select date, sum(amount) as amount from balances where
bank and account in (list of bank and account pairs) group by date
```
The list of bank-account pairs is supplied by the client.
How do I do this? Create a temp table and join on it?
I'm using Sybase | If bank account pairs is known in you app you just write:
```
(bank = 1 AND account = 2) OR (bank = 3 AND account = 4) OR ...
```
If list of bank account pairs is a subquery, then write something like this:
```
SELECT * FROM balances b LEFT JOIN bank_account_pairs p ON ...
WHERE b.bank = p.bank AND b.account = p.account AND ...
``` | It may be helpful to have some more information.
If you have criteria that are driving your particular list of bank and account entities then you should be joining on these tables.
You do have a Bank table and an Account table don't you?
Assuming you have the information in the accounts table that narrow down the specific accounts you want to reference, for example suppose your Accounts table has an IsActive char(1) NOT NULL field and you want the balances for inactive accounts you would write something like this:
```
SELECT date, sum( amount ) AS amount
FROM Balances b
INNER JOIN Accounts a
ON b.Bank = a.Bank AND b.Account = a.Account
WHERE a.IsActive = 'N'
```
From a design perspective your should probably have created an artificial key to remove replication of non-identifying data across tables. This would give you something like this:
```
CREATE TABLE Accounts (
AccountId int identity(1,1) NOT NULL,
Bank nvarchar(15) NOT NULL,
Account nvarchar(15) NOT NULL
)
CREATE TABLE Balances (
AccountId int,
Date datetime,
Amount money
)
```
This allows errors in the Bank or Account fields to be edited without having to cascade these changes to the Balances table as well as a slightly simpler query.
```
SELECT date, sum( amount ) AS amount
FROM Balances b
INNER JOIN Accounts a
ON b.AccountId = a.AccountId
WHERE a.IsActive = 'N'
``` | SQL: filter on a combination of two column values | [
"",
"sql",
"sybase",
""
] |
```
function valid()
{
begin_checked = false;
end_checked = false;
alert("begin_checked: " +begin_checked);
alert("end_checked: " +end_checked);
if (document.dd.begin.checked.length == undefined || document.dd.end.checked.length == undefined )
{
alert("In undefined");
}
alert("end");
}
```
When the if statement is false, it never gets to alert("end") ? When it is true, it executes properly. Why? | There is probably a null pointer exception and you do not have errors outputting to your browser.
You need some output to check:
```
alert(document);
alert(document.dd);
alert(document.dd.begin);
alert(document.dd.begin.checked);
alert(document.dd.end);
alert(document.dd.end.checked);
```
If you get undefined from any of those, then your code will not execute properly.
Edit: Also, the other answers here all have good information. Read those as well.
Edit2: Alternative - Surround your code in a try/catch block and alert the error:
```
function valid(){
try{
begin_checked = false;
end_checked = false;
alert("begin_checked: " +begin_checked);
alert("end_checked: " +end_checked);
if (document.dd.begin.checked.length == undefined || document.dd.end.checked.length == undefined ){
alert("In undefined");
}
alert("end");
} catch (e) {
alert(e);
}
}
``` | Are there any errors in your browsers error console? I'm guessing it's because it's trying to evaluate a property that doesn't exist, this causing it to fail (never getting to the `== undefined`). You can just check that the property exists or use the typeof to check if it's undefined.
```
if (!document.dd.begin.checked.length || !document.dd.end.checked.length)
{
alert("In undefined");
}
if (typeof document.dd.begin.checked.length == 'undefined' || typeof document.dd.end.checked.length == 'undefined' )
{
alert("In undefined");
}
``` | javascript if statement question | [
"",
"javascript",
""
] |
So, Python functions can return multiple values. It struck me that it would be convenient (though a bit less readable) if the following were possible.
```
a = [[1,2],[3,4]]
def cord():
return 1, 1
def printa(y,x):
print a[y][x]
printa(cord())
```
...but it's not. I'm aware that you can do the same thing by dumping both return values into temporary variables, but it doesn't seem as elegant. I could also rewrite the last line as "printa(cord()[0], cord()[1])", but that would execute cord() twice.
Is there an elegant, efficient way to do this? Or should I just see that quote about premature optimization and forget about this? | ```
printa(*cord())
```
The `*` here is an argument expansion operator... well I forget what it's technically called, but in this context it takes a list or tuple and expands it out so the function sees each list/tuple element as a separate argument.
It's basically the reverse of the `*` you might use to capture all non-keyword arguments in a function definition:
```
def fn(*args):
# args is now a tuple of the non-keyworded arguments
print args
fn(1, 2, 3, 4, 5)
```
prints `(1, 2, 3, 4, 5)`
```
fn(*[1, 2, 3, 4, 5])
```
does the same. | Try this:
```
>>> def cord():
... return (1, 1)
...
>>> def printa(y, x):
... print a[y][x]
...
>>> a=[[1,2],[3,4]]
>>> printa(*cord())
4
```
The star basically says "use the elements of this collection as positional arguments." You can do the same with a dict for keyword arguments using two stars:
```
>>> a = {'a' : 2, 'b' : 3}
>>> def foo(a, b):
... print a, b
...
>>> foo(**a)
2 3
``` | Passing functions which have multiple return values as arguments in Python | [
"",
"python",
"return-value",
"function-calls",
""
] |
This [flickr blog post](http://code.flickr.com/blog/2009/03/18/building-fast-client-side-searches/) discusses the thought behind their latest improvements to the people selector autocomplete.
One problem they had to overcome was how to parse and otherwise handle so much data (i.e., all your contacts) client-side. They tried getting XML and JSON via AJAX, but found it too slow. They then had this to say about loading the data via a dynamically generated script tag (with callback function):
> ## JSON and Dynamic Script Tags: Fast but Insecure
>
> Working with the theory that large
> string manipulation was the problem
> with the last approach, we switched
> from using Ajax to instead fetching
> the data using a dynamically generated
> script tag. This means that the
> contact data was never treated as
> string, and was instead executed as
> soon as it was downloaded, just like
> any other JavaScript file. The
> difference in performance was
> shocking: 89ms to parse 10,000
> contacts (a reduction of 3 orders of
> magnitude), while the smallest case of
> 172 contacts only took 6ms. The parse
> time per contact actually decreased
> the larger the list became. This
> approach looked perfect, except for
> one thing: in order for this JSON to
> be executed, we had to wrap it in a
> callback method. **Since it’s executable
> code, any website in the world could
> use the same approach to download a
> Flickr member’s contact list.** This was
> a deal breaker. (emphasis mine)
Could someone please go into the exact security risk here (perhaps with a sample exploit)? How is loading a given file via the "src" attribute in a script tag different from loading that file via an AJAX call? | This is a good question and this exact sort of exploit was once used to steal contact lists from gmail.
Whenever a browser fetches data from a domain, it send across any cookie data that the site has set. This cookie data can then used to authenticate the user, and fetch any specific user data.
For example, when you load a new stackoverflow.com page, your browser sends your cookie data to stackoverflow.com. Stackoverflow uses that data to determine who you are, and shows the appropriate data for you.
The same is true for anything else that you load from a domain, including CSS and Javascript files.
The security vulnerability that Flickr faced was that any website could embed this javascript file hosted on Flickr's servers. Your Flickr cookie data would then be sent over as part of the request (since the javascript was hosted on flickr.com), and Flickr would generate a javascript document containing the sensitive data. The malicious site would then be able to get access to the data that was loaded.
Here is the exploit that was used to steal google contacts, which may make it more clear than my explanation above:
<http://blogs.zdnet.com/Google/?p=434> | If I was to put an HTML page on my website like this:
```
<script src="http://www.flickr.com/contacts.js"></script>
<script> // send the contact data to my server with AJAX </script>
```
Assuming contacts.js uses the session to know which contacts to send, I would now have a copy of your contacts.
However if the contacts are sent via JSON, I can't request them from my HTML page, because it would be a cross-domain AJAX request, which isn't allowed. I can't request the page from my server either, because I wouldn't have your session ID. | Security issue with dynamic script tags | [
"",
"javascript",
"security",
"json",
""
] |
I'm using Linq to SQL. I have a DataContext against which I am .SubmitChanges()'ing. There is an error inserting the identity field:
```
Cannot insert explicit value for identity column in table 'Rigs' when IDENTITY_INSERT is set to OFF.
```
The only identity field is "ID", which has a value of 0. It's defined in the DBML as:
```
[Column(Storage="_ID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
```
There are a few foreign keys, and I've verified they have values that jive with the foreign tables' content.
Why would I be getting this error?
Edit: Here is the query:
```
exec sp_executesql N'INSERT INTO [dbo].[Rigs]([id], [Name], [RAM], [Usage], [MoreInfo], [datetime], [UID])
VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6)
SELECT [t0].[id], [t0].[OSID], [t0].[Monitors]
FROM [dbo].[Rigs] AS [t0]
WHERE [t0].[id] = @p7',N'@p0 int,@p1 varchar(1),@p2 int,@p3 varchar(1),@p4 varchar(1),@p5 datetime,@p6 int,@p7
int',@p0=0,@p1='1',@p2=NULL,@p3='4',@p4='5',@p5=''2009-03-11 20:09:15:700'',@p6=1,@p7=0
```
Clearly it is passing a zero, despite having never been assigned a value.
Edit: Adding Code:
```
Rig rig = new Rig();
int RigID;
try
{ // Confirmed these always contain a nonzero value or blank
RigID = int.Parse(lbSystems.SelectedValue ?? hfRigID.Value);
if (RigID > 0) rig = mo.utils.RigUtils.GetByID(RigID);
}
catch { }
rig.Name = Server.HtmlEncode(txtName.Text);
rig.OSID = int.Parse(ddlOS.SelectedValue);
rig.Monitors = int.Parse(txtMonitors.Text);
rig.Usage = Server.HtmlEncode(txtUsage.Text);
rig.MoreInfo = Server.HtmlEncode(txtMoreInfo.Text);
rig.RigsToVideoCards.Clear();
foreach (ListItem li in lbYourCards.Items)
{
RigsToVideoCard r2vc = new RigsToVideoCard();
r2vc.VCID = int.Parse(li.Value);
rig.RigsToVideoCards.Add(r2vc);
}
rig.UID = c_UID > 0 ? c_UID : mo.utils.UserUtils.GetUserByToken(this.Master.LiveToken).ID;
if (!mo.utils.RigUtils.Save(rig))
throw new ApplicationException("There was an error saving your Rig. I have been notified.");
hfRigID.Value = rig.id.ToString();
public static User GetUserByToken(string token)
{
DataClassesDataContext dc = new DataClassesDataContext(ConfigurationManager.ConnectionStrings["MultimonOnlineConnectionString"].ConnectionString);
return (from u in dc.Users
where u.LiveToken == token
select u).FirstOrDefault();
}
```
Also, I notice that when I UPDATE an existing rig (insertonsubmit), it doesn't update. Profiler doesn't even show any queries being run. | Is your code setting the ID value explicitely to 0? (instead of leaving it untouched).
**Update 1:** As you posted on the updated version, linq2sql is clearly passing the value to the db. Here is one I haven't had any trouble with:
```
[Column(Storage="_CustomerID", AutoSync=AutoSync.Always, DbType="Int NOT NULL IDENTITY", IsDbGenerated=true)]
public int CustomerID
```
I just saw another one, and it has the same exact definition of the one you are using.
```
[Column(Storage="_TestID", AutoSync=AutoSync.OnInsert, DbType="Int NOT NULL IDENTITY", IsPrimaryKey=true, IsDbGenerated=true)]
public int TestID
```
**Update 2:** Regarding updates, you are not supposed to do InsertOnSubmit for that. Just update the values and call .SubmitChanges (should be throwing an exception). On the insert it is really weird, as the property attributes you posted seems to be correct, so the Insert method linq2sql generates should be correct as well. I would try, re-adding the table on the designer again and verifying all the properties are correct.
Note that the generated insert method should look like (with a matchingRig\_Insert):
```
private void InsertRig(Rig obj)
{
System.Nullable<int> p1 = obj.Id;
```
this.Rig\_Insert(/\* bunch of values \*/, ref p1);
obj.Id = p1.GetValueOrDefault();
} | My theory of what happened is as follows:
1. You designed and created the DataBase
2. You created the DB Context using LINQ TO SQL in visual Studio
3. You forgot to set the auto-identity to your table
4. You fixed that by going to your DataBase and setting the auto-identity
5. **But you forgot to recreate/update your LINQ TO SQL DB Context!!!**
:D | Linq to SQL: Why am I getting IDENTITY_INSERT errors? | [
"",
"c#",
"linq",
"linq-to-sql",
"identity-insert",
""
] |
I'm currently in charge of setting up a polling system (using PHP).
Now for it to be as secure and objective as possible, it's important that a visitor can only vote once. I'm thinking of validating the polls by visitor's IP (there can be only one vote from one IP), and maybe throw in a captcha test to be sure that no bots can get in once they've passed the IP validation for some reason.
1. So there it is, unique-IP validation and captcha. But is this enough ? Is there a possibility that a single user can change his/her IP by using proxies or other ways I don't know of, and vote multiple times with unique IPs ?
2. Are there better ways to do this ? Preferably without the captcha.
Thanks in advance. | There is absolutely **no way to be sure** a user has voted once when it's a public voting system, where no login is required.
Checking the IP is not a good idea for several reason. As described in other answers, lots of networks are behind one ip, and users can just use an other pc with different ip and vote again.
**OpenId**
Use OpenId to identify the user and check if they have already voted.
**Register users**
Optionally you could allow users to register themselves if they do not have an openid account.
To implement a secure system, where session spoofing, and thus multiple voting, is made difficult [read this](http://jaspan.com/improved_persistent_login_cookie_best_practice) | You can't create a 100% secure voting system.
* If it's based on registration/IP/cookie, the user can create a new user/get an another PC/delete all cookie.
But you can try it with **auto prefilter + administrator as postfilter** workflow:
* Prevent multiple voting with cookie (or IP / browser properties / etc.) filtering *automatically*.
* On an admin view, the administrator can parse and delete votes *by hand* based on IP or subnet address. This is nor a perfect solution, but with some good query (same votes in the same time intervall from the same IP/subnet) the administrator can easily delete suspicious votes.
One big drawback of this solution is the need of an administrator. But - I think - there is no perfect solution. | Setting up a secure polling system | [
"",
"php",
"validation",
""
] |
I'm having problems trying to overload the post increment operator in C#. Using integers we get the following results.
```
int n;
n = 10;
Console.WriteLine(n); // 10
Console.WriteLine(n++); // 10
Console.WriteLine(n); // 11
n = 10;
Console.WriteLine(n); // 10
Console.WriteLine(++n); // 11
Console.WriteLine(n); // 11
```
But, when I try it using classes, it looks like the objects are exchanged.
```
class Account
{
public int Balance { get; set; }
public string Name { get; set; }
public Account(string name, int balance)
{
Balance = balance;
Name = name;
}
public override string ToString()
{
return Name + " " + Balance.ToString();
}
public static Account operator ++(Account a)
{
Account b = new Account("operator ++", a.Balance);
a.Balance += 1;
return b;
}
public static void Main()
{
Account a = new Account("original", 10);
Console.WriteLine(a); // "original 10"
Account b = a++;
Console.WriteLine(b); // "original 11", expected "operator ++ 10"
Console.WriteLine(a); // "operator ++ 10", expected "original 11"
}
}
```
Debugging the application, the overloaded operator method, returns the new object with the old value (10) and the object that has been passed by reference, has the new value (11), but finally the objects are exchanged. Why is this happening? | The key is in understanding how the line `Account b = a++;` works. Given how your code is written, this line is the equivalent of this:
```
Account b = a;
a++;
```
And that is the order it will execute in. The assignment effectively(1) happens before the increment. So, the first effect of this line is that *a* and *b* both refer to the original object *a*.
Now the ++ portion will be evaluated. Inside of the operator method, we increment the `Balance` of the original object. At this point *a* and *b* are both pointing at the original, with a `Balance` of 11, and *b* will continue to do so.
However, you've created a new object inside the operator method and returned it as the output of the operator. *a* will now be updated to point at the newly created object.
So, *a* now points to a new object, while *b* continues to point to the original. That's why the WriteLine output appears swapped.
As @MarkusQ pointed out, the ++ operator is meant to do in-place modification. By generating a new object, you're breaking that assumption. Operator overloading on objects is a tricky subject, and this is an excellent example of why it's better avoided in most cases.
---
1 - *Just for accuracy's sake, the assignment does not actually happen before the increment when dealing with operators on objects, but the end result is the same in this case. Actually, the original object reference is copied, the operation is carried out on the original, and then the copied reference is assigned to the left-hand variable. It's just easier to explain if you pretend that assignment happens first.*
What's really happening is that this:
```
Account b = a++;
```
results in this, due to how the ++ operator works on objects:
```
Account copy = a;
Account x = new Account("operator ++", a.Balance);
a.Balance += 1; // original object's Balance is incremented
a = x; // a now points to the new object, copy still points to the original
Account b = copy; // b and copy now point at the same, original, object
``` | My first thought was to point out that the normal semantics of ++ are *in-place modification*. If you want to mimic that you'd write:
```
public static Account operator ++(Account a)
{
a.Balance += 1;
return a;
}
```
and not create a new object.
But then I realized that you were trying to mimic the post increment.
So my second thought is "don't do that" -- the semantics don't map well at all onto objects, since the value being "used" is really a mutable storage location. But nobody likes to be told "don't do that" by a random stranger so I'll let [Microsoft tell you not to do it](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=243943). And I fear their word is final on such matters.
P.S. As to *why* it's doing what it does, you're really overriding the preincrement operator, and then using it *as if* it were the postincrement operator. | Post-increment Operator Overloading | [
"",
"c#",
"operator-overloading",
""
] |
> **Possible Duplicate:**
> [Interface defining a constructor signature?](https://stackoverflow.com/questions/619856/interface-defining-a-constructor-signature)
I know that you cannot specify a constructor in an interface in .Net, but why can we not?
It would be really useful for my current project to be able to specify that an 'engine' must be passed in with the constructor, but as I cant, I have to suffice with an XML comment on the class. | Because an interface describes behaviour. Constructors aren't behaviour. How an object is built is an implementation detail. | How would you call the constructor? When you use interfaces, you normally pass an instance of the interface around (or rather, a reference). Also bear in mind that if one class implements an interface, a derived class inherits that interface, but may not have the same set of constructors.
Now, I can see the use of what I call *static interfaces* for specifying constructors and other essentially static members for use in generic methods. See [my blog post on the idea](http://codeblog.jonskeet.uk/2008/08/29/lessons-learned-from-protocol-buffers-part-4-static-interfaces/) for more information. | Why are we not allowed to specify a constructor in an interface? | [
"",
"c#",
".net",
"vb.net",
"oop",
""
] |
How can I make a website multilingual?
I want to create a website and in the home page i want the client to choose a language from English and Arabic. Then the whole website is converted to that language. What should I do to achieve this? I am creating this website in asp.net 2.0 with C# | What you're asking for is a tutorial, which you really should try googling for. Look at the links below, if there's something particular, more specific you don't understand - ask the question here.
<http://www.beansoftware.com/ASP.NET-Tutorials/Globalisation-Multilingual-CultureInfo.aspx>
<http://www.asp.net/learn/Videos/video-40.aspx>
<http://www.about2findout.com/blog/2007/02/aspnet-multilingual-site_10.html>
Good luck! | ASP.NET can use a number of mechanisms to change language settings - however you will need to perform the translations your self.
You could look at using Resource files for the common elements of your site - see this answer to [Currency, Calendar changes to selected language, but not label in ASP.NET](https://stackoverflow.com/questions/608226/currency-calendar-changes-to-selected-language-but-not-label-in-asp-net/610314#610314)
However, for the main content you'd probably want to do something with the URL to ensure that your content is served correctly - the links that Honsa has supplied would be a good place to start. | language setting for a website | [
"",
"c#",
"asp.net",
".net-2.0",
""
] |
What is the best practice for right-justifying a numeric in TSQL?
I have to format a fixed length extract file and need to have the Numeric fields right justified. (I am using SQL Server 2005)
I found [this](http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=104823), which seems pretty straight forward.
```
right(' '+convert(varchar(20),a.num),12)
```
Here is the full Select statement
```
select
a.num,
fixed_number =
right(' '+convert(varchar(20),a.num),12)
from
(
--Test Data
select num = 2400.00 union all
select num = 385.00 union all
select num = 123454.34
) a
Results:
num fixed_number
---------- ------------
2400.00 2400.00
385.00 385.00
123454.34 123454.34
(3 row(s) affected)
```
I am asking this question because I found this line of code at work, which appears INSANELY complex (It is also removing the decimal and zero filling)
```
CAST(REPLACE(REPLICATE('0', 12 - LEN(REPLACE(CAST(CONVERT(DECIMAL(10,2),@DD8DBAMT) AS VARCHAR),'.','')))
+ CAST(CONVERT(DECIMAL(10,2),@DD8DBAMT) AS VARCHAR),'.','') AS VARCHAR(12))
```
**Updated:**
Daniel Pratt's idea of using a function got me looking at [SQL#](http://www.sqlsharp.com/) (which we own). It has a function called [PadLeft](http://www.sqlsharp.com/features/), which surprisingly enough had the same parameters and functionality as Daniel Pratt's fn\_PadRight function defined in his answer below.
Here is how to use SQL# function:
```
DECLARE @F6D2 AS DECIMAL(8,2)
SET @F6D2 = 0
SQL#.String_PadLeft(@F6D2,9,' ')
SQL#.String_PadLeft(123.400,9,' ')
SQL#.String_PadLeft('abc',9,' ')
```
It can take both numbers and strings. | The only thing I can suggest to help with the "insane complexity" is to encapsulate it in one or more functions. Here's a somewhat modified version of something we're using:
```
CREATE FUNCTION [dbo].[fn_PadRight]
(
@Value nvarchar(4000)
,@NewLength int
,@PadChar nchar(1) = ' '
) RETURNS nvarchar(4000)
AS
BEGIN
DECLARE @ValueLength int
SET @ValueLength = LEN(@Value)
IF (@NewLength > @ValueLength) BEGIN
SET @Value = @Value + REPLICATE(@PadChar, @NewLength - @ValueLength)
END
RETURN @Value
END
GO
CREATE FUNCTION [dbo].[fn_FormatAmountDE]
(
@Value money
) RETURNS nvarchar(4000)
AS
BEGIN
RETURN [dbo].[fn_PadRight](REPLACE(CAST(@Value AS varchar), '.', ''), 12, '0')
END
GO
``` | Your not going like my answer, but the best practice is to do this someplace other then SQL. SQL is meant to store retrieve and process data not visualize it. Not format it for display. You'd be much better IMHO having a console application that pulls the data then generates the file.
But with that said when I did this before, I did it like this:
```
declare @num int
set @num=1555
select replicate(' ',20-len(cast(@num as varchar))) + cast(@num as varchar)
```
Hardcoding spaces so nasty, this will probally break for a huge number but then again if your generating a fixed file your going generate garbage anyways for a huge number
# Edit
Ken I did read the ops post, and yes he is formatting the data into a fixed width file. The point is that you should do formatting in an application tier, not in SQL. Yes there is no one visually looking at the data, but I guess I feel like you are still formating the data, we are probally splitting hairs. | Best practice for right-justifying a Numeric in TSQL | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Does anyone know where I can find a discussion on how type inference works when using Generics in Java. | This is originally specified in [Section 15.12.2.7 of the Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#341287), as a result of the [Java Specification Requests #14](http://jcp.org/en/jsr/detail?id=14).
You may also find various discussions on the subject, such as [Generics - type inference from context](http://forums.sun.com/thread.jspa?threadID=428361&forumID=316) or [Type Argument Inference at the Generics FAQ](http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html#Type+Argument+Inference), etc. | I recommend [Angelika Langer's site](http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html) for more information on Java generics. She does have a discussion on [type inference](http://www.angelikalanger.com/GenericsFAQ/FAQSections/TechnicalDetails.html#Type%20Argument%20Inference). | What rules are used for type inference when using Generics | [
"",
"java",
"generics",
"type-inference",
""
] |
Suppose I have a string `"011100011"`.
Now I need to find another string by adding the adjacent digits of this string, like the output string should be `"123210122"`.
How do I split each characters in the string and manipulate them?
The method that I thought was to convert the string to integer using Parsing and splitting each character using modulus or something and performing operations on them.
But can you suggest some simpler methods? | Here's a solution which uses some LINQ plus dahlbyk's idea:
```
string input = "011100011";
// add a 0 at the start and end to make the loop simpler
input = "0" + input + "0";
var integers = (from c in input.ToCharArray() select (int)(c-'0'));
string output = "";
for (int i = 0; i < input.Length-2; i++)
{
output += integers.Skip(i).Take(3).Sum();
}
// output is now "123210122"
```
Please note:
* the code is not optimized. E.g. you might want to use a StringBuilder in the for loop.
* What should happen if you have a '9' in the input string -> this might result in two digits in the output string. | Try converting the string to a character array and then subtract `'0'` from the `char` values to retrieve an integer value. | String operations in C# | [
"",
"c#",
""
] |
What is the best way to define that a value does not exist in PHP, or is not sufficent for the applications needs.
`$var = NULL`, `$var = array()`, `$var = FALSE`?
And what is the best way to test?
`isset($var)`, `empty($var)`, `if($var != NULL)`, `if($var)`?
Initializing variables as what they will be, e.g. `NULL` if a string, `array()` if they will be arrays, has some benefits in that they will function in the setting they are ment to without any unexpected results.
e.g. `foreach($emptyArray)` won't complain it just wont output anything, whereas `foreach($false)` will complain about the wrong variable type.
But it seams like an unnecessary hassle to have so many different ways of doing basically the same thing. eg. `if(empty($var))` or `if ($var == NULL)`
---
**Duplicate:** [Best way to test for a variable’s existence in PHP; isset() is clearly broken](https://stackoverflow.com/questions/418066) | Each function you named is for different purposes, and they should be used accordingly:
* **[empty](https://www.php.net/manual/en/function.empty.php)**: tells if an existing variable is with a value that could be considered empty (0 for numbers, empty array for arrays, equal to NULL, etc.).
* **[isset($var)](https://www.php.net/manual/en/function.isset.php)**: tells if the script encountered a line before where the variable was the left side of an assignment (i.e. $var = 3;) or any other obscure methods such as [extract](https://www.php.net/manual/en/function.extract.php), [list](https://www.php.net/manual/en/function.list.php) or [eval](https://www.php.net/manual/en/function.eval.php). This is *the* way to find if a variable has been set.
* **[$var == NULL](https://www.php.net/manual/en/types.comparisons.php)**: This is tricky, since 0 == NULL. If you really want to tell if a variable is NULL, you should use triple =: $var === NULL.
* **[if($var)](https://www.php.net/manual/en/types.comparisons.php)**: same as $var == NULL.
As useful link is <https://www.php.net/manual/en/types.comparisons.php>.
The way to tell if the variable is good for a piece of script you're coding will entirely depend on your code, so there's no single way of checking it.
One last piece of advice: if you expect a variable to be an array, don't wait for it to be set somewhere. Instead, initialize it beforehand, then let your code run and maybe it will get overwritten with a new array:
```
// Initialize the variable, so we always get an array in this variable without worrying about other code.
$var = array();
if(some_weird_condition){
$var = array(1, 2, 3);
}
// Will work every time.
foreach($var as $key => $value){
}
``` | Another thing to remember is that since php is liberal in what it allows to evaluate to NULL or empty, it's necessary to use the identity operators (===, !== see [http://php.net/operators.comparison](http://ca.php.net/operators.comparison). This is the reason why all of these comparison and equality functions exists, since you often have to differentiate between values with subtle differences.
If you are explicitly checking for NULL, always use $var === NULL | Detecting insufficient PHP variables: FALSE vs NULL vs unset() vs empty()? | [
"",
"php",
""
] |
Does anyone have an example of implementing Orbital Mechanics (preferably in XNA)? The code I am currently using is below, but it doesn't "feel right" when it executes. The object just bends ever so slightly to the planet, and no matter how much I tweak the variables I cant get it to enter an orbit, or even a partial orbit.
```
shot.Position += shot.Velocity;
foreach (Sprite planet in planets)
{
Vector2 directionToPlanet = (planet.Position - shot.Position);
directionToPlanet.Normalize();
float distance = Vector2.DistanceSquared(shot.Position, planet.Position);
float gPull = (float)(planet.gravityStrength * (planet.Mass * shot.Mass) / distance) + planet.gravityField;
shot.Position += new Vector2(directionToPlanet.X * gPull, directionToPlanet.Y * gPull);
}
```
**Edit**
Marking Mendelt's answer correct for pointing out that I need to update the velocity, not the position. I also needed to change the calculation of gPull to
```
float gPull = shot.Mass * planet.Mass / distanceSqr * planet.gStr;
``` | In the last line you're updating the position of the shot. You should be updating the velocity.
You might want to take a look at the code in this blogpost <http://blog.mendeltsiebenga.com/post/Fun-with-planets.aspx> No xna, but working orbital mechanics. (although i never got rid of the screen-flicker) | [Newton-Raphson iteration](http://en.wikipedia.org/wiki/Newton%27s_method) is not a stable way to solve this problem (that is you *can't* get it right using so simple an integrator for the differential equation). Consider using a second (or higher) order solution: [Runge-Kutta](http://en.wikipedia.org/wiki/Runge-Kutta_methods) is good and is fairly easy to implement in this case.
From the point of view of numeric analysis, the problem of orbital mechanics reduces to that of solving the set of coupled differential equations:
```
x_i'' + G m_i \sum_{i != j} m_j r_ji/(|r_ji|)^3 = 0
```
where the `x`'s are three-vectors representing the positions of the bodies, the `m`'s are the masses of the same bodies, and `r_ji = x_j - x_i` is the vector displacement between bodies `j` and `i`. | Orbital Mechanics | [
"",
"c#",
"xna",
"physics",
""
] |
I hope I'm not writing a duplicate, but I haven't found anything that answers my question. (Although it seems to me to be quite common problem.)
The problem occurs in nearly every web project: You have a table with many many entries and want them to be displayed on single pages.
Now I wonder what's the best way to compute the number of pages needed for a certain set of table rows.
Here some approaches I've been thinking of. I'd like to get some response on how effective they are. I'll give PHP-specific examples, but I bet there are similar techniques in other languages.
1. The probably best way is to save the number of pages statically and modify the value every time a new entry is added. (Nevertheless... I'm looking for a dynamic solution :-) )
2. Do a `SELECT COUNT(*)` over the rows of interest and compute the page number every time the page is displayed.
3. Do a ordinary select to get a result set for all rows. Now don't load the rows by calling `mysql_fetch_row` or so, but get the number of rows with `mysql_num_rows`. (Since I have no idea how this is implemented I cannot say whether it is effective or not. Anyone who knows?) Then I could comfortably move the result set pointer. (For `mysqli` there is `mysql_data_seek`, but the native MySQL extension has no similar function. Therefore I assume that this is just some buffering behaviour of `mysqli`)
Can anyone say how to count the number of rows (number of pages) most effectively? | Number 2 is the most common pattern
```
select count(*) from [Table] where [Expressions]
```
And then
```
select [Columns] from [Table] where [Expressions] limit [Pagesize] offset [Pagenum*Pagesize-Pagesize]
```
This gives you the total rows for the entire result set, but only the data of the rows for the current page.
Many frameworks or CMSes have conventions for caching certain parts of this data in the session which you may or may-not want to do depending on you expected table sizes, volatility of data, etc. | If you really wanted to something of truely WTF proportions, you could always keep track of how many rows there were by incrementing some register using a trigger on insert/delete.
But I think this is an answer asking for yet more questions ;).
Just use SELECT COUNT if you have to. If its slow, that means your database is built wrong usually.
Also, I have the feeling there is premature optimisation creeping in here. Don't optimise prematurely. Make it make sense, and then make it make sense better. Make sense? | How to determine the "number of pages" most effectively? | [
"",
"php",
"database",
"pagination",
""
] |
```
int main()
{
char myString = NULL;
realloc(&myString, 5);
strncpy((char *)&myString, "test", 5);
}
```
Seems to work fine but I'm still slightly confused about stack vs heap. Is this allowed? If it is allowed, does `myString` need to be freed manually or will it be released when it goes out of scope?
---
Edit: Thanks for the responses, so i presume this is equally illegal
```
//I want the code to change myString to "tests"
char myString[5] = "test";
realloc(&myString, strlen(myString)+2);
myString[4] = 's';
myString[5] = '\0';
``` | No, this is completely wrong. realloc should only be used to reallocate memory allocated by malloc, what you are doing works only by accident, and will eventually crash horribly
```
char *myString = malloc(x);
myString = realloc(myString,y);
free(myString)
```
You are better off using new and delete, and even better off using std::string, however. | **Some problems with the code you posted:**
* Yes you need to free everything you allocate with malloc, and realloc, and the other related C style memory allocation functions.
* I think you meant to have char \*myString, not char. Passing in the address of something on the stack (your char) is completely wrong.
* You need to initialize your myString char pointer to NULL before using it in realloc.
* You should be passing 4 into strncpy not 5, if you had a larger string you'd be overwriting memory.
* You should be freeing the buffer you created in your example
* You should be checking the return value of your realloc call. realloc()
> [Regarding realloc's return value:] Upon successful completion with a size
> not equal to 0, realloc() returns a
> pointer to the (possibly moved)
> allocated space. If size is 0, either
> a null pointer or a unique pointer
> that can be successfully passed to
> free() is returned. If there is not
> enough available memory, realloc()
> returns a null pointer and sets errno
> to [ENOMEM].
* re-alloc will work like malloc when you pass in NULL:
> If ptr is a null pointer, realloc()
> behaves like malloc() for the
> specified size.
**A more C++ way to do it:**
You tagged this as C++ though, and it's more type safe to use C++'s new operator. Although the new operator does not allow for re-allocations, it will work for allocations and for re-using existing buffers (placement new).
```
char *myString = new char[5];
strncpy(myString, "test", 4);
//...
delete[] myString;
```
or even:
```
#include <string>
//...
std::string str = "test";
```
[Source of top 2 quotes](http://www.opengroup.org/onlinepubs/007908775/xsh/realloc.html) | Is it valid to pass a pointer to a stack variable to realloc()? | [
"",
"c++",
"c",
"memory",
"memory-management",
"heap-corruption",
""
] |
I'm using Symfony 1.2 in a standard Propel form class.
```
public function configure()
{
$this->setWidgets(array(
'graduate_job_title' => new sfWidgetFormInput( array(), array( 'maxlength' => 80, 'size' => 30, 'value' => '' ) )
));
//etc
}
```
However, I want the value of this field to come from the user information, which I'd normally access using `$this->getUser()->getAttribute( '...' )`. However, this doesn't seem to work in the form.
What should I be using? | Does that work?
```
sfContext::getInstance()->getUser()->getAttribute('...');
```
**// Edit** : See cirpo's recommandation on the use of sfContext instead. | It's a very bad idea to rely on the sfContext instance.
It's better to pass what you need during sfForm initialization in the options array parameter.
<http://www.symfony-project.org/api/1_4/sfForm>
\_\_contruct method
for example in your action:
```
$form = new myForm(null,
array('attributeFoo' =>
$this->getUser()->getAttribute('attributeFoo'));
```
and then retrieve the value inside the form class:
> $this->getOption('attributeFoo');
cirpo | How to get user data in form in Symfony 1.2? | [
"",
"php",
"symfony1",
""
] |
I have a string that is like below.
```
,liger, unicorn, snipe,
```
how can I trim the leading and trailing comma in javascript? | because I believe everything can be solved with regex:
```
var str = ",liger, unicorn, snipe,"
var trim = str.replace(/(^,)|(,$)/g, "")
// trim now equals 'liger, unicorn, snipe'
``` | While cobbal's answer is the "best", in my opinion, I want to add one note: Depending on the formatting of your string and purpose of stripping leading and trailing commas, you may also want to watch out for whitespace.
```
var str = ',liger, unicorn, snipe,';
var trim = str.replace(/(^\s*,)|(,\s*$)/g, '');
```
Of course, with this application, the value of using regex over basic string methods is more obvious. | How can I trim the leading and trailing comma in javascript? | [
"",
"javascript",
""
] |
I'm trying to rename a file after it's uploaded in the model's save method. I'm renaming the file to a combination the files primary key and a slug of the file title.
I have it working when a file is first uploaded, when a new file is uploaded, and when there are no changes to the file or file title.
However, when the title of the file is changed, and the system tries to rename the old file to the new path I get the following error:
```
WindowsError at /admin/main/file/1/
(32, 'The process cannot access the file because it is being used by another process')
```
I don't really know how to get around this. I've tried just coping the file to the new path. This works, but I don't know I can delete the old version.
Shortened Model:
```
class File(models.Model):
nzb = models.FileField(upload_to='files/')
name = models.CharField(max_length=256)
name_slug = models.CharField(max_length=256, blank=True, null=True, editable=False)
def save(self):
# Create the name slug.
self.name_slug = re.sub('[^a-zA-Z0-9]', '-', self.name).strip('-').lower()
self.name_slug = re.sub('[-]+', '-', self.name_slug)
# Need the primary key for naming the file.
super(File, self).save()
# Create the system paths we need.
orignal_nzb = u'%(1)s%(2)s' % {'1': settings.MEDIA_ROOT, '2': self.nzb}
renamed_nzb = u'%(1)sfiles/%(2)s_%(3)s.nzb' % {'1': settings.MEDIA_ROOT, '2': self.pk, '3': self.name_slug}
# Rename the file.
if orignal_nzb not in renamed_nzb:
if os.path.isfile(renamed_nzb):
os.remove(renamed_nzb)
# Fails when name is updated.
os.rename(orignal_nzb, renamed_nzb)
self.nzb = 'files/%(1)s_%(2)s.nzb' % {'1': self.pk, '2': self.name_slug}
super(File, self).save()
```
I suppose the question is, does anyone know how I can rename an uploaded file when the uploaded file isn't be re-uploaded? That's the only time it appears to be locked/in-use.
---
**Update:**
Tyler's approach is working, except when a new file is uploaded the primary key is not available and his technique below is throwing an error.
```
if not instance.pk:
instance.save()
```
Error:
```
maximum recursion depth exceeded while calling a Python object
```
Is there any way to grab the primary key? | I think you should look more closely at the upload\_to field. This would probably be simpler than messing around with renaming during save.
<http://docs.djangoproject.com/en/dev/ref/models/fields/#filefield>
> This may also be a callable, such as a
> function, which will be called to
> obtain the upload path, including the
> filename. This callable must be able
> to accept two arguments, and return a
> Unix-style path (with forward slashes)
> to be passed along to the storage
> system. The two arguments that will be
> passed are: | My other answer is deprecated, use this instead:
```
class File(models.Model):
nzb = models.FileField(upload_to=get_filename)
...
def get_filename(instance, filename):
if not instance.pk:
instance.save()
# Create the name slug.
name_slug = re.sub('[^a-zA-Z0-9]', '-', instance.name).strip('-').lower()
name_slug = re.sub('[-]+', '-', name_slug)
filename = u'filess/%(2)s_%(3)s.nzb' % {'2': instance.pk, '3': name_slug}
return filename
```
As of 1.0, [`upload_to` can be callable](http://docs.djangoproject.com/en/dev/ref/models/fields/#django.db.models.FileField.upload_to), in which case it is expected to return the filename, including path (relative to MEDIA\_ROOT). | Django: Uploaded file locked. Can't rename | [
"",
"python",
"django",
"file-io",
""
] |
Why it is not allowed to assign null to a DateTime in C#? How has this been implemented? And can this feature be used to make your own classes non-nullable?
Example:
```
string stringTest = null; // Okay
DateTime dateTimeTest = null; // Compile error
```
I know that I can use `DateTime?` in C# 2.0 to allow null to be assigned to dateTimeTest and that I could use [Jon Skeet's NonNullable class](http://msmvps.com/blogs/jon_skeet/archive/2008/10/06/non-nullable-reference-types.aspx) on my string to get a run time error on the assignment of stringTest. I'm just wondering why the two types behave differently. | `DateTime` is a value-type (`struct`), where-as string is a reference-type (`class` etc). That is the key difference. A reference can always be null; a value can't (unless it uses `Nullable<T>` - i.e. `DateTime?`), although it can be zero'd (`DateTime.MinValue`), which is often interpreted as the same thing as null (esp. in 1.1). | DateTime is a struct and not a class. Do a 'go to definition' or look at it in the object browser to see.
HTH! | Why is null not allowed for DateTime in C#? | [
"",
"c#",
"non-nullable",
""
] |
So is the following equivalent in memory usage?
```
System.Threading.Thread.Sleep(500);
```
vs
```
using System.Threading;
...
Thread.Sleep(500);
```
I would have thought that the less namespaces you're 'using' in memory the better, but I've heard that the former example has to load the namespace into memory regardless. I know `Sleep` isn't the best example of a memory hungry method but it's just an example. | The `using` statement doesn't cause anything at all to be loaded, it only tells the compiler where to look for classes.
The two examples produces exactly the same code. | The two produce exactly the same IL when compiled, as said in the other posts.
There is a difference, though. The first option explicitly lets the compiler know where to go for the class/method/struct/etc. The second options includes the namespace (System.Threading) into the compiler's list of namespaces to search.
If you have many namespaces in using statements, it will cause the compiler to take longer to compile this file. With C#, this is probably not something you'd ever care about, since the compiler is so damn fast, but it does slow things down.
With a very large project, and very large namespaces (which isn't a good idea for other reasons), this can be noticeable (although still subtle). | Is referencing a method/variable in an external namespace more memory efficient than including it entirely? | [
"",
"c#",
""
] |
I have this:
```
double myDecimal = static_cast<double>(atoi(arg_vec[1]));
cout << myDecimal << endl;
```
But why when I pass the argument like this:
```
./MyCode 0.003
```
It prints `0` instead of `0.003`. | [`atoi()`](http://linux.die.net/man/3/atoi) converts to integer. You want [`atof()`](http://linux.die.net/man/3/atof).
Or you could use [strtod().](http://www.cplusplus.com/reference/clibrary/cstdlib/strtod.html) | atoi() converts to an integer, you want atof(), which converts to a double | How to Pass Decimal Value as Argument Correctly | [
"",
"c++",
"decimal",
"argument-passing",
""
] |
I'm looking for clean way to break my current habit of using print commands in PHP when I want to see what's happening.
I am aware of options such as Zend Debugger but I use [Coda](http://www.panic.com/coda/) for development and I'm not interested in mixing other software or having to do server commands. I just need a console that can be added to my codebase and then turned on/off.
Does anything like this exist? Furthermore, what do you use and why?
**EDIT**: There was a lot of stuff out there but I needed something even simpler so I ended up coding it myself. It didn't take long (nor is it very pretty) but I've put it up on [my server](http://www.pieffedesign.com/free/Console.zip) for anyone else interested. | You can use [Xdebug](http://xdebug.org/) in combination with any one of the [many options available to view its debugging info](http://xdebug.org/docs/remote). | There is very good extension for Google Chrome - [PHP Console](https://chrome.google.com/extensions/detail/nfhmhhlpfleoednkpnnnkolmclajemef). | PHP Console that doesn't require heavy installation or a desktop app? | [
"",
"php",
"console",
""
] |
In my Android app, I always get VerifyErrors! And I cannot figure out why. Whenever I include a external JAR, I always get VerifyErrors when I try to launch my app (except for once, when I included Apache Log4j.)
I usually get around this by taking the source of the library and adding it to my project, but I am trying to put the [GData client library](http://code.google.com/p/gdata-java-client/).
I can get this in source, but it's dependencies (mail.jar, activation.jar, servlet-api.jar) I cannot, so I get verify errors. I would like to get to the root of this problem once and for all. I looked on the internet, but they all seem to talk about incomplete class files? which I do not know of. | Android uses a different class file format. Are you running the 3rd party JAR files through the "dx" tool that ships with the Android SDK? | Look at LogCat and see what's causing the verifyerror. It's probably some method in a java.lang class that is not supported on the android SDK level you are using (for instance, String.isEmpty()). | Android java.lang.VerifyError? | [
"",
"java",
"android",
"gdata",
"verifyerror",
""
] |
I recently attended an interview and they asked me the question "Why Interfaces are preferred over Abstract classes?"
I tried giving a few answers like:
* We can get only one Extends functionality
* they are 100% Abstract
* Implementation is not hard-coded
They asked me take any of the JDBC api that you use. "Why are they Interfaces?".
Can I get a better answer for this? | That interview question reflects a certain belief of the person asking the question. I believe that the person is wrong, and therefore you can go one of two directions.
1. Give them the answer they want.
2. Respectfully disagree.
The answer that they want, well, the other posters have highlighted those incredibly well.
Multiple interface inheritance, the inheritance forces the class to make implementation choices, interfaces can be changed easier.
However, if you create a compelling (and correct) argument in your disagreement, then the interviewer might take note.
First, highlight the positive things about interfaces, this is a MUST.
Secondly, I would say that interfaces are better in many scenarios, but they also lead to code duplication which is a negative thing. If you have a wide array of subclasses which will be doing largely the same implementation, plus extra functionality, then you might want an abstract class. It allows you to have many similar objects with fine grained detail, whereas with only interfaces, you must have many distinct objects with almost duplicate code.
Interfaces have many uses, and there is a compelling reason to believe they are 'better'. However you should always be using the correct tool for the job, and that means that you can't write off abstract classes. | In general, and this is by no means a "rule" that should be blindly followed, the most flexible arrangement is:
```
interface
abstract class
concrete class 1
concrete class 2
```
The interface is there for a couple of reasons:
* an existing class that already extends something can implement the interface (assuming you have control over the code for the existing class)
* an existing class can be subclasses and the subclass can implement the interface (assuming the existing class is subclassable)
This means that you can take pre-existing classes (or just classes that MUST extend from something else) and have them work with your code.
The abstract class is there to provide all of the common bits for the concrete classes. The abstract class is extended from when you are writing new classes or modifying classes that you want to extend it (assuming they extend from java.lang.Object).
You should always (unless you have a really good reason not to) declare variables (instance, class, local, and method parameters) as the interface. | Why are interfaces preferred to abstract classes? | [
"",
"java",
"oop",
"interface",
"abstraction",
""
] |
I have this code:
```
>>> class G:
... def __init__(self):
... self.x = 20
...
>>> gg = G()
>>> gg.x
20
>>> gg.y = 2000
```
And this code:
```
>>> from datetime import datetime
>>> my_obj = datetime.now()
>>> my_obj.interesting = 1
*** AttributeError: 'datetime.datetime' object has no attribute 'interesting'
```
From my Python knowledge, I would say that `datetime` overrides `setattr`/`getattr`, but I am not sure. Could you shed some light here?
EDIT: I'm not specifically interested in `datetime`. I was wondering about objects in general. | My guess, is that the implementation of datetime uses [\_\_slots\_\_](http://docs.python.org/reference/datamodel.html#id3) for better performance.
When using `__slots__`, the interpreter reserves storage for just the attributes listed, nothing else. This gives better performance and uses less storage, but it also means you can't add new attributes at will.
Read more here: <http://docs.python.org/reference/datamodel.html> | It's written in C
<http://svn.python.org/view/python/trunk/Modules/datetimemodule.c?view=markup>
It doesn't seem to implement setattr. | Why can't I directly add attributes to any python object? | [
"",
"python",
"attributes",
"object",
""
] |
I'm wondering if there's a way to automatically stub in the Global.asax's event handlers? Thus far, I've not been able to find any examples of how to do this. Seems I have to just find the list of delegate names available to me and type them in manually.
Intellisense doesn't seem to lend any useful info on the subject either. | The ASP.Net runtime uses reflection to dynamically look for methods with names like "Application\_Start", "Session\_Start" etc. and then binds them to the corresponding events on the HttpApplication class. You can effectively bind to any of the HttpApplication events simply by including a method in Global.asax.cs whose name is "Application\_" followed by the name of the event. For example, to utilize the EndRequest event, add this to your Global.asax.cs file:
```
protected void Application_EndRequest(object sender, EventArgs e)
{
// Your code here
}
```
See this [Blog Entry](http://www.west-wind.com/weblog/posts/2009/Jun/18/How-do-ASPNET-Application-Events-Work) from Rick Strahl for a bunch of helpful information on how this is done. | All of the events of the [`HttpApplication`](http://msdn.microsoft.com/en-us/library/system.web.httpapplication.aspx) class can have a handler in the global.asax. | Automatic Event Wiring in Global.asax | [
"",
"c#",
"asp.net",
"web-applications",
"event-handling",
"global-asax",
""
] |
How do you kill a `java.lang.Thread` in Java? | See this [thread by Sun on why they deprecated `Thread.stop()`](http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html). It goes into detail about why this was a bad method and what should be done to safely stop threads in general.
The way they recommend is to use a shared variable as a flag which asks the background thread to stop. This variable can then be set by a different object requesting the thread terminate. | Generally you don't..
You ask it to interrupt whatever it is doing using [Thread.interrupt() (javadoc link)](http://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#interrupt%28%29)
A good explanation of why is in the javadoc [here (java technote link)](http://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html) | How do you kill a Thread in Java? | [
"",
"java",
"multithreading",
""
] |
Is the use of server side javascript prevalent? Why would one use it as opposed the any other server side scripting? Is there a specific use case(s) that makes it better than other server side languages?
Also, confused on how to get started experimenting with it, I'm on freeBSD, what would I need installed in order to run server side javascript? | It goes like this:
Servers are expensive, but users will give you processing time in their browsers for free. Therefore, server-side code is relatively expensive compared to client-side code on any site big enough to need to run more than one server. However, there are some things you can't leave to the client, like data validation and retrieval. You'd like to do them on the client, because it means faster response times for the users and less server infrastructure for yourself, but security and accessibility concerns mean server-side code is required.
What typically happens is you do both. You write server-side logic because you have to, but you also write the same logic in javascript in hopes of providing faster responses to the user and saving your servers a little extra work in some situations. This is especially effective for validation code; a failed validation check in a browser can save an entire http request/response pair on the server.
Since we're all (mostly) programmers here we should immediately spot the new problem. There's not only the extra work involved in developing two sets of the same logic, but also the work involved in maintaining it, the inevitable bugs resulting from platforms don't match up well, and the bugs introduced as the implementations drift apart over time.
Enter server-side javascript. The idea is you can write code once, so the same code runs on both server and client. This would appear to solve most of the issue: you get the full set of both server and client logic done all at once, there's no drifting, and no double maintenance. It's also nice when your developers only need to know one language for both server and client work.
Unfortunately, in the real world it doesn't work out so well. The problem is four-fold:
1. The server view of a page is still very different from the client view of a page. The server needs to be able to do things like talk directly to a database that just shouldn't be done from the browser. The browser needs to do things like manipulate a DOM that doesn't match up with the server.
2. You don't control the javascript engine of the client, meaning there will still be important language differences between your server code and your client code.
3. The database is normally a bigger bottleneck than the web server, so savings and performance benefit ends up less than expected.
4. While just about everyone knows a little javascript, not many developers really know and understand javascript *well*.
These aren't completely unassailable technical problems: you constrain the server-supported language to a sub-set of javascript that's well supported across most browsers, provide an IDE that knows this subset and the server-side extensions, make some rules about page structure to minimize DOM issues, and provide some boiler-plate javascript for inclusion on the client to make the platform a little nicer to use. The result is something like Aptana Studio/Jaxer, or more recently Node.js, which can be pretty nice.
But not perfect. In my opinion, there are just too many pitfalls and little compatibility issues to make this really shine. Ultimately, additional servers are still cheap compared to developer time, and most programmers are able to be much more productive using something other than javascript.
What I'd really like to see is partial server-side javascript. When a page is requested or a form submitted the server platform does *request* validation in javascript, perhaps as a plugin to the web server that's completely independent from the rest of it, but the *response* is built using the platform of your choice. | I think a really cool use of server-side Javascript that isn't used nearly often enough is for data validation. With it, you can write one javascript file to validate a form, check it on the client side, then check it again on the server side because we shouldn't trust anything on the client side. It lets you keep your validation rules DRY. Quite handy.
Also see:
* [Will server-side Javascript take off? Which implementation is most stable?](https://stackoverflow.com/questions/17435/will-server-side-javascript-take-off-which-implementation-is-most-stable)
* [When and how do you use server side JavaScript?](https://stackoverflow.com/questions/459238/when-and-how-do-you-use-server-side-javascript) | Server Side Javascript: Why? | [
"",
"javascript",
"scripting",
"server-side",
""
] |
I know this is a similar question to one already asked, but I was hoping for a different answers to a problem. I have a form where you can upload new articles to a database all fine works ace, wonderful, brill. The form uses a drop down menu for the type of article, I have news, gossip, travel, performances and others in my drop down box. When you upload to the db it's only going to add the selected item let's say, in this case, News.
I need the user to be able edit their articles, so I need to populate the drop down box with the selected item. I think it's a bit of a pain in the BUM to set up a database table with each of the drop items and an ID for them. Is there away of setting the selected item as value in the db, and then just using a if statement or something to populate the rest of the drop down box?
Hope that makes sense. I also thought use of a radio buttons could be a solution however I cant get that to set the selected button with the value in the db. | You could do something like this:
```
// array of available options
$available = array('news'=>'News', 'gosip'=>'Gosip', 'travel'=>'Travel', 'performances'=>'Performance');
// selected option value
$selected = 'news';
echo '<select name="article-type">';
foreach ($available as $val => $label) {
echo '<option value="'.htmlspecialchars($val).'"';
if ($val == $selected) {
echo ' selected="selected"';
}
echo '>'.htmlspecialchars($label).'</option>';
}
echo '</select>';
``` | Sounds like you want to put the article types in a table or something along those lines.
Then you can load the drop-down from the table, and just store a reference to the article type ID in the article table.
On the plus it should make retrieving all articles of a given type quite a bit faster as you'd be doing the lookup on ID. | How do you populate a radio button or drop down box when editing from a database? | [
"",
"php",
"database",
"drop-down-menu",
"radio-button",
"editing",
""
] |
I'm currently reading up on OO before I embark upon my next major project. To give you some quick background, I'm a PHP developer, working on web applications.
One area that particularly interests me is the User Interface; specifically how to build this and connect it to my OO "model".
I've been doing some reading on this area. One of my favourites is this:
[Building user interfaces for object-oriented systems](http://www.javaworld.com/javaworld/jw-07-1999/jw-07-toolbox.html)
> "All objects must provide their own UI"
Thinking about *my* problem, I can see this working well. I build my "user" object to represent someone who has logged into my website, for example. One of my methods is then "display\_yourself" or similar. I can use this throughout my code. Perhaps to start with this will just be their name. Later, if I need to adjust to show their name+small avatar, I can just update this one method and hey-presto, my app is updated. Or if I need to make their name a link to their profile, hey-presto I can update again easily from one place.
In terms of an OO system; I think this approach works well. Looking on other StackOverflow threads, I found this under "Separation of Concerns":
[Soc](https://stackoverflow.com/questions/98734/separation-of-concerns)
> "In computer science, separation of
> concerns (SoC) is the process of
> breaking a computer program into
> distinct features that overlap in
> functionality as little as possible. A
> concern is any piece of interest or
> focus in a program. Typically,
> concerns are synonymous with features
> or behaviors. Progress towards SoC is
> traditionally achieved through
> modularity and encapsulation, with the
> help of information hiding."
To my mind I have achieved this. My user object hides all it's information. I don't have any places in my code where I say $user->get\_user\_name() before I display it.
However, this seems to go against what other people seem to think of as "best practice".
To quote the "selected" (green one) answer from the same question:
> "The separation of concerns is keeping
> the code for each of these concerns
> separate. Changing the interface
> should not require changing the
> business logic code, and vice versa.
> Model-View-Controller (MVC) design
> pattern is an excellent example of
> separating these concerns for better
> software maintainability."
Why does this make for better software maintainability? Surely with MVC, my View has to know an awful lot about the Model? Read the JavaWorld article for a detailed discussion on this point:
[Building user interfaces for object-oriented systems](http://www.javaworld.com/javaworld/jw-07-1999/jw-07-toolbox.html)
Anyway... getting to the actual point, finally!
**1.** Can anyone recommend any books that discuss this in detail? I don't want an MVC book; I'm not sold on MVC. I want a book that discusses OO / UI, the potential issues, potential solutuions etc.. (maybe including MVC)
Arthur Riel's [Object-Oriented Design Heuristics](https://rads.stackoverflow.com/amzn/click/com/020163385X)
touches on it (and is an excellent book as well!), but I want something that goes into more detail.
**2.** Can anyone put forward an argument that is as well-explained as Allen Holub's JavaWorld article that explains why MVC is a good idea?
Many thanks for anyone who can help me reach a conclusion on this. | This is a failure in how OOP is often taught, using examples like rectangle.draw() and dinosaur.show() that make absolutely no sense.
You're almost answering your own question when you talk about having a user class that displays itself.
"Later, if I need to adjust to show their name+small avatar, I can just update this one method and hey-presto, my app is updated."
Think about just that little piece for moment. Now take a look at Stack Overflow and notice all of the places that your username appears. Does it look the same in each case? No, at the top you've just got an envelope next to your username followed by your reputation and badges. In a question thread you've got your avatar followed by your username with your reputation and badges below it. Do you think that there is a user object with methods like getUserNameWithAvatarInFrontOfItAndReputationAndBadgesUnderneath() ? Nah.
An object is concerned with the data it represents and methods that act on that data. Your user object will probably have firstName and lastName members, and the necessary getters to retrieve those pieces. It might also have a convenience method like toString() (in Java terms) that would return the user's name in a common format, like the first name followed by a space and then the last name. Aside from that, the user object shouldn't do much else. It is up to the client to decide what it wants to do with the object.
Take the example that you've given us with the user object, and then think about how you would do the following if you built a "UI" into it:
1. Create a CSV export showing all users, ordered by last name. E.g. Lastname, Firstname.
2. Provide both a heavyweight GUI and a Web-based interface to work with the user object.
3. Show an avatar next to the username in one place, but only show the username in another.
4. Provide an RSS list of users.
5. Show the username bold in one place, italicized in another, and as a hyperlink in yet another place.
6. Show the user's middle initial where appropriate.
If you think about these requirements, they all boil down to providing a user object that is only concerned with the data that it should be concerned with. It shouldn't try to be all things to everyone, it should just provide a means to get at user data. It is up to each of the *many* views you will create to decide how it wants to display the user data.
Your idea about updating code in one place to update your views in many places is a good one. This is still possible without mucking with things at a too low of a level. You could certainly create widget-like classes that would encapsulate your various common views of "stuff", and use them throughout your view code. | Here's the approach I take when creating websites in PHP using an MVC/separation of concerns pattern:
The framework I use has three basic pieces:
* Models - PHP Classes. I add methods to them to fetch and save data. Each
model represents a distinct type of entity in the system: users, pages,
blog posts
* Views - Smarty templates. This is where the html lives.
* Controllers - PHP classes. These are the brains of the application. Typically
urls in the site invoke methods of the class. example.com/user/show/1 would
invoke the $user\_controller->show(1) method. The controller fetches data out
of the model and gives it to the view.
Each of these pieces has a specific job or "concern". The **model**'s job is to provide a clean interface to the data. Typically the site's data is stored in a SQL database. I add methods to the model for fetching data out and saving data in.
The **view**'s job is to display data. All HTML markup goes in the view. Logic to handle zebra-striping for a table of data goes in the view. Code to handle the format that a date should be displayed in goes in the view. I like using Smarty templates for views because it offers some nice features to handle things like that.
The **controller**'s job is to act as an intermediary between the user, the model, and the view.
Let's look at an example of how these come together and where the benefits lie:
Imagine a simple blog site. The main piece of data is a post. Also, imagine that the site keeps track of the number of times a post is viewed. We'll create a SQL table for that:
```
posts
id date_created title body hits
```
Now suppose you would like to show the 5 most popular posts. Here's what you might see in a non MVC application:
```
$sql = "SELECT * FROM posts ORDER BY hits DESC LIMIT 5";
$result = mysql_query($sql);
while ($row = mysql_fetch_assoc($result)) {
echo "<a href="post.php?id=$row['id']">$row['title']</a><br />";
}
```
This snippet is pretty straightforward and works well if:
1. It is the only place you want to show the most popular posts
2. You never want to change how it looks
3. You never decide to change what a "popular post" is
Imagine that you want to show the 10 most popular posts on the home page and the 5 most popular in a sidebar on subpages. You now need to either duplicate the code above, or put it in an include file with logic to check where it is being displayed.
What if you want to update the markup for the home page to add a "new-post" class to posts that were created today?
Suppose you decide that a post is popular because it has a lot of comments, not hits. The database will change to reflect this. Now, every place in your application that shows popular posts must be updated to reflect the new logic.
You are starting to see a snowball of complexity form. It's easy to see how things can become increasingly difficult to maintain over the course of a project. Also, consider the complexity when multiple developers are working on a project. Should the designer have to consult with the database developer when adding a class to the output?
Taking an MVC approach and enforcing a separation of concerns within your application can mitigate these issues. Ideally we want to separate it out into three areas:
1. data logic
2. application logic
3. and display logic
Let's see how to do this:
We'll start with the **model**. We'll have a `$post_model` class and give it a method called `get_popular()`. This method will return an array of posts. Additionally we'll give it a parameter to specify the number of posts to return:
```
post_model.php
class post_model {
public function get_popular($number) {
$sql = "SELECT * FROM posts ORDER BY hits DESC LIMIT $number";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
return $array;
}
}
```
Now for the homepage we have a **controller**, we'll call it "home". Let's imagine that we have a url routing scheme that invokes our controller when the home page is requested. It's job is to get the popular posts and give them to the correct view:
```
home_controller.php
class home_controller {
$post_model = new post_model();
$popular_posts = $post_model->get_popular(10);
// This is the smarty syntax for assigning data and displaying
// a template. The important concept is that we are handing over the
// array of popular posts to a template file which will use them
// to generate an html page
$smarty->assign('posts', $popular_posts);
$smarty->view('homepage.tpl');
}
```
Now let's see what the **view** would look like:
```
homepage.tpl
{include file="header.tpl"}
// This loops through the posts we assigned in the controller
{foreach from='posts' item='post'}
<a href="post.php?id={$post.id}">{$post.title}</a>
{/foreach}
{include file="footer.tpl"}
```
Now we have the basic pieces of our application and can see the separation of concerns.
The **model** is concerned with getting the data. It knows about the database, it knows about SQL queries and LIMIT statements. It knows that it should hand back a nice array.
The **controller** knows about the user's request, that they are looking at the homepage. It knows that the homepage should show 10 popular posts. It gets the data from the model and gives it to the view.
The **view** knows that an array of posts should be displayed as a series of achor tags with break tags after them. It knows that a post has a title and an id. It knows that a post's title should be used for the anchor text and that the posts id should be used in the href. The view also knows that there should be a header and footer shown on the page.
It's also important to mention what each piece *doesn't* know.
The **model** doesn't know that the popular posts are shown on the homepage.
The **controller** and the **view** don't know that posts are stored in a SQL database.
The **controller** and the **model** don't know that every link to a post on the homepage should have a break tag after it.
So, in this state we have established a clear separation of concerns between data logic (the model), application logic (the controller), and display logic (the view). So now what? We took a short simple PHP snippet and broke it into three confusing files. What does this give us?
Let's look at how having a separation of concerns can help us with the issues mentioned above. To reiterate, we want to:
1. Show popular posts in a sidebar on subpages
2. Highlight new posts with an additional css class
3. Change the underlying definition of a "popular post"
To show the popular posts in a sidebar we'll add two files our subpage:
A subpage controller...
```
subpage_controller.php
class subpage_controller {
$post_model = new post_model();
$popular_posts = $post_model->get_popular(5);
$smarty->assign('posts', $popular_posts);
$smarty->view('subpage.tpl');
}
```
...and a subpage template:
```
subpage.tpl
{include file="header.tpl"}
<div id="sidebar">
{foreach from='posts' item='post'}
<a href="post.php?id={$post.id}">{$post.title}</a>
{/foreach}
</div>
{include file="footer.tpl"}
```
The new subpage **controller** knows that the subpage should only show 5 popular posts. The subpage **view** knows that subpages should put the list of posts inside a sidebar div.
Now, on the homepage we want to highlight new posts. We can achieve this by modifying the homepage.tpl.
```
{include file="header.tpl"}
{foreach from='posts' item='post'}
{if $post.date_created == $smarty.now}
<a class="new-post" href="post.php?id={$post.id}">{$post.title}</a>
{else}
<a href="post.php?id={$post.id}">{$post.title}</a>
{/if}
{/foreach}
{include file="footer.tpl"}
```
Here the **view** handles all of the new logic for displaying popular posts. The **controller** and the **model** didn't need to know anything about that change. It's purely display logic. The subpage list continues to show up as it did before.
Finally, we'd like to change what a popular post is. Instead of being based on the number of hits a page got, we'd like it to be based on the number of comments a post got. We can apply that change to the model:
```
post_model.php
class post_model {
public function get_popular($number) {
$sql = "SELECT * , COUNT(comments.id) as comment_count
FROM posts
INNER JOIN comments ON comments.post_id = posts.id
ORDER BY comment_count DESC
LIMIT $number";
$result = mysql_query($sql);
while($row = mysql_fetch_assoc($result)) {
$array[] = $row;
}
return $array;
}
}
```
We have increased the complexity of the "popular post" logic. However, once we've made this change in the **model**, in one place, the new logic is applied everywhere. The homepage and the subpage, with no other modifications, will now display popular posts based on comments. Our designer didn't need to be involved in this. The markup is not affected.
Hopefully, this provides a compelling example of how separating the concerns of data logic, application logic, and display logic, can make developing your application easier. Changes in one area tend to have less of an impact on other areas.
Following this convention isn't a magic bullet that will automatically make your code perfect. And you will undoubtedly come across issues where it is far less clear where the separation should be. In the end, it's all about managing complexity within the application.
You should give plenty of thought to how you construct your models. What sort of interfaces will they provide (see Gregory's answer regarding contracts)? What data format does the controller and view expect to work with? Thinking about these things ahead of time will make things easier down the road.
Also, there can be some overhead when starting a project to get all of these pieces working together nicely. There are many frameworks that provide the building blocks for models, controllers, templating engines, url routing, and more. See many other posts on SO for suggestions on PHP MVC frameworks. These frameworks will get you up and running but you as the developer are in charge of managing complexity and enforcing a separation of concerns.
I will also note that the code snippets above are just simplified examples. They may (most likely) have bugs. However, they are very similar in structure to the code I use in my own projects. | Separation of concerns; MVC; why? | [
"",
"php",
"model-view-controller",
"user-interface",
"oop",
""
] |
I am running multiple PHP apps on my Mac, running OS X 10.5.6, Apache 2, PHP 5. I have subdomains setup for each project, a host file entries for each subdomain, and Virtual Directory blocks in the Apache config. So
project1.localhost goes to /Library/WebServer/Documents/Project1
project2.localhost goes to /Library/WebServer/Documents/Project2
etc...
However, this method doesn't really "isolate" the web apps. For example, if I include a script like so:
```
<?php
include("/includes/include.php");
?>
```
It references the script from the base directory of my computer. So it accesses
C:/includes/include.php
Is there a way for me to make it reference
C:/Library/WebServer/Documents/Project2/includes/include.php
Basically, make it so that its not aware of anything outside of its own directory. Also, is there a way to use php.ini's on a per subdomain basis as well? | I believe it's possible to set a php.ini per virtual host
```
<VirtualHost *:80>
...
PHPINIDir /full/path/to/php/ini/
</VirtualHost>
```
this way you can customize open\_basedir and others | You can limit a scripts ability to see anything above a specific folder tree by adding the [open\_basedir](http://www.php.net/manual/en/ini.sect.safe-mode.php#ini.open-basedir) directive a folder block in the httpd.conf file. It should look like:
> <DIRECTORY /full/path/to/folder/containing/script/>
>
> php\_admin\_value open\_basedir "/full/path/to/top/folder/of/desired/tree/"
>
> </DIRECTORY>
One thing - if you don't end the path with a / then it's a wildcard match. In other words, "/var/etc/my" will match "/var/etc/myFolder" as well as "/var/etc/myMothersFolder", while "/var/etc/my/" will only match that exact folder name. | How do I limit PHP apps to their own directories and their own php.ini? | [
"",
"php",
"apache",
"include",
"subdomain",
"server-side-includes",
""
] |
I have a script that uses mcrypt\_decrypt() function, but I get the following error
> Fatal error: Call to undefined function mcrypt\_decrypt()
What modules/libraries do I need to include to use this function? Or is there another reason I'm getting the error?
Thanks | Please see:
* [Mcrypt Requirements](http://de.php.net/manual/en/mcrypt.requirements.php)
* [Mcrypt Installation](http://de.php.net/manual/en/mcrypt.installation.php)
You need to compile your PHP with `--with-mcrypt[=DIR]` and have libmcrypt Version 2.5.6 or greater on your machine. | sudo apt-get install php5-mcrypt
works on ubuntu. | What's needed for PHP's mcrypt_decrypt()? | [
"",
"php",
"mcrypt",
""
] |
I'm trying to run some java script just before a page redirect but it fails to run.
When I comment out the Response.Redirect all works fine but this goes against the particular requirements. Any ideas on how to implement this functionality?
```
Dim strscript As String = "<script>alert('hello');</script>"
If Not ClientScript.IsClientScriptBlockRegistered("clientscript") Then
ClientScript.RegisterStartupScript(Me.GetType(), "clientscript", strscript)
End If
Response.Redirect("http://www.google.com")
``` | Your problem is that the Response.Redirect redirects the response (...) before anything is sent back to the client. So what the client gets is a response from Google rather than from your server.
In order to write some javascript on the page and have it execute before sending the client to Google, you'll need to do your redirect in javascript after the alert.
```
Dim strscript As String = "<script>alert('hello');window.location.href='http://www.google.com'</script>"
If Not ClientScript.IsClientScriptBlockRegistered("clientscript") Then
ClientScript.RegisterStartupScript(Me.GetType(), "clientscript", strscript)
End If
``` | The client isn't getting a chance to load. Try redirecting from the client side:
```
Dim strscript As String = "<script>alert('hello');window.location.href("http://www.google.com");</script>"
If Not ClientScript.IsClientScriptBlockRegistered("clientscript") Then
ClientScript.RegisterStartupScript(Me.GetType(), "clientscript", strscript)
End If
``` | How do I call javascript just before a response redirect | [
"",
"asp.net",
"javascript",
"vb.net",
"asp.net-2.0",
""
] |
I got a native library that needs to be added to *java.library.path*. With JVM argument *-Djava.library.path=path...* I can set the path as I want.
My problem is that my other library (pentaho reporting) searches fonts based on the default java.library.path (including system directories etc) and the manual setting overrides the default path..
So : how can I **add** a path entry to the default java.library.path instead of overriding it (which seems to be done with -Djava.library.path)? (I wouldn't want to add the default path by hand, which wouldn't be nice for the sake of deployment)
EDIT: Sorry for missing details; I'm working with Eclipse. (The deployment is done with JNLP and there I can use *nativelib* under *resources*) | Had forgotten this issue... I was actually asking with Eclipse, sorry for not stating that originally.
And the answer seems to be too simple (at least with 3.5; probably with older versions also):
Java run configuration's Arguments : VM arguments:
```
-Djava.library.path="${workspace_loc:project}\lib;${env_var:PATH}"
```
Must not forget the quotation marks, otherwise there are problems with spaces in PATH. | If you want to add a native library without interfering with `java.library.path` at development time in Eclipse (to avoid including absolute paths and having to add parameters to your launch configuration), you can supply the path to the native libraries location for each Jar in the *Java Build Path* dialog under *Native library location*. Note that the native library file name has to correspond to the Jar file name. See also this [detailed description](http://www.eclipsezone.com/eclipse/forums/t49342.html). | How to add native library to "java.library.path" with Eclipse launch (instead of overriding it) | [
"",
"java",
"eclipse",
"path",
"java.library.path",
""
] |
I've been using the crap out of the [Nested Set Model](http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/) lately. I have enjoyed designing queries for just about every useful operation and view. One thing I'm stuck on is how to select the immediate children (and *only* the children, not further descendants!) of a node.
To be honest, I do know of a way - but it involves unmanageable amounts of SQL. I'm sure there is a more straightforward solution. | Did you read the article you posted? It's under the heading "Find the Immediate Subordinates of a Node"
```
SELECT node.name, (COUNT(parent.name) - (sub_tree.depth + 1)) AS depth
FROM nested_category AS node,
nested_category AS parent,
nested_category AS sub_parent,
(
SELECT node.name, (COUNT(parent.name) - 1) AS depth
FROM nested_category AS node,
nested_category AS parent
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.name = 'PORTABLE ELECTRONICS'
GROUP BY node.name
ORDER BY node.lft
)AS sub_tree
WHERE node.lft BETWEEN parent.lft AND parent.rgt
AND node.lft BETWEEN sub_parent.lft AND sub_parent.rgt
AND sub_parent.name = sub_tree.name
GROUP BY node.name
HAVING depth <= 1
ORDER BY node.lft;
```
However, what I do (this is cheating) is I combined the nested set with adjacency lists -- I embed a "parent\_id" in the table, so I can easily ask for the children of a node. | It seems to me this should be easily doable without the subqueries or parent column redundancy! For example, given parent's left and right are already known:
```
SELECT child.id
FROM nodes AS child
LEFT JOIN nodes AS ancestor ON
ancestor.left BETWEEN @parentleft+1 AND @parentright-1 AND
child.left BETWEEN ancestor.left+1 AND ancestor.right-1
WHERE
child.left BETWEEN @parentleft+1 AND @parentright-1 AND
ancestor.id IS NULL
```
That is, “from all descendents of the node in question, pick ones with no ancestor between themselves and the node”. | Is there a simple way to query the children of a node? | [
"",
"sql",
"tree",
"nested-set-model",
""
] |
I am working with a dataset, and will be returning both positive and negative currency figures. I already have a parenthesis around it. How do I get only the negative numbers in the gridview to show up in red? Can I do this on the HTML side? | I would set the CssClass of the control to something that styles the text the way you want if the number is negative. The reason for using CssClass instead of FontColor is that you may change this in the future and it will be easier to just change the CSS style rather than any code that uses it.
```
<asp:BoundField runat="server"
DataField="Value"
HeaderText="value"
ItemStyleCssClass='<% (double)Eval("Value") < 0 ? "negative-number" : "" %>' />
``` | Without going to a third party control that has formatting rules, I would use the Row's data binding event and color the text of the cell in question when it is negative. This adds a slight bit of weight to the UI layer, but not enough it will be noticeable until you are delivering thousands and thousands of rows. If you are delivering thousands and thousands of rows, you probably have an architecture problem. | How do I Turn negative numbers red? | [
"",
"c#",
".net",
"asp.net",
"html",
""
] |
Is it possible to use create\_object view to create a new object and automatically assign request.user as foreign key?
P.E:
```
class Post(models.Model):
text = models.TextField()
author = models.ForeignKey(User)
```
What I want is to use create\_object and fill author with request.user. | In many ways, all the solutions to this will be more trouble than they are worth. This one qualifies as a hack. It is possible for a django update to leave you high and dry if they change the way create\_update is implemented. For simplicity sake, I'll assume that you are trying to set a default user, not silently force the user to be the logged in user.
Write a context processor:
```
from django.views.generic.create_update import get_model_and_form_class
def form_user_default(request):
if request.method == 'GET':
model, custom_form = get_model_and_form_class(Post,None)
custom_form.author = request.user
return {'form':custom_form}
else: return {}
```
What this will do is override the form object that create\_update passes to the template. What it's technically doing is re-creating the form after the default view has done it.
Then in your url conf:
```
url(r'pattern_to_match', 'django.views.generic.create_update.create_object', kwargs={'context_processors':form_user_default})
```
Again, I had to delve into the source code to figure out how to do this. It might really be best to try writing your own view (but incorporate as many Django custom objects as possible). There's no "simple default" way to do this, because in the django paradigm forms are more closely tied to the model layer than to views, and only views have knowledge of the request object. | You may want to consider a closure.
```
from django.forms import ModelForm
from django.views.generic.create_update import create_object, update_object
def make_foo_form(request):
class FooForm(ModelForm):
class Meta:
model = Foo
fields = ['foo', 'bar']
def save(self, commit=True):
f = super(FooForm, self).save(commit=False)
if not f.pk: f.user = request.user
if commit: f.save()
return f
return FooForm
def create_foo(request):
FooForm = make_foo_form(request)
return create_object(form_class=FooForm)
```
There is some inefficiency here, since you need to create the ModelForm object on each request, but it does allow you to inject functionality into the generic view.
You need to decide whether the added complexity for the form creation is worth maintaining simplicity on the view side.
A benefit here, though, is that this also works with the update case with practically no extra effort:
```
def update_foo(request, object_id):
FooForm = make_foo_form(request)
return update_object(form_class=FooForm, object_id=object_id)
```
Obviously, you can use this approach for more complex cases as well. | Setting object owner with generic create_object view in django | [
"",
"python",
"django",
""
] |
This is a program I wrote to calculate Pythagorean triplets. When I run the program it prints each set of triplets twice because of the if statement. Is there any way I can tell the program to only print a new set of triplets once? Thanks.
```
import math
def main():
for x in range (1, 1000):
for y in range (1, 1000):
for z in range(1, 1000):
if x*x == y*y + z*z:
print y, z, x
print '-'*50
if __name__ == '__main__':
main()
``` | Pythagorean Triples make a good example for claiming "**`for` loops considered harmful**", because `for` loops seduce us into thinking about counting, often the most irrelevant part of a task.
(I'm going to stick with pseudo-code to avoid language biases, and to keep the pseudo-code streamlined, I'll not optimize away multiple calculations of e.g. `x * x` and `y * y`.)
**Version 1**:
```
for x in 1..N {
for y in 1..N {
for z in 1..N {
if x * x + y * y == z * z then {
// use x, y, z
}
}
}
}
```
is the worst solution. It generates duplicates, and traverses parts of the space that aren't useful (e.g. whenever `z < y`). Its time complexity is cubic on `N`.
**Version 2**, the first improvement, comes from requiring `x < y < z` to hold, as in:
```
for x in 1..N {
for y in x+1..N {
for z in y+1..N {
if x * x + y * y == z * z then {
// use x, y, z
}
}
}
}
```
which reduces run time and eliminates duplicated solutions. However, it is still cubic on `N`; the improvement is just a reduction of the co-efficient of `N`-cubed.
It is pointless to continue examining increasing values of `z` after `z * z < x * x + y * y` no longer holds. That fact motivates **Version 3**, the first step away from brute-force iteration over `z`:
```
for x in 1..N {
for y in x+1..N {
z = y + 1
while z * z < x * x + y * y {
z = z + 1
}
if z * z == x * x + y * y and z <= N then {
// use x, y, z
}
}
}
```
For `N` of 1000, this is about 5 times faster than Version 2, but it is *still* cubic on `N`.
The next insight is that `x` and `y` are the only independent variables; `z` depends on their values, and the last `z` value considered for the previous value of `y` is a good *starting* search value for the next value of `y`. That leads to **Version 4**:
```
for x in 1..N {
y = x+1
z = y+1
while z <= N {
while z * z < x * x + y * y {
z = z + 1
}
if z * z == x * x + y * y and z <= N then {
// use x, y, z
}
y = y + 1
}
}
```
which allows `y` and `z` to "sweep" the values above `x` only once. Not only is it over 100 times faster for `N` of 1000, it is quadratic on `N`, so the speedup increases as `N` grows.
I've encountered this kind of improvement often enough to be mistrustful of "counting loops" for any but the most trivial uses (e.g. traversing an array).
**Update:** Apparently I should have pointed out a few things about V4 that are easy to overlook.
1. **Both** of the `while` loops are controlled by the value of `z` (one directly, the other indirectly through the square of `z`). The inner `while` is actually speeding up the outer `while`, rather than being orthogonal to it. *It's important to look at what the loops are doing, not merely to count how many loops there are.*
2. All of the calculations in V4 are strictly integer arithmetic. Conversion to/from floating-point, as well as floating-point calculations, are costly by comparison.
3. V4 runs in constant memory, requiring only three integer variables. There are no arrays or hash tables to allocate and initialize (and, potentially, to cause an out-of-memory error).
4. The original question allowed all of `x`, `y`, and `x` to vary over the same range. V1..V4 followed that pattern.
Below is a not-very-scientific set of timings (using Java under Eclipse on my older laptop with other stuff running...), where the "use x, y, z" was implemented by instantiating a Triple object with the three values and putting it in an ArrayList. (For these runs, `N` was set to 10,000, which produced 12,471 triples in each case.)
```
Version 4: 46 sec.
using square root: 134 sec.
array and map: 400 sec.
```
The "array and map" algorithm is *essentially*:
```
squares = array of i*i for i in 1 .. N
roots = map of i*i -> i for i in 1 .. N
for x in 1 .. N
for y in x+1 .. N
z = roots[squares[x] + squares[y]]
if z exists use x, y, z
```
The "using square root" algorithm is *essentially*:
```
for x in 1 .. N
for y in x+1 .. N
z = (int) sqrt(x * x + y * y)
if z * z == x * x + y * y then use x, y, z
```
The actual code for V4 is:
```
public Collection<Triple> byBetterWhileLoop() {
Collection<Triple> result = new ArrayList<Triple>(limit);
for (int x = 1; x < limit; ++x) {
int xx = x * x;
int y = x + 1;
int z = y + 1;
while (z <= limit) {
int zz = xx + y * y;
while (z * z < zz) {++z;}
if (z * z == zz && z <= limit) {
result.add(new Triple(x, y, z));
}
++y;
}
}
return result;
}
```
Note that `x * x` *is* calculated in the outer loop (although I didn't bother to cache `z * z`); similar optimizations are done in the other variations.
I'll be glad to provide the Java source code on request for the other variations I timed, in case I've mis-implemented anything. | Substantially faster than any of the solutions so far. Finds triplets via a ternary tree.
[Wolfram](http://mathworld.wolfram.com/PythagoreanTriple.html) says:
> Hall (1970) and Roberts (1977) prove that `(a, b, c)` is a primitive Pythagorean triple if and only if
>
> ```
> (a,b,c)=(3,4,5)M
> ```
>
> where `M` is a finite product of the matrices `U`, `A`, `D`.
And there we have a formula to generate every primitive triple.
In the above formula, the hypotenuse is ever growing so it's pretty easy to check for a max length.
In Python:
```
import numpy as np
def gen_prim_pyth_trips(limit=None):
u = np.mat(' 1 2 2; -2 -1 -2; 2 2 3')
a = np.mat(' 1 2 2; 2 1 2; 2 2 3')
d = np.mat('-1 -2 -2; 2 1 2; 2 2 3')
uad = np.array([u, a, d])
m = np.array([3, 4, 5])
while m.size:
m = m.reshape(-1, 3)
if limit:
m = m[m[:, 2] <= limit]
yield from m
m = np.dot(m, uad)
```
If you'd like all triples and not just the primitives:
```
def gen_all_pyth_trips(limit):
for prim in gen_prim_pyth_trips(limit):
i = prim
for _ in range(limit//prim[2]):
yield i
i = i + prim
```
`list(gen_prim_pyth_trips(10**4))` took 2.81 milliseconds to come back with 1593 elements while `list(gen_all_pyth_trips(10**4))` took 19.8 milliseconds to come back with 12471 elements.
For reference, the [accepted answer](https://stackoverflow.com/a/576405/992385) [(in Python)](https://gist.github.com/kgullion/6adc2d633038ff852923) took 38 seconds for 12471 elements.
Just for fun, setting the upper limit to one million `list(gen_all_pyth_trips(10**6))` returns in 2.66 seconds with 1980642 elements (almost 2 million triples in 3 seconds). `list(gen_all_pyth_trips(10**7))` brings my computer to its knees as the list gets so large it consumes every last bit of RAM. Doing something like `sum(1 for _ in gen_all_pyth_trips(10**7))` gets around that limitation and returns in 30 seconds with 23471475 elements.
For more information on the algorithm used, check out the articles on [Wolfram](http://mathworld.wolfram.com/PythagoreanTriple.html) and [Wikipedia](http://en.wikipedia.org/wiki/Tree_of_primitive_Pythagorean_triples). | Generating unique, ordered Pythagorean triplets | [
"",
"python",
"math",
""
] |
Any ideas on this one? I'm trying to write a unit test that will delete an item and confirm that item is no longer in a repository by trying to retrieve the item by its ID which should throw a DataAccessException. However, the test keeps failing. I added a try catch block and sure enough I caught the exception I was expecting. I'm using VS Test Tools for unit testing.
```
[ExpectedException(typeof(DataAccessException))]
private static void NHibernateRepositoryBaseDeleteHelper<T, TKey>(T myItem, TKey myItemId)
{
MyTestRepository<T, TKey> myRepository = new MyTestRepository<T, TKey>();
myRepository.Delete(myItem);
myRepository.CommitChanges();
try
{
myRepository.GetById(myItemId, false);
}
catch (DataAccessException dae)
{
Assert.IsTrue(true);
}
}
``` | You need to add the ExpectedException attribute onto the same method which has the TestMethod attribute. The VS Unit Test Framework will only look for an ExpectedException attribute at the entry point of a particular test.
```
[TestMethod]
[ExpectedException(typeof(DataAccessException))]
public void ATestMethod() {
...
NHibernateRepositoryBaseDeleteHelper(itemValue, keyValue);
}
``` | I'll add to what Jared said by pointing out that the "ExpectedException" attribute sucks. There's no way to assert that the exception's message is correct (the "message" parameter doesn't do what you might think it does) and you can't check for multiple exceptions in one test.
A better solution is to do something like this:
[Link](https://web.archive.org/web/20210123150121/http://geekswithblogs.net/sdorman/archive/2009/01/17/unit-testing-and-expected-exceptions.aspx)
That class lets you do neat stuff like this:
```
[TestMethod]
public void TestAFewObviousExceptions()
{
// some setup here
ExceptionAssert.Throws("Category 47 does not exist", () =>
wallet.Categories.GetChildCategoryIds(47));
ExceptionAssert.Throws("Id Flim is not valid", () =>
wallet.Categories.IdFromName("Flim"));
}
``` | ExpectedException not catching exception, but I can catch it with try catch | [
"",
"c#",
"visual-studio",
"unit-testing",
"exception",
""
] |
I was under the assumption that if I disabled a div, all content got disabled too.
However, the content is grayed but I can still interact with it.
Is there a way to do that? (disable a div and get all content disabled also) | Many of the above answers only work on form elements. A simple way to disable any DIV including its contents is to just disable mouse interaction. For example:
```
$("#mydiv").addClass("disabledbutton");
```
CSS
```
.disabledbutton {
pointer-events: none;
opacity: 0.4;
}
```
***Supplement:***
Many commented like these: "This will only disallow mouse events, but the control is still enabled" and "you can still navigate by keyboard". You Could add this code to your script and inputs can't be reached in other ways like keyboard tab. You could change this code to fit your needs.
```
$([Parent Container]).find('input').each(function () {
$(this).attr('disabled', 'disabled');
});
``` | Use a framework like JQuery to do things like:
```
function toggleStatus() {
if ($('#toggleElement').is(':checked')) {
$('#idOfTheDIV :input').attr('disabled', true);
} else {
$('#idOfTheDIV :input').removeAttr('disabled');
}
}
```
[Disable And Enable Input Elements In A Div Block Using jQuery](http://techchorus.net/disable-and-enable-input-elements-div-block-using-jquery) should help you!
As of jQuery 1.6, you should use `.prop` instead of `.attr` for disabling. | How to disable all div content | [
"",
"javascript",
"jquery",
"html",
""
] |
I'm hoping that someone will be able to recommend a good hosting company that provides the following environment. I know that I could just google for one, but I'm asking here first because I'm looking for someone that has previous experience working with such a company.
1. Linux Box.
2. Apache 2.0.
3. PHP5 (5.2.6 to be exact).
4. PostGreSQL (8.3.1).
5. Great tech support who know what they are doing.
A little background information for why I'm searching for a new host. I'm doing some freelance PHP work for a client that currently has his site hosted by, first name starts with H and last name starts with V (for anonymity). I'm sure they are a great company, but last night I was able to get my first glimpse at their web portal and frankly, it looked like it was developed in 90s and it terrified me.
I'm looking for a modern hosting company (my personal site is hosted by godaddy, and all the negative that they may get, their hosting control center is great IMO).
I have already spoken with my client, and they are open to switching hosting companies, so there is no problem there. I'm doing all my work on a local machine I have setup, so I want to be able to work with the tech support to get an identical server setup. Simple things like getting the correct php extensions enabled and ini file changes. There is also a part of the site that has its access controlled by http authentication, so I would also need to work with the techs to get that correctly set up. Access to folders outside of the web root is also definitely a plus (for example, godaddy does not allow this via ftp to my knowledge).
The programmer that was previously working on this site talked a bit with the techs at the current hosting company, and got the impression that they could not even correctly set up the pg\_hba.conf file.
I'm also looking for a company that either already provides pgPhpAdmin installed, or can properly edit the pg\_hba.conf file so that I may install it myself. The differences between the database for the old site and the new site that I will have finished are pretty substantial, so having such a tool would be a huge help to me when it comes to getting the site online and confirming that the database is setup correctly.
Anyways, sorry for the long winded post, and thank you for any replies! | [Servergrove](http://www.servergrove.com/)
Go for a VPS hosting. I have only positive experiences so far, you can do almost everything yourself over SSH. They are extremely helpful and uncomplicated. Plus they have an eco-conscious approach which I like very much. | try [webfaction](http://www.webfaction.com). They offer you a preinstalled environment (apache, php, postgres) and you can (if you want) configure everything yourself. Postgres Version is 8.3.1, the other version you can check yourself. Webfaction has a very good support, so I would recommend having a look.
The concept is a little different from a vps: If you take their software your get regular updates. Only if you install your own Software (like PHP)(which is possible because of a complete preinstalled build-essential) you have to maintain it yourself. | Another Hosting Question: Linux, Apache2, PHP5, PostGreSQL 8.3 | [
"",
"php",
"linux",
"postgresql",
"apache2",
"hosting",
""
] |
Are there any data binding frameworks (BCL or otherwise) that allow binding between *any two CLR properties* that implement `INotifyPropertyChanged` and `INotifyCollectionChanged`? It seems to be it should be possible to do something like this:
```
var binding = new Binding();
binding.Source = someSourceObject;
binding.SourcePath = "Customer.Name";
binding.Target = someTargetObject;
binding.TargetPath = "Client.Name";
BindingManager.Bind(binding);
```
Where `someSourceObject` and `someTargetObject` are just POCOs that implement `INotifyPropertyChanged`. However, I am unaware of any BCL support for this, and am not sure if there are existing frameworks that permit this.
**UPDATE**: Given that there is no existing library available, I have taken it upon myself to write my own. It is available [here](http://truss.codeplex.com/).
Thanks | I wrote [Truss](https://web.archive.org/web/20180108193909/http://truss.codeplex.com/) to fill the void. | I'm not aware of any *library* that does this - but you could write your own fairly easily.
Here's a basis I knocked up in a few minutes that establishes two way data binding between two simple properties:
```
public static class Binder
{
public static void Bind(
INotifyPropertyChanged source,
string sourcePropertyName,
INotifyPropertyChanged target,
string targetPropertyName)
{
var sourceProperty
= source.GetType().GetProperty(sourcePropertyName);
var targetProperty
= target.GetType().GetProperty(targetPropertyName);
source.PropertyChanged +=
(s, a) =>
{
var sourceValue = sourceProperty.GetValue(source, null);
var targetValue = targetProperty.GetValue(target, null);
if (!Object.Equals(sourceValue, targetValue))
{
targetProperty.SetValue(target, sourceValue, null);
}
};
target.PropertyChanged +=
(s, a) =>
{
var sourceValue = sourceProperty.GetValue(source, null);
var targetValue = targetProperty.GetValue(target, null);
if (!Object.Equals(sourceValue, targetValue))
{
sourceProperty.SetValue(source, targetValue, null);
}
};
}
}
```
Of course, this code lacks a few niceties. Things to add include
* Checking that `source` and `target` are assigned
* Checking that the properties identified by `sourcePropertyName` and `targetPropertyName` exist
* Checking for type compatibility between the two properties
Also, Reflection is relatively slow (though benchmark it before discarding it, it's not *that* slow), so you might want to use compiled expressions instead.
Lastly, given that specifying properties by string is error prone, you could use Linq expressions and extension methods instead. Then instead of writing
```
Binder.Bind( source, "Name", target, "Name")
```
you could write
```
source.Bind( Name => target.Name);
``` | Data Binding POCO Properties | [
"",
"c#",
".net",
"data-binding",
"poco",
"system.componentmodel",
""
] |
In GMail, the user can click on one checkbox in the email list, hold down the Shift key, and select a second checkbox. The JavaScript will then select/unselect the checkboxes that are between the two checboxes.
I am curious as to how this is done? Is this JQuery or some basic (or complex) JavaScript? | I wrote a self-contained demo that uses jquery:
```
$(document).ready(function() {
var $chkboxes = $('.chkbox');
var lastChecked = null;
$chkboxes.click(function(e) {
if (!lastChecked) {
lastChecked = this;
return;
}
if (e.shiftKey) {
var start = $chkboxes.index(this);
var end = $chkboxes.index(lastChecked);
$chkboxes.slice(Math.min(start,end), Math.max(start,end)+ 1).prop('checked', lastChecked.checked);
}
lastChecked = this;
});
});
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
</head>
<body>
<input type="checkbox" id="id_chk1" class="chkbox" value="1" />Check 1<br/>
<input type="checkbox" id="id_chk2" class="chkbox" value="2" />Check 2<br/>
<input type="checkbox" id="id_chk3" class="chkbox" value="3" />Check 3<br/>
<input type="checkbox" id="id_chk4" class="chkbox" value="4" />Check 4<br/>
<input type="checkbox" id="id_chk5" class="chkbox" value="5" />Check 5<br/>
<input type="checkbox" id="id_chk6" class="chkbox" value="6" />Check 6<br/>
<input type="checkbox" id="id_chk7" class="chkbox" value="7" />Check 7<br/>
</body>
</html>
``` | This is done through fairly simple javascript.
They keep track of the id of the last checked box and when when another checkbox is checked they use the [shiftKey event attribute](https://developer.mozilla.org/en-US/docs/DOM/event.shiftKey) to see if shift was held while clicking the checkbox. If so they set the [checked property](https://developer.mozilla.org/en-US/docs/DOM/HTMLInputElement) of each checkbox in between the two to true.
To determine when a box is checked they probably use an [onclick](https://developer.mozilla.org/en-US/docs/DOM/element.onclick) event on the checkboxes | How can I shift-select multiple checkboxes like GMail? | [
"",
"javascript",
"gmail",
""
] |
I'm trying to get my WinForm based C# to cooperate with the commandline too, but I'm having difficulty getting it to play nice. For example, I have this code:
```
[STAThread]
static void Main(string[] args) {
foreach (string s in args) {
System.Windows.Forms.MessageBox.Show(s);
Console.WriteLine("String: " + s);
}
Mutex appSingleton = new System.Threading.Mutex(false, "WinSyncSingalInstanceMutx");
if (appSingleton.WaitOne(0, false)) {
try {
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//start logger
Logger.singleton.makeOpen(true);
Application.Run(new MainForm(false));
} catch (Exception) {
} finally {
appSingleton.Close();
Logger.singleton.makeOpen(false);
}
} else {
System.Windows.Forms.MessageBox.Show("Sorry, only one instance of WinSync can be ran at once.");
}
}
}
```
It should write to the console with the Console.WriteLine, but I see nothing, only the MessageBox shows up.
What am I doing wrong? | Try AttachConsole(-1) to redirect Console.Out, worked for me:
```
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace PEFixer
{
static class Program
{
[DllImport("kernel32.dll")]
private static extern bool AttachConsole(int dwProcessId);
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static int Main(string[] args)
{
if (args.Length > 0)
{
AttachConsole(-1);
return Form1.doTransformCmdLine(args);
}
else
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
return 0;
}
}
}
``` | Windows application model makes it a bit painful. You need to change your application type to Console (in properties), and it should magically start working. Your form will appear anyway, because it is create explicitly by the autogenerated code. | Writing to the command line in a windowed app | [
"",
"c#",
".net",
"user-interface",
"console",
""
] |
how do you create a new database user with password in sql server 2005?
i will need this user/password to use in the connection string eg:
```
uid=*user*;pwd=*password*;
``` | ```
CREATE LOGIN [user] WITH PASSWORD='password',
DEFAULT_DATABASE=[your_db], CHECK_POLICY=OFF
GO
CREATE USER [user] FOR LOGIN [user]
EXEC sp_addrolemember N'db_datareader', N'your_db'
EXEC sp_addrolemember N'db_datawriter', N'your_db'
GO
```
Where `CHECK_POLICY=OFF` switches off password complexity check, etc | As of SQL Server 2005, you should basically create users in two steps:
* create a "login" to your SQL Server as a whole
* create users for this login in each database needed
You'd go about doing this like so:
```
CREATE LOGIN MyNewUser WITH PASSWORD = 'top$secret';
```
And the "USE" your database and create a user for that login:
```
USE AdventureWorks;
CREATE USER MyNewUser FOR LOGIN MyNewUser
``` | Create a new db user in SQL Server 2005 | [
"",
"sql-server",
"sql-server-2005",
"t-sql",
"sql",
""
] |
Preferably also on linux - if necessary I'll install a basic version of Windows XP | If you are going to install the XP on your linux machine then the Microsoft Visual C# Express Edition 2005 and 2008 are extremely good programs. Infact I think all the express editions are amazing that they are free. | No problem - [MonoDevelop](http://monodevelop.com/Main_Page) will run were you want it -
> MonoDevelop is a free GNOME IDE primarily designed for C# and other .NET languages. | What is the best way to program C# on a free platform? (Compiler / IDE / Debugger / etc) | [
"",
"c#",
""
] |
What, in Your opinion is a meaningful docstring? What do You expect to be described there?
For example, consider this Python class's `__init__`:
```
def __init__(self, name, value, displayName=None, matchingRule="strict"):
"""
name - field name
value - field value
displayName - nice display name, if empty will be set to field name
matchingRule - I have no idea what this does, set to strict by default
"""
```
Do you find this meaningful? Post Your good/bad examples for all to know (and a general answer so it can be accepted). | I agree with "Anything that you can't tell from the method's signature". It might also mean to explain what a method/function returns.
You might also want to use [Sphinx](http://www.sphinx-doc.org/) (and reStructuredText syntax) for documentation purposes inside your docstrings. That way you can include this in your documentation easily. For an example check out e.g. [repoze.bfg](http://svn.repoze.org/repoze.bfg/trunk) which uses this extensively ([example file](http://svn.repoze.org/repoze.bfg/trunk/repoze/bfg/location.py), [documentation example](http://svn.repoze.org/repoze.bfg/trunk/docs/)).
Another thing one can put in docstrings is also [doctests](http://docs.python.org/library/doctest.html). This might make sense esp. for module or class docstrings as you can also show that way how to use it and have this testable at the same time. | From [PEP 8](http://www.python.org/dev/peps/pep-0008/):
> Conventions for writing good documentation strings (a.k.a.
> "docstrings") are immortalized in [PEP 257](http://www.python.org/dev/peps/pep-0257/).
>
> * Write docstrings for all public modules, functions, classes, and methods. Docstrings are not necessary for non-public methods, but you
> should have a comment that describes what the method does. This
> comment should appear after the "def" line.
> * [PEP 257](http://www.python.org/dev/peps/pep-0257/) describes good docstring conventions. Note that most importantly, the """ that ends a multiline docstring should be on a
> line by itself, and preferably preceded by a blank line.
> * For one liner docstrings, it's okay to keep the closing """ on the same line. | How to write meaningful docstrings? | [
"",
"python",
"comments",
"docstring",
""
] |
I am searching for a way to encrypt a .txt file into a zip, but in a secure password protected way. My goal is to email this file to me, without anyone being able to read the content of the attachment.
Does anybody know an easy, and above all, secure way to accomplish this ? I can create zip archives, but I do not know how to encrypt them, or, how secure this is. | > Note: this answer recommends a cryptographic method that is known
> insecure, even with good password. Please [see link from comments](http://math.ucr.edu/%7Emike/zipattacks.pdf)
> and [the Winzip QA on AES](http://kb.winzip.com/kb/entry/80/). Support for in-php AES zip encryption
> arrives with [php 7.2](http://php.net/manual/en/ziparchive.setencryptionname.php) (and [libzip 1.2.0](https://libzip.org/news/release-1.2.0.html)), which means this
> answer will soon be outdated too. Until then [see this answer for how
> to call out to 7z instead of the zip command, which supports winzip's
> AES encryption](https://stackoverflow.com/a/13483798/144364).
You can use this:
```
<?php echo system('zip -P pass file.zip file.txt'); ?>
```
Where pass is the password, and file.txt will be zipped into file.zip. This should work on Windows and Linux, you just need to get a free version of zip for Windows ( <http://www.info-zip.org/Zip.html#Win32> )
This kind of security can be broken by brute force attacks, dictionary attacks and etc. But it's not that easy, specially if you chose a long and hard to guess password. | As of php 7.2 (which was released a hours ago), the right way to do this is to use additional functionality included in [ZipArchive](http://php.net/manual/en/class.ziparchive.php) native php code. (thanks to [abraham-tugalov](https://stackoverflow.com/users/3684575/abraham-tugalov) for pointing out that this change was coming)
Now the simple answer looks something like this:
```
<?php
$zip = new ZipArchive();
if ($zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
$zip->setPassword('secret_used_as_default_for_all_files'); //set default password
$zip->addFile('thing1.txt'); //add file
$zip->setEncryptionName('thing1.txt', ZipArchive::EM_AES_256); //encrypt it
$zip->addFile('thing2.txt'); //add file
$zip->setEncryptionName('thing2.txt', ZipArchive::EM_AES_256); //encrypt it
$zip->close();
echo "Added thing1 and thing2 with the same password\n";
} else {
echo "KO\n";
}
?>
```
But you can also set the encryption method by index and not name, and you can set each password on a per-file basis... as well as specify weaker encryption options, using the [newly supported encryption options.](http://php.net/manual/en/zip.constants.php)
This example exercises these more complex options.
```
<?php
$zip = new ZipArchive();
if ($zip->open('test.zip', ZipArchive::CREATE) === TRUE) {
//being here means that we were able to create the file..
//setting this means that we do not need to pass in a password to every file, this will be the default
$zip->addFile('thing3.txt');
//$zip->setEncryptionName('thing3.txt', ZipArchive::EM_AES_128);
//$zip->setEncryptionName('thing3.txt', ZipArchive::EM_AES_192);
//you should just use ZipArchive::EM_AES_256 unless you have super-good reason why not.
$zip->setEncryptionName('thing3.txt', ZipArchive::EM_AES_256, 'password_for_thing3');
$zip->addFile('thing4.txt');
//or you can also use the index (starting at 0) of the file...
//which means the following line should do the same thing...
//but just referencing the text.txt by index instead of name..
//$zip->setEncryptionIndex(1, ZipArchive::EM_AES_256, 'password_for_thing_4'); //encrypt thing4, using its index instead of its name...
$zip->close();
echo "Added thing3 and thing4 with two different passwords\n";
} else {
echo "KO\n";
}
?>
```
The underlying support for zip encryption is enabled because libzip 1.2.0 introduced support for encryption. So you will need to have php 7.2 and libzip 7.2 in order to run this code... Hopefully this note will be cruft on this answer "real soon" | Create an encrypted zip archive with PHP | [
"",
"php",
"encryption",
"zip",
""
] |
I have a system that spend 66% of its time in a time(NULL) call.
It there a way to cache or optimize this call?
Context: I'm playing with Protothread for c++. Trying to simulate threads with state machines. So Therefore I cant use native threads.
Here's the header:
```
#ifndef __TIMER_H__
#define __TIMER_H__
#include <time.h>
#include <iostream>
class Timer
{
private:
time_t initial;
public:
Timer();
unsigned long passed();
};
#endif
```
and the source file:
```
#include "Timer.h"
using namespace std;
Timer::Timer()
{
initial = time(NULL);
}
unsigned long Timer::passed()
{
time_t current = time(NULL);
return (current - initial);
}
```
UPDATE:
Final solution!
The cpu cycles it going away somewhere, and if I spend them being correct. That is
not so bad after all.
```
#define start_timer() timer_start=time(NULL)
#define timeout(x) ((time(NULL)-timer_start)>=x)
``` | I presume you are calling it within some loop which is otherwise stonkingly efficient.
What you could do is keep a count of how many iterations your loop goes through before the return value of time changes.
Then don't call it again until you've gone through that many iterations again.
You can dynamically adjust this count upwards or downwards if you find you're going adrift, but you should be able to engineer it so that on average, it calls time() once per second.
Here's a rough idea of how you might do it (there's many variations on this theme)
```
int iterations_per_sec=10; //wild guess
int iterations=0;
while(looping)
{
//do the real work
//check our timing
if (++iterations>iterations_per_sec)
{
int t=time(NULL);
if (t==lasttime)
{
iterations_per_sec++;
}
else
{
iterations_per_sec=iterations/(t-lasttime);
iterations=0;
lastime=t;
//do whatever else you want to do on a per-second basis
}
}
}
``` | That sounds quite much, given that `time` only has a precision of 1 second. Sounds like you call it way too often. One possible improvement would be to maybe call it only each 500ms. So it will still hit every second.
So instead of calling it 100 times a second, start off a timer that rings every 500ms, taking the current time and storing it into an integer. Then, read that integer 100 times a second instead. | optimize time(NULL) call in c++ | [
"",
"c++",
"optimization",
""
] |
How can I access the public variable which in *Sample.xaml.cs* file like asp.net `<%=VariableName%>`? | There are a few ways to do this.
* Add your variable as a resource from codebehind:
```
myWindow.Resources.Add("myResourceKey", myVariable);
```
Then you can access it from XAML:
```
<TextBlock Text="{StaticResource myResourceKey}"/>
```
If you have to add it after the XAML gets parsed, you can use a `DynamicResource` above instead of `StaticResource`.
* Make the variable a property of something in your XAML. Usually this works through the `DataContext`:
```
myWindow.DataContext = myVariable;
```
or
```
myWindow.MyProperty = myVariable;
```
After this, anything in your XAML can access it through a `Binding`:
```
<TextBlock Text="{Binding Path=PropertyOfMyVariable}"/>
```
or
```
<TextBlock Text="{Binding ElementName=myWindow, Path=MyProperty}"/>
``` | For binding, if `DataContext` is not in use, you can simply add this to the constructor of the code behind:
```
this.DataContext = this;
```
Using this, every property in the code becomes accessible to binding:
```
<TextBlock Text="{Binding PropertyName}"/>
```
Another way is to just give a name to the root element of the XAML:
```
x:Name="root"
```
Since the XAML is compiled as a partial class of the code-behind, we can access every property by name:
```
<TextBlock Text="{Binding ElementName="root" Path=PropertyName}"/>
```
Note: access is only available to properties; not to fields. `set;` and `get;` or `{Binding Mode = OneWay}` are necessary. If OneWay binding is used, the underlying data should implement *INotifyPropertyChanged*. | Access codebehind variable in XAML | [
"",
"c#",
"wpf",
"xaml",
"silverlight",
""
] |
Suppose I have some code that looks like this:
```
foreach(type x in list y)
{
//dostuff1(x)
}
foreach(type x in list y)
{
//dostuff2(x)
}
foreach(type x in list y)
{
//dostuff3(x)
}
foreach(type x in list y)
{
//dostuff4(x)
}
foreach(type x in list y)
{
//dostuff5(x)
}
```
I cannot combine things into one big for loop like this:
```
foreach (type x in list y)
{
//dostuff1(x)
//dostuff2(x)
//dostuff3(x)
//dostuff4(x)
//dostuff5(x)
}
```
Doing so would change the order. Any commentary on the best ways to make the code simpler in C#?
I imagine I could solve this problem by creating a function like this, though I'd rather leave it the way it is than force future readers of my code to understand `yield`:
```
void func(type x)
{
dostuff1(x)
yield 0;
dostuff2(x)
yield 0;
dostuff3(x)
yield 0;
dostuff4(x)
yield 0;
dostuff5(x)
yield break;
}
for (int i = 0; i<5; ++i)
{
foreach (type x in list y)
{
//Call func(x) using yield semantics, which I'm not going to look up right now
}
}
``` | Another alternative:
```
List<Action<Foo>> actions = new List<Action<Foo>> {
doStuff1, doStuff2, doStuff3, doStuff4, doStuff5
};
foreach (Action<Foo> action in actions)
{
foreach (Foo x in list)
{
action(x);
}
}
```
Just checked, and that works. For instance:
```
using System;
using System.Collections.Generic;
public class Test
{
static void Main(string[] args)
{
var actions = new List<Action<string>> {
First, Second
};
foreach (var action in actions)
{
foreach (string arg in args)
{
action(arg);
}
}
}
static void First(string x)
{
Console.WriteLine("First: " + x);
}
static void Second(string x)
{
Console.WriteLine("Second: " + x);
}
}
```
Results of running `Test.exe a b c`
```
First: a
First: b
First: c
Second: a
Second: b
Second: c
``` | If you have a fairly constant list of actions, you could just avoid the foreach loops, but still do the actions explicitly (haven't tested the code):
```
list.ForEach(action1);
list.ForEach(action2);
list.ForEach(action3);
list.ForEach(action4);
``` | C# Code Simplification Query: The Sequential Foreach Loops | [
"",
"c#",
""
] |
Bash scripts are very useful and can save a lot of programming time. So how do you start a bash script in a C++ program? Also if you know how to make user become the super-user that would be nice also. Thanks! | Use the `system` function.
```
system("myfile.sh"); // myfile.sh should be chmod +x
``` | ```
#include <stdio.h>
#include <stdlib.h>
// ....
system("my_bash_script.sh");
``` | How to run a bash script from C++ program | [
"",
"c++",
"linux",
"bash",
"shell",
""
] |
Our web-based applications has user accounts tied down to users with the passwords specified during account creation. In the case of Java, how does one process the password securely, before persisting its hash in the database.
To be more specific, how does one ensure that the string holding the password is garbage collected within a sufficiently short interval of time ? | If you have the possibility (may be difficult in web applications), it would be better to store passwords in character arrays than to store them in strings. If you finished storing the password you can overwrite it in memory by using [Array.fill()](http://java.sun.com/javase/6/docs/api/java/util/Arrays.html#fill(char[],%20char)) and make the reference available for the garbage collector by discarding it:
```
Arrays.fill(password, ' ');
password = null;
```
I just noticed that nulling the password would be a bit paranoid but you can do if it reassures you :) | You do not use a String. You use a char[] and then overwrite the char[] when done.
There are absolutely no guarantees when it comes to garbage collection (aside from that the finalizer will run before the object is collected). The GC may never run, if it runs it may never GC the String that has the password in it. | How does one store password hashes securely in memory, when creating accounts? | [
"",
"java",
"security",
"hash",
"passwords",
""
] |
I just want to know that creating local variables to accept the return value of function is going to hit memory usage or performance in .Net applications , especially in ASP.Net.
say
```
MyObject myObject = Foo();
MyOtherObject myOtherObject = Boo();
SomeFuntion(myObject, myOtherObject);
```
OR
Should I use
```
MyFunction(Foo(), Boo());
```
Certainly the former usage has a better readability.. But what about the memory usage and performance?
Thanks in advance
123Developer | Don't optimise prematurely; in a release build it is quite likely that the compiler will optimise these away anyway! Either way, you are just talking a tiny amount of stack space for (presumably) a few references. Either approach is fine; go with whichever is more readable. | CIL (the intermediate language into which C# is compiled) is a stack-based language so the return values of the intermediate functions need to end up on the stack before being passed as arguments to the final one anyway.
There's no way of predicting what the C# compiler will do[1] in terms of locals; it may decide to use locals when you do, or it may use the stack behaviour and skip them altogether. Similarly it may synthesize locals even when you don't use them, or it might not.
Either way, the performance difference isn't worth worrying about.
---
[1] Yes, of course, you can compile and look at the IL it produces to determine what it will do, but that is only valid for the current version of the compiler you're using and is an implementation detail you shouldn't rely on. | Creating Local variables in .Net | [
"",
"c#",
"premature-optimization",
""
] |
When did Java first get a JIT compiler for production code? | Borland had the first one followed shortly by Symantec. Sun licensed the Symantec one. Symantec demoed theirs in March of 1996. | <http://java.sun.com/features/2000/06/time-line.html>
October 25, 1996
Sun announces first Just-In-Time (JIT) compiler for Java platform
Also, from wikipedia: Since JRE version 1.2, Sun's JVM implementation has included a just-in-time compiler instead of an interpreter.
<http://en.wikipedia.org/wiki/Java_(Sun)> | When did Java get a JIT compiler? | [
"",
"java",
"history",
""
] |
I have a form on my index.html page which makes a POST request to a Java Servlet. This servlet does some processing and I would like to redirect back to index.html with some variables that the servlet has produced.
In PHP, it would be as simple as:
```
header("Location: index.html?var1=a&var2=b");
```
How can I acheive the same with Java, hopefully making use of a GET request.
Thanks all | In a Java Servlet, you'll want to write:
```
response.sendRedirect("index.html?var1=a&var2=b...");
```
Oh right, I should note that you'll want to do this in the processor method like doGet() or doPost()... | You redirect the response to the same servlet with some additional values:
```
req.setAttribute("message","Hello world");
rd =req.getRequestDispatcher("/index.jsp");
```
And in your servlet, you grab the data with:
```
<%=request.getAttribute("message");%>
``` | How do I redirect to a html page and pass variables to that page in Java? | [
"",
"java",
"html",
"forms",
"servlets",
""
] |
Is the private member access at the class level or at the object level. If it is at the object level, then the following code should not compile
```
class PrivateMember {
private int i;
public PrivateMember() {
i = 2;
}
public void printI() {
System.out.println("i is: "+i);
}
public void messWithI(PrivateMember t) {
t.i *= 2;
}
public static void main (String args[]) {
PrivateMember sub = new PrivateMember();
PrivateMember obj = new PrivateMember();
obj.printI();
sub.messWithI(obj);
obj.printI();
}
}
```
Please clarify if accessing the member i of obj within the messWithI() method of sub is valid | As DevSolar has said, it's at the (top level) class level.
From [section 6.6 of the Java Language Specification](http://java.sun.com/docs/books/jls/third_edition/html/names.html#6.6):
> Otherwise, if the member or
> constructor is declared private, then
> access is permitted if and only if it
> occurs within the body of the top
> level class (§7.6) that encloses the
> declaration of the member or
> constructor.
Note that there's no indication that it's restricted to members for a particular object.
As of Java 7, [the compiler no longer allows access to private members of type variables](http://www.oracle.com/technetwork/java/javase/compatibility-417013.html#source). So if the method had a signature like `public <T extends PrivateMember> void messWithI(T t)` then it would be a compiler error to access `t.i`. That wouldn't change your particular scenario, however. | Note that you don't even need source level access to mess with private fields. By using `java.lang.reflect.AccessibleObject.setAccessibe()`, all code can access all private members of all other code unless you specify a security policy that disallows it.
**`private` is not by itself a security feature!** It is merely a strong hint to other developers that something is an internal implementation detail that other parts on the code should not depend on. | Private Member Access Java | [
"",
"java",
"accessibility",
"private-members",
""
] |
Is there a way to use PHP to detect if the page is being loaded using IE6? | Try checking their user agent for `'MSIE 6.'`.
```
$using_ie6 = (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE 6.') !== FALSE);
```
This is based on [this user agent information](http://www.useragentstring.com/pages/Internet%20Explorer/). | You can detect IE6 with HTML this way
```
<!--[if IE 6]>
// ie6 only stuff here
<![endif]-->
```
~~[Here's a link on how it's done in PHP](http://www.studioyucca.com/2008/10/01/detecting-ie6-in-php/)~~[Way Back Machine](http://web.archive.org/web/20081221042900/http://www.studioyucca.com/2008/10/01/detecting-ie6-in-php/) but I've seen many false positives in parsing the `$_SERVER["HTTP_USER_AGENT"]` for IE6 | Can I detect IE6 with PHP? | [
"",
"php",
"internet-explorer-6",
"cross-browser",
""
] |
I have found many questions and articles about this but i still have some difficulties.
I'm using the following command
/usr/bin/php home/domain.com/public\_html/cron/script.php
I receive the following error
Status: 404 Not Found
X-Powered-By: PHP/5.2.8
Content-type: text/html
No input file specified.
i'm using Cpanel, the file is hosted on domain.com/cron/script.php
Anyideas, thanks :p | Try:
```
wget -O - http://domain.com/cron/script.php
```
and see if you get a better result.
Edit: added "- O - " to not write output to home folder. | Put a leading slash on the script name, i.e.
```
/usr/bin/php /home/domain.com/public_html/cron/script.php
```
Unless you actually intend to run the script through the web, as in lacqui's answer, *and* you don't mind random third parties being able to run it any time they like, there's no reason you should put it inside your public\_html directory; quite the opposite. | How to run a php script in cron | [
"",
"cron",
"php",
""
] |
I'm thinking of buying Martin Fowler's "Patterns of Enterprise Application Architecture".
From what I can see it seems like a great book, an architectural book with bias towards enterprise Java -- just what I need.
However, in computer years, it is quite old. 2003 was a long time ago, and things have moved on quite a bit since that time.
So I'm wondering if anyone can tell me: is this book still relevant, and worth the read? | Yes, it is still very relevant and an excellent resource. | This book, and [Eric Evans book about Domain-Driven Design](http://domaindrivendesign.org/books#DDD), are my books of the year - every year ;) ... | Fowler's "Patterns of Enterprise Application Architecture" still relevant? | [
"",
"java",
"jakarta-ee",
"architecture",
"poeaa",
""
] |
In the diagram below there is a 1:1 relationship between 'DodgyOldTable' and 'MainTable'. Table 'Option' contains records with 'OptionVal1', 'OptionVal2' and 'OptionVal3' in the 'OptionDesc' field.
I need to do an insert into MainTable\_Option with a select from DodgyOldTable. Something like this:
```
INSERT MainTable_Option ([MainTableID],[OptionID])
SELECT ID, (CASE WHEN OptionVal1 = 'y' THEN
(SELECT OptionID
FROM Option
WHERE OptionDesc = 'OptionVal1') END
FROM DodgyOldTable
```
If possible I want to avoid using several different select statements to perform the insert operation.
[alt text http://www.freeimagehosting.net/uploads/863f10bf5f.jpg](http://www.freeimagehosting.net/uploads/863f10bf5f.jpg) | ```
INSERT
MainTable_Option
(
MainTableID,
OptionID
)
SELECT
d.ID,
o.OptionId
FROM
DodgyOldTable d
INNER JOIN Option o ON
(d.OptionVal1 = 'Y' AND o.OptionDesc = 'OptionVal1') OR
(d.OptionVal2 = 'Y' AND o.OptionDesc = 'OptionVal2') OR
(d.OptionVal3 = 'Y' AND o.OptionDesc = 'OptionVal3')
``` | perhaps not the most efficient solution but by using a union, this should work.
```
INSERT MainTable_Option ([MainTableID],[OptionID])
SELECT ID, (SELECT OptionID FROM Option WHERE OptionDesc = 'OptionVal1')
FROM DodgyOldTable dot
WHERE OptionVal1 = 'y'
UNION SELECT ID, (SELECT OptionID FROM Option WHERE OptionDesc = 'OptionVal2')
FROM DodgyOldTable dot
WHERE OptionVal2 = 'y'
UNION SELECT ID, (SELECT OptionID FROM Option WHERE OptionDesc = 'OptionVal3')
FROM DodgyOldTable dot
WHERE OptionVal3 = 'y'
``` | Perform INSERT with SELECT to insert multiple records | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
I am using Asp.Net c# and Sql Server 2005. I am using Masterpage and content page. when i debug my code that time it's give error ::
**Window Internet Explorer
SYS.WEBFORMS.PAGEREQUESTMANAGER TIMEOUTEXCEPTION: THE SERVER REQUEST TIMED OUT.**
Any body please help me out ?
Thanks | It is an Ajax error - do you only get the error when debugging? If you want to increase this timeout then set the AsyncPostBackTimeout of your script manager to something large | You have an ajax request that's taking too long to complete. It would help if you can isolate the request and share what it's trying to do. | Sql Server 2005 - Time Out in Asp.net c# | [
"",
"c#",
"asp.net",
"sql-server-2005",
""
] |
I'm writing a php application that submits via curl data to sign up for an iContact email list. However I keep getting an invalid email address error. I think this may be due to the fact that I'm escaping the @ symbol so it looks like %40 instead of @. Also, according to the php documentation for curl\_setopt with CURLOPT\_POSTFIELDS:
> The full data to post in a HTTP
> "POST" operation. To post a file,
> prepend a filename with @ and use the
> full path.
So, is there anyway to pass the @ symbol as post data through curl in php without running it through urlencode first? | Use [`http_build_query()`](http://php.net/http_build_query) on your data-array first before passing it to `curl_setopt()`, that will lead to it sending the form as `application/x-www-form-encoded` instead of `multipart/form-data` (and thus the @ is not interpreted).
Also why do you really care about the @ in an email-address? It only matters if the @ is the first character, not somewhere in the middle. | After search PHP curl manual, I found there is no information to escape the first ‘@’ if the post field is a string instead of a file if post with multipart/form-data encoding.
The way I worked around this problem is prefixing a blank at the beginning of the text. While our backend API will strip blanks so it could remove the blank and restore the original text. I don't know weather Twitter API will trim blanks on user input.
If so, this workaround also works for you.
If any one found the way to escaping the first '@' when using PHP curl with multipart/form-data encoding, please let us know. | Escaping CURL @ symbol with PHP | [
"",
"php",
"curl",
"escaping",
""
] |
While coding in Python it's better to code by following the guidelines of PEP8.
And while coding for Symbian it's better to follow its coding standards.
But when I code for PyS60 which guidelines should I follow? Till now I have been following PEP8, but [this code](http://wiki.forum.nokia.com/index.php/A_100%25_Python_implemented_Listbox_base_class) shows the opposite. Do I need to rework my code? | I don't see anything in your code sample that is obviously bogus. It's not the style I'd use, but neither is it hard to read, and it's not so far from PEP8 that I'd call it “the opposite”.
PEP8 shouldn't be seen as hard-and-fast law to which all code must conform, character by rigid character. It is a baseline for readable Python. When you go a little bit Java-programmer and get that antsiness about making the spacing around every operator consistent, go back and read the start of PEP8 again. The bit with the hobgoblin.
Don't get hung up on lengthy ‘reworking’ of code that is functional, readable, and at least in the same general vicinity as PEP8. | "Do I need to rework my code?"
Does it add value to rework you code?
How many folks will help you develop code who
A) don't know PEP 8
B) only know PyS60 coding standards because that's the only code they've ever seen.
and
C) cannot be taught anything different than the PyS60 coding standards?
List all the people who you'll work with that meet all three criteria. Then decide which is cheaper: rework your code or fire them. | Clashing guidelines | [
"",
"python",
"symbian",
"coding-style",
"pys60",
"pep8",
""
] |
I have a few .NET developers who only want to use the MS AJAX Toolkit and think JavaScript (and any JS Library) is evil. I tried to explain that if you treat client-side development like a grown-up language you can build maintainable code ... but I assume that the classic ASP days have left a mark on these guys. Anyone have a suggestion to help convince this type of developer that learning jQuery will actually benefit them in the long run as the industry is trending back to "lets get close to the metal again" w/ MVC for example? | Tell them microsoft endorses jquery and that it's shipping with MVC | If they don't realize that jQuery is the bee's knees - they're living under a rock - tell them about all of the people that are using jQuery (Google, Dell, MLB, Bank of America.....the rest of a good list is in the middle of the jQuery home page) - or just tell them that every time they go to their Netflix account they are using jQuery or if they visit the president's web site (which could backfire I guess.... ;)
Emphasize that learning a 'technology' that is becoming that ubiquitous can only help your career. | How to convince my fellow .NET developers that learning jQuery will be beneficial | [
"",
"javascript",
"jquery",
"client-side",
""
] |
Can't remember where I read it, but I remember a MS guy saying that once you create a reader around a System.IO.Stream, then the stream is not longer responsible for the disposal of the stream.
Is this true? Can someone confirm this? Maybe provide a reference.
This means the outer using in this code is redundant
```
using (var s = new FileStream(@"c:\file.txt",FileMode.Open)) {
using (var reader = new StreamReader(s)) {
reader.ReadToEnd();
}
}
``` | Both `FileStream` and `StreamReader` implement `IDisposable`, so I would use both `using`'s regardless, that way if the underlying implementation were to change, however unlikely, your code would still be good. | read the approved answer to this question:
[Who Disposes of an IDisposable public property?](https://stackoverflow.com/questions/674879/who-disposes-of-an-idisposable-public-property/675001#675001)
It says that StreamReader always disposes the underlying stream. | System.IO.Stream disposable with a reader | [
"",
"c#",
".net",
"file-io",
"stream",
""
] |
Having the following generic class that would contain either **`string, int, float, long`** as the type:
```
public class MyData<T>
{
private T _data;
public MyData (T value)
{
_data = value;
}
public T Data { get { return _data; } }
}
```
I am trying to get a list of **`MyData<T>`** where each item would be of different **`T`**.
I want to be able to access an item from the list and get its value as in the following code:
```
MyData<> myData = _myList[0]; // Could be <string>, <int>, ...
SomeMethod (myData.Data);
```
where **`SomeMethod()`** is declared as follows:
```
public void SomeMethod (string value);
public void SomeMethod (int value);
public void SomeMethod (float value);
```
---
**UPDATE:**
**`SomeMethod()`** is from another tier class I do not have control of and **`SomeMethod(object)`** does not exist.
---
However, I can't seem to find a way to make the compiler happy.
Any suggestions?
Thank you. | Delegates can really help simplify this, and still keep things type-safe:
```
public void TestMethod1()
{
Action<SomeClass, int> intInvoke = (o, data) => o.SomeMethod(data);
Action<SomeClass, string> stringInvoke = (o, data) => o.SomeMethod(data);
var list = new List<MyData>
{
new MyData<int> { Data = 10, OnTypedInvoke = intInvoke },
new MyData<string> { Data = "abc", OnTypedInvoke = stringInvoke }
};
var someClass = new SomeClass();
foreach (var item in list)
{
item.OnInvoke(someClass);
}
}
public abstract class MyData
{
public Action<SomeClass> OnInvoke;
}
public class MyData<T> : MyData
{
public T Data { get; set; }
public Action<SomeClass, T> OnTypedInvoke
{ set { OnInvoke = (o) => { value(o, Data); }; } }
}
public class SomeClass
{
public void SomeMethod(string data)
{
Console.WriteLine("string: {0}", data);
}
public void SomeMethod(int data)
{
Console.WriteLine("int: {0}", data);
}
}
``` | I think the issue that you're having is because you're trying to create a generic type, and then create a list of that generic type. You could accomplish what you're trying to do by contracting out the data types you're trying to support, say as an IData element, and then create your MyData generic with a constraint of IData. The downside to this would be that you would have to create your own data types to represent all the primitive data types you're using (string, int, float, long). It might look something like this:
```
public class MyData<T, C>
where T : IData<C>
{
public T Data { get; private set; }
public MyData (T value)
{
Data = value;
}
}
public interface IData<T>
{
T Data { get; set; }
void SomeMethod();
}
//you'll need one of these for each data type you wish to support
public class MyString: IData<string>
{
public MyString(String value)
{
Data = value;
}
public void SomeMethod()
{
//code here that uses _data...
Console.WriteLine(Data);
}
public string Data { get; set; }
}
```
and then you're implementation would be something like:
```
var myData = new MyData<MyString, string>(new MyString("new string"));
// Could be MyString, MyInt, ...
myData.Data.SomeMethod();
```
it's a little more work but you get the functionality you were going for.
**UPDATE:**
remove SomeMethod from your interface and just do this
```
SomeMethod(myData.Data.Data);
``` | C#: Declaring and using a list of generic classes with different types, how? | [
"",
"c#",
".net",
"generics",
"list",
""
] |
Table has about 8 million rows. There is a non-unique index for X.
Showing indexes, it shows that in the table there is a non-unique index on key name X with "seq\_in\_index" of 1, collation A, cardinality 7850780, sub\_part NULL, packed NULL, index\_type BTREE.
Still, this query can take 5 seconds to run. The list of ints comes from another system, and I am not allowed to store them in a table, because they represent friendships on a social network.
Is there a faster way than a massive IN statement? | You can convert your list of IDs into a temp-table (or table-var if MySql supports them) and join with it.
The table would only live as long as the query so you're not actually *storing* anything in a table. | You could try storing them in a [temporary table](http://dev.mysql.com/doc/refman/5.1/en/create-table.html). This table wouldn't be stored in the database permanently and I think the resulting join (assuming that you index the temporary table as well) would be faster since it would be able to process the indices in parallel and not have to do an index lookup for each int the IN clause. Of course, MySQL may optimize the IN clause and do the same thing if it knows that it will be using an index so it may not actually gain you anything. I would give a try though and see if it is faster. | SELECT * FROM table WHERE x IN (...a few hundred ints...) | [
"",
"sql",
"mysql",
"indexing",
"in-clause",
""
] |
What are the best options for connecting PHP apps to logic located in .NET libraries?
PHP, since v5.0, supports [a DOTNET class](https://www.php.net/manual/en/class.dotnet.php) that is supposed to let me invoke .NET logic from a PHP script. But it seems there are many problems - I've not been able to get it to work reliably, with arbitrary .NET classes. The doc is sort of slim and what *is* documented isn't really correct. The questions on the internets on this class are many, as are the bug reports on php.net.
I have been able to get PHP to connect with .NET via COM interop - but this requires that the .NET class be ComVisible. And as far as I know, because of the COM requirement, this works on Windows only.
I've heard of the [Phalanger project](http://phalanger.codeplex.com/) but don't know many details. Does it work with arbitrary PHP scripts? Work on Linux? Does it have heavy perf or runtime implications?
Does it even make sense to do this, or is it one of those you-could-do-it-but-you-shouldn't sort of things?
EDIT: I'd like to hear about the general case: there is a wide variety of .NET class libraries available, and it would be nice to be able to take advantage of them from different environments, including PHP. Examples might be encryption, logging, data access, clients to HPC clusters. The particular immediate scenario is a ZIP library with AES encryption, available in .NET. | I think the best way is to do it via COM. | Microsoft doesn't ship or support .NET on Linux. If you wan't to run .NET code on Linux then you should look at Mono. I don't know if PHP 5 supports Mono as well as MicroSoft.NET | Best way to call .NET classes from PHP? | [
"",
".net",
"php",
"com",
""
] |
I have the following code:
```
SN.get_Chars(5)
```
`SN` is a string so this should give the 5th Char. Ok!
Now I have another code but: `SN.get_Chars(0x10)`
I wonder what 0x10 is? Is it a number? If it's so, then what is it in decimal notation? | 0x means the number is [hexadecimal](http://en.wikipedia.org/wiki/Hexadecimal), or base 16.
0x10 is 16. | `0xNNNN` (not necessarily four digits) represents, in C at least, a hexadecimal (base-16 because 'hex' is 6 and 'dec' is 10 in Latin-derived languages) number, where `N` is one of the digits `0` through `9` or `A` through `F` (or their lower case equivalents, either representing 10 through 15), and there may be 1 or more of those digits in the number. The other way of representing it is NNNN16.
It's very useful in the computer world as a single hex digit represents four bits (binary digits). That's because four bits, each with two possible values, gives you a total of `2 x 2 x 2 x 2` or `16` (24) values. In other words:
```
_____________________________________bits____________________________________
/ \
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
| bF | bE | bD | bC | bB | bA | b9 | b8 | b7 | b6 | b5 | b4 | b3 | b2 | b1 | b0 |
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
\_________________/ \_________________/ \_________________/ \_________________/
Hex digit Hex digit Hex digit Hex digit
```
A base-X number is a number where each position represents a multiple of a power of X.
---
In base 10, which we humans are used to, the digits used are `0` through `9`, and the number 730410 is:
* (7 x 103) = 700010 ; plus
* (3 x 102) = 30010 ; plus
* (0 x 101) = 010 ; plus
* (4 x 100) = 410 ; equals 7304.
---
In octal, where the digits are `0` through `7`. the number 7548 is:
* (7 x 82) = 44810 ; plus
* (5 x 81) = 4010 ; plus
* (4 x 80) = 410 ; equals 49210.
Octal numbers in C are preceded by the character `0` so `0123` is not 123 but is instead (1 \* 64) + (2 \* 8) + 3, or 83.
---
In binary, where the digits are `0` and `1`. the number 10112 is:
* (1 x 23) = 810 ; plus
* (0 x 22) = 010 ; plus
* (1 x 21) = 210 ; plus
* (1 x 20) = 110 ; equals 1110.
---
In hexadecimal, where the digits are `0` through `9` and `A` through `F` (which represent the "digits" `10` through `15`). the number 7F2416 is:
* (7 x 163) = 2867210 ; plus
* (F x 162) = 384010 ; plus
* (2 x 161) = 3210 ; plus
* (4 x 160) = 410 ; equals 3254810.
Your relatively simple number `0x10`, which is the way C represents 1016, is simply:
* (1 x 161) = 1610 ; plus
* (0 x 160) = 010 ; equals 1610.
As an aside, the different bases of numbers are used for many things.
* base 10 is used, as previously mentioned, by we humans with 10 digits on our hands.
* base 2 is used by computers due to the relative ease of representing the two binary states with electrical circuits.
* base 8 is used almost exclusively in UNIX file permissions so that each octal digit represents a 3-tuple of binary permissions (read/write/execute). It's also used in C-based languages and UNIX utilities to inject binary characters into an otherwise printable-character-only data stream.
* base 16 is a convenient way to represent four bits to a digit, especially as most architectures nowadays have a word size which is a multiple of four bits.
* base 64 is used in encoding mail so that binary files may be sent using only printable characters. Each digit represents six binary digits so you can pack three eight-bit characters into four six-bit digits (25% increased file size but guaranteed to get through the mail gateways untouched).
* as a semi-useful snippet, base 60 comes from some very old civilisation (Babylon, Sumeria, Mesopotamia or something like that) and is the source of 60 seconds/minutes in the minute/hour, 360 degrees in a circle, 60 minutes (of arc) in a degree and so on [not really related to the computer industry, but interesting nonetheless].
* as an even less-useful snippet, the ultimate question and answer in [The Hitchhikers Guide To The Galaxy](http://en.wikipedia.org/wiki/The_Hitchhiker%27s_Guide_to_the_Galaxy) was "What do you get when you multiply 6 by 9?" and "42". Whilst same say this is because the Earth computer was faulty, others see it as proof that the creator has 13 fingers :-) | What is 0x10 in decimal? | [
"",
"c#",
"numbers",
"hex",
""
] |
With the increasing popularity of powerful client side javascript widgets, I am curious on when is the best time to handle the sorting of data strictly on the client side, making use of widgets such as those found in YUI, and when to make a request to the backend and have it handle the sorting via a DB query or other means. | It depends on the amount of data - the best thing to do is to test and see which is faster. | It really depends what you're sorting, whether the client will require all of the data or only a sorted subset at any one time, and how expensive the sort actually is. | Sorting in Web Applications | [
"",
"javascript",
"ajax",
"sorting",
""
] |
I'd like to create a Python decorator that can be used either with parameters:
```
@redirect_output("somewhere.log")
def foo():
....
```
or without them (for instance to redirect the output to stderr by default):
```
@redirect_output
def foo():
....
```
Is that at all possible?
Note that I'm not looking for a different solution to the problem of redirecting output, it's just an example of the syntax I'd like to achieve. | I know this question is old, but some of the comments are new, and while all of the viable solutions are essentially the same, most of them aren't very clean or easy to read.
Like thobe's answer says, the only way to handle both cases is to check for both scenarios. The easiest way is simply to check to see if there is a single argument and it is callabe (NOTE: extra checks will be necessary if your decorator only takes 1 argument and it happens to be a callable object):
```
def decorator(*args, **kwargs):
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
# called as @decorator
else:
# called as @decorator(*args, **kwargs)
```
In the first case, you do what any normal decorator does, return a modified or wrapped version of the passed in function.
In the second case, you return a 'new' decorator that somehow uses the information passed in with \*args, \*\*kwargs.
This is fine and all, but having to write it out for every decorator you make can be pretty annoying and not as clean. Instead, it would be nice to be able to automagically modify our decorators without having to re-write them... but that's what decorators are for!
Using the following decorator decorator, we can deocrate our decorators so that they can be used with or without arguments:
```
def doublewrap(f):
'''
a decorator decorator, allowing the decorator to be used as:
@decorator(with, arguments, and=kwargs)
or
@decorator
'''
@wraps(f)
def new_dec(*args, **kwargs):
if len(args) == 1 and len(kwargs) == 0 and callable(args[0]):
# actual decorated function
return f(args[0])
else:
# decorator arguments
return lambda realf: f(realf, *args, **kwargs)
return new_dec
```
Now, we can decorate our decorators with @doublewrap, and they will work with and without arguments, with one caveat:
I noted above but should repeat here, the check in this decorator makes an assumption about the arguments that a decorator can receive (namely that it can't receive a single, callable argument). Since we are making it applicable to any generator now, it needs to be kept in mind, or modified if it will be contradicted.
The following demonstrates its use:
```
def test_doublewrap():
from util import doublewrap
from functools import wraps
@doublewrap
def mult(f, factor=2):
'''multiply a function's return value'''
@wraps(f)
def wrap(*args, **kwargs):
return factor*f(*args,**kwargs)
return wrap
# try normal
@mult
def f(x, y):
return x + y
# try args
@mult(3)
def f2(x, y):
return x*y
# try kwargs
@mult(factor=5)
def f3(x, y):
return x - y
assert f(2,3) == 10
assert f2(2,5) == 30
assert f3(8,1) == 5*7
``` | Using keyword arguments with default values (as suggested by kquinn) is a good idea, but will require you to include the parenthesis:
```
@redirect_output()
def foo():
...
```
If you would like a version that works without the parenthesis on the decorator you will have to account both scenarios in your decorator code.
If you were using Python 3.0 you could use keyword only arguments for this:
```
def redirect_output(fn=None,*,destination=None):
destination = sys.stderr if destination is None else destination
def wrapper(*args, **kwargs):
... # your code here
if fn is None:
def decorator(fn):
return functools.update_wrapper(wrapper, fn)
return decorator
else:
return functools.update_wrapper(wrapper, fn)
```
In Python 2.x this can be emulated with varargs tricks:
```
def redirected_output(*fn,**options):
destination = options.pop('destination', sys.stderr)
if options:
raise TypeError("unsupported keyword arguments: %s" %
",".join(options.keys()))
def wrapper(*args, **kwargs):
... # your code here
if fn:
return functools.update_wrapper(wrapper, fn[0])
else:
def decorator(fn):
return functools.update_wrapper(wrapper, fn)
return decorator
```
Any of these versions would allow you to write code like this:
```
@redirected_output
def foo():
...
@redirected_output(destination="somewhere.log")
def bar():
...
``` | How to create a decorator that can be used either with or without parameters? | [
"",
"python",
"decorator",
""
] |
I'm maintaining a number of console applications at work and one thing I've been noticing in a number of them is that they call Environment.Exit(0).
A sample program would look like this:
```
public class Program
{
public static void Main(string[] args)
{
DoStuff();
Environment.Exit(0);
}
}
```
I don't understand what the intent of the original programmer was in doing this? In my mind even without the Environment.Exit statement the program should exit just fine. That said, for one of these programs, it's console window has been remaining even after it was supposed to have closed so I'm really not sure what's going on there....
Am I missing something here? Or is there a reason why Environment.Exit should be called in this instance? | The only reason for calling `Exit()` as the last line of the Main method is if there might be other foreground threads running. They would stay running if execution just fell off the end of `Main`. Even in this case, it would usually be a better idea either to put in some explicit graceful termination into the other threads - or make them background threads to start with.
If you ever want to return a different exit code from `Main`, the simpler way to achieve that is to declare it to return `int`.
In short, I don't think you need `Environment.Exit()` here, and it's worth asking your colleagues exactly why they're using it - chances are they won't be able to give you a good reason, and it's another bit of fluff you can cut out. | Basically, the statement `Environment.Exit(0)` tells the operating system that this is a "clean" exit. There are other numbers as well, each with a different meaning like, `Environment.Exit(1)`.
However, one thing to note is that the "Main" has been declared as returning nothing "void", so the exit code will really not have a meaning to it.
Just in case you wanted to know more about the different exit codes, have a look here:
*[System Error Codes (0-499)](https://learn.microsoft.com/en-us/windows/win32/debug/system-error-codes--0-499-)* | When should one use Environment.Exit to terminate a console application? | [
"",
"c#",
".net",
"console-application",
""
] |
I tend to use the words define, declare and assign interchangeably but this seems to cause offense to some people. Is this justified? Should I only use the word declare for the first time I assign to a variable? Or is there more to it than that? | Define and declare are similar but assign is very different.
Here I am declaring (or defining) a variable:
```
int x;
```
Here I am assigning a value to that variable:
```
x = 0;
```
Here I am doing both in one statement:
```
int x = 0;
```
**Note**
Not all languages support declaration and assignment in one statement:
**T-SQL**
```
declare x int;
set x = 0;
```
Some languages require that you assign a value to a variable upon declaration. This requirement allows the compiler or interpreter of the language to infer a type for the variable:
**Python**
```
x = 0
``` | A definition is where a value or function is described, i.e. the compiler or programmer is told precisely what it is, e.g.
```
int foo()
{
return 1;
}
int var; // or, e.g. int var = 5; but this is clearer.
```
A declaration tells the compiler, or programmer that the function or variable exists. e.g.
```
int foo();
extern int var;
```
An assignment is when a variable has its value set, usually with the = operator. e.g.
```
a = b;
a = foo();
``` | What exactly are C++ definitions, declarations and assignments? | [
"",
"c++",
"variable-assignment",
"terminology",
"declare",
""
] |
I need some way to check the size of a download without having to download the entire file. I am using C# and the System.Net.WebClient to do the downloads.The check needs to run in a asp.net webservice.
Thanks | Use HTTP method **HEAD** to retrieve **Content-Length:** header.
```
HEAD / HTTP/1.1
Host: www.example.com
HTTP/1.1 200 OK
Date: Wed, 18 Mar 2009 11:21:51 GMT
Server: Apache/2.2.3 (CentOS)
Last-Modified: Tue, 15 Nov 2005 13:24:10 GMT
ETag: "b80f4-1b6-80bfd280"
Accept-Ranges: bytes
Content-Length: 438
Connection: close
Content-Type: text/html; charset=UTF-8
``` | Make a HEAD (rather than GET or POST) request to just get the response headers, this should include the content-length header with the information you need. | Checking Download size before download | [
"",
"c#",
".net",
"asp.net",
""
] |
Is there a simple tutorial for me to get up to speed in SSE, SSE2 and SSE3 in GNU C++? How can you do code optimization in SSE? | Sorry don't know of a tutorial.
Your best bet (IMHO) is to use SSE via the "intrinsic" functions Intel provides to wrap (generally) single SSE instructions.
These are made available via a set of include files named \*mmintrin.h e.g xmmintrin.h is the original SSE instruction set.
Begin familiar with the contents of Intel's Optimization [Reference Manual](https://www.intel.com/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-optimization-manual.pdf) is a good idea (see section 4.3.1.2 for an example of intrinsics) and the SIMD sections are essential reading. The instruction set reference manuals are pretty helpful too, in that each instruction's documentation includes the "intrinsic" function it corresponds to.
*Do* spend some time inspecting the assembler produced by the compiler from intrinsics (you'll learn a lot) and on profiling/performance measurement (you'll avoid wasting time SSE-ing code for little return on the effort).
**Update 2011-05-31:** There is some very nice coverage of intrinsics and vectorization in Agner Fog's [optimization PDFs](http://agner.org/optimize/) ([thanks](https://stackoverflow.com/questions/695222/code-optimization-bibles/695293#695293)) although it's a bit spread about (e.g section 12 of the [first one](http://agner.org/optimize/optimizing_cpp.pdf) and section 5 of the [second one](http://agner.org/optimize/optimizing_assembly.pdf)). These aren't exactly tutorial material (in fact there's a "these manuals are not for beginners" warning) but they do rightly treat SIMD (whether used via asm, intrinsics or compiler vectorization) as just one part of the larger optimization toolbox.
**Update 2012-10-04:** A [nice little Linux Journal article](http://www.linuxjournal.com/content/introduction-gcc-compiler-intrinsics-vector-processing) on gcc vector intrinsics deserves a mention here. More general than just SSE (covers PPC and ARM extensions too). There's a good collection of references on the [last page](http://www.linuxjournal.com/content/introduction-gcc-compiler-intrinsics-vector-processing?page=0,4), which drew my attention to Intel's ["intrinsics guide"](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html). | The most simple optimization to use is to allow gcc to emit SSE code.
Flags: `-msse`, `-msse2`, `-msse3`, `-march=`, `-mfpmath=sse`
For a more concise list about 386 options, see <http://gcc.gnu.org/onlinedocs/gcc-4.3.3/gcc/i386-and-x86_002d64-Options.html#i386-and-x86_002d64-Options>, more exact documentation for your specific compiler version is there: <http://gcc.gnu.org/onlinedocs/>.
For optimization, always check out Agner Fog's: <http://agner.org/optimize/>. I think he doesn't have SSE tutorials for intrinsics, but he has some really neat std-c++ tricks and also provides lots of information about coding SSE assembly (which can often be transcribed to intrinsics). | SSE SSE2 and SSE3 for GNU C++ | [
"",
"c++",
"optimization",
"simd",
"sse",
"sse2",
""
] |
I have a list of radio stations, mostly .mp3 and .ogg. I would like to have a player on a web page that could be controlled with JavaScript. Now I use [jlgui](http://www.javazoom.net/applets/jlguiapplet/jlguiapplet.html), but it is somewhat limited.
Do you know of any alternative to jlgui? Preferably a java applet, but I can tolerate flash or even a system-default media player for a particular content-type. | I found JPlayer which uses HTML5 if available, otherwise it falls back to Flash. Works almost as good as the JLgui | There are a thousand MP3 players for Flash, using the native streaming stuff. Unfortunately that copes generally poorly with streamed MP3 (either over Icecast HTTP, or even more so under SHOUTcast ICY). Generally the player has to reconnect to the stream every so often, causing a playback glitch, otherwise memory just fills with MP3 data.
OGG is harder. There's no native support, but in Flash 10 you can play any old samples you can decode yourself, so it's possible to implement your own OGG decoder. It needs a lot of CPU on the client though. See <http://barelyfocused.net/blog/2008/10/03/flash-vorbis-player/> — I don't know of anyone having fixed this up into a single player that can do both MP3 and OGG from the same interface yet, but there's no reason it shouldn't be possible. | Playing audio streams on a web page | [
"",
"java",
"flash",
"audio",
"applet",
"audio-streaming",
""
] |
I'm trying to learn and grasp what and how C# does things. I'm historically a Visual Foxpro (VFP) developer, and somewhat spoiled at the years of visual inheritance by creating my own baseline of user controls to be used application wide.
In trying to learn the parallels in C#, I am stuck on something. Say I derive my own label control (control is subclass of label) defined with a font "Arial", 10 point. Then, on any form I add it to, the Designer will automatically pre-fill in some property values which can be seen in the "Designer.cs" portion of the Form class.
```
this.LabelHdr2.AutoSize = true;
this.LabelHdr2.Font = new System.Drawing.Font("Arial", 14F, System.Drawing.FontStyle.Bold);
this.LabelHdr2.ForeColor = System.Drawing.Color.Blue;
this.LabelHdr2.Location = new System.Drawing.Point(150, 65);
this.LabelHdr2.Name = "LabelHdr2";
this.LabelHdr2.Size = new System.Drawing.Size(158, 22);
this.LabelHdr2.TabIndex = 5;
this.LabelHdr2.Text = "LabelHdr2";
```
I want to prevent things like the Font, Color, Size, AutoSize from getting generated every time a control is put on the form. If I later decide to change the font from "Arial" 10, to "Tahoma" 11, I would have to go back to all the forms (and whatever other custom controls) and edit to change over.
In VFP, if I change anything of my baseclass, all forms automatically recognize the changes. I don't have to edit anything (with exception of possible alignments via sizing impacts)... but color, font, and all else are no problems in VFP...
In C#, I have to go back and change each form so it is recognized by the new / updated values of the class...
Is there a reasonable way to avoid this? | Here is a simple solution using the [`ReadOnlyAttribute`](http://msdn.microsoft.com/en-us/library/system.componentmodel.readonlyattribute.aspx) in the derived class.
```
class MyLabel : Label
{
[ReadOnly(true)]
public override Font Font
{
get { return new Font(FontFamily.GenericMonospace, 10); }
set { /* do nothing */ }
}
}
```
The [`ReadOnlyAttribute`](http://msdn.microsoft.com/en-us/library/system.componentmodel.readonlyattribute.aspx) will disable property editing in the VS.NET designer. | Instead of using the "ReadOnlyAttribute", try using the "[DefaultValueAttribute](http://msdn.microsoft.com/en-us/library/system.componentmodel.defaultvalueattribute.aspx)" instead. If I remember correctly, the designer shouldn't create code to set the property if the current value matches the value stored in the "DefaultValueAttribute". | How can "default" values in overridden WinForm controls be prevented? | [
"",
"c#",
"controls",
"default",
"subclass",
""
] |
My co-worker said that in a previous interview, he learned that foreach is faster in VB.Net than c#'s foreach. He was told that this was because both have different CLR implementation.
Coming from a C++ perspective, I'm curious on why this is and I was told that I need to read up on CLR first. Googling foreach and CLR doesn't help me understand.
Does anyone have a good explanation on why foreach is faster in VB.Net than in c#? Or was my co-worker misinformed? | There is no significant difference at the IL level between C# and VB.Net. There are some additional Nop instructions thrown in here and there between the two versions, but nothing that actually changes what is going on.
Here is the method: (in C#)
```
public void TestForEach()
{
List<string> items = new List<string> { "one", "two", "three" };
foreach (string item in items)
{
Debug.WriteLine(item);
}
}
```
And in VB.Net:
```
Public Sub TestForEach
Dim items As List(Of String) = New List(Of String)()
items.Add("one")
items.Add("two")
items.Add("three")
For Each item As string In items
Debug.WriteLine(item)
Next
End Sub
```
Here is the IL for the C# version:
```
.method public hidebysig instance void TestForEach() cil managed
{
.maxstack 2
.locals init (
[0] class [mscorlib]System.Collections.Generic.List`1<string> items,
[1] string item,
[2] class [mscorlib]System.Collections.Generic.List`1<string> <>g__initLocal3,
[3] valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<string> CS$5$0000,
[4] bool CS$4$0001)
L_0000: nop
L_0001: newobj instance void [mscorlib]System.Collections.Generic.List`1<string>::.ctor()
L_0006: stloc.2
L_0007: ldloc.2
L_0008: ldstr "one"
L_000d: callvirt instance void [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
L_0012: nop
L_0013: ldloc.2
L_0014: ldstr "two"
L_0019: callvirt instance void [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
L_001e: nop
L_001f: ldloc.2
L_0020: ldstr "three"
L_0025: callvirt instance void [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
L_002a: nop
L_002b: ldloc.2
L_002c: stloc.0
L_002d: nop
L_002e: ldloc.0
L_002f: callvirt instance valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<!0> [mscorlib]System.Collections.Generic.List`1<string>::GetEnumerator()
L_0034: stloc.3
L_0035: br.s L_0048
L_0037: ldloca.s CS$5$0000
L_0039: call instance !0 [mscorlib]System.Collections.Generic.List`1/Enumerator<string>::get_Current()
L_003e: stloc.1
L_003f: nop
L_0040: ldloc.1
L_0041: call void [System]System.Diagnostics.Debug::WriteLine(string)
L_0046: nop
L_0047: nop
L_0048: ldloca.s CS$5$0000
L_004a: call instance bool [mscorlib]System.Collections.Generic.List`1/Enumerator<string>::MoveNext()
L_004f: stloc.s CS$4$0001
L_0051: ldloc.s CS$4$0001
L_0053: brtrue.s L_0037
L_0055: leave.s L_0066
L_0057: ldloca.s CS$5$0000
L_0059: constrained [mscorlib]System.Collections.Generic.List`1/Enumerator<string>
L_005f: callvirt instance void [mscorlib]System.IDisposable::Dispose()
L_0064: nop
L_0065: endfinally
L_0066: nop
L_0067: ret
.try L_0035 to L_0057 finally handler L_0057 to L_0066
}
```
Here is the IL for the VB.Net version:
```
.method public instance void TestForEach() cil managed
{
.maxstack 2
.locals init (
[0] class [mscorlib]System.Collections.Generic.List`1<string> items,
[1] string item,
[2] valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<string> VB$t_struct$L0,
[3] bool VB$CG$t_bool$S0)
L_0000: nop
L_0001: newobj instance void [mscorlib]System.Collections.Generic.List`1<string>::.ctor()
L_0006: stloc.0
L_0007: ldloc.0
L_0008: ldstr "one"
L_000d: callvirt instance void [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
L_0012: nop
L_0013: ldloc.0
L_0014: ldstr "two"
L_0019: callvirt instance void [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
L_001e: nop
L_001f: ldloc.0
L_0020: ldstr "three"
L_0025: callvirt instance void [mscorlib]System.Collections.Generic.List`1<string>::Add(!0)
L_002a: nop
L_002b: nop
L_002c: ldloc.0
L_002d: callvirt instance valuetype [mscorlib]System.Collections.Generic.List`1/Enumerator<!0> [mscorlib]System.Collections.Generic.List`1<string>::GetEnumerator()
L_0032: stloc.2
L_0033: br.s L_0045
L_0035: ldloca.s VB$t_struct$L0
L_0037: call instance !0 [mscorlib]System.Collections.Generic.List`1/Enumerator<string>::get_Current()
L_003c: stloc.1
L_003d: ldloc.1
L_003e: call void [System]System.Diagnostics.Debug::WriteLine(string)
L_0043: nop
L_0044: nop
L_0045: ldloca.s VB$t_struct$L0
L_0047: call instance bool [mscorlib]System.Collections.Generic.List`1/Enumerator<string>::MoveNext()
L_004c: stloc.3
L_004d: ldloc.3
L_004e: brtrue.s L_0035
L_0050: nop
L_0051: leave.s L_0062
L_0053: ldloca.s VB$t_struct$L0
L_0055: constrained [mscorlib]System.Collections.Generic.List`1/Enumerator<string>
L_005b: callvirt instance void [mscorlib]System.IDisposable::Dispose()
L_0060: nop
L_0061: endfinally
L_0062: nop
L_0063: ret
.try L_002c to L_0053 finally handler L_0053 to L_0062
}
``` | I'm a little suspicious of this claim. The foreach construct works the same way against both languages, in that it gets the [IEnumerator](http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.aspx) from the managed object and calls MoveNext() on it. Whether the original code was written in VB.NET or c# should not matter, they both compile to the same thing.
In my test timings, the same foreach loop in VB.NET and c# were never more than ~1% apart for very long iterations.
c#:
```
L_0048: ldloca.s CS$5$0001
L_004a: call instance !0 [mscorlib]System.Collections.Generic.List`1/Enumerator<string>::get_Current()
L_004f: stloc.3
L_0050: nop
L_0051: ldloc.3
L_0052: call void [mscorlib]System.Console::WriteLine(string)
L_0057: nop
L_0058: nop
L_0059: ldloca.s CS$5$0001
L_005b: call instance bool [mscorlib]System.Collections.Generic.List`1/Enumerator<string>::MoveNext()
L_0060: stloc.s CS$4$0000
L_0062: ldloc.s CS$4$0000
L_0064: brtrue.s L_0048
```
VB.NET:
```
L_0043: ldloca.s VB$t_struct$L0
L_0045: call instance !0 [mscorlib]System.Collections.Generic.List`1/Enumerator<string>::get_Current()
L_004a: stloc.s item
L_004c: ldloc.s item
L_004e: call void [mscorlib]System.Console::WriteLine(string)
L_0053: nop
L_0054: nop
L_0055: ldloca.s VB$t_struct$L0
L_0057: call instance bool [mscorlib]System.Collections.Generic.List`1/Enumerator<string>::MoveNext()
L_005c: stloc.s VB$CG$t_bool$S0
L_005e: ldloc.s VB$CG$t_bool$S0
L_0060: brtrue.s L_0043
``` | Is the foreach in VB.NET faster than in c#? | [
"",
"c#",
".net",
"vb.net",
"clr",
"language-design",
""
] |
I don't know a better title, but I'll describe the problem.
A piece of hardware we use has the ability to display images.
It can display a black and white image with a resolution of 64 x 256.
The problem is the format of the image we have to send to the device.
It is not a standard bitmap format, but instead it is simply an array of
bytes representing each pixel of the image.
0 = black, 1 = white.
So if we had an image with the size: 4 x 4 the byte array might look something like:
1000 0100 0010 0001
And the image would look like:
[Bitmap http://www.mediafire.com/imgbnc.php/6ee6a28148d0170708cb10ec7ce6512e4g.jpg](http://www.mediafire.com/imgbnc.php/6ee6a28148d0170708cb10ec7ce6512e4g.jpg)
The problem is that we need to create this image by creating a monochrome bitmap
in C# and then convert it to the file format understood by the device.
For example, one might to display text on the device. In order to do so he would
have to create a bitmap and write text to it:
```
var bitmap = new Bitmap(256, 64);
using (var graphics = Graphics.FromImage(bitmap))
{
graphics.DrawString("Hello World", new Font("Courier", 10, FontStyle.Regular), new SolidBrush(Color.White), 1, 1);
}
```
There are 2 problems here:
1. The generated bitmap isn't monochrome
2. The generated bitmap has a different binary format
So I need a way to:
1. Generate a monochrome bitmap in .NET
2. Read the individual pixel colors for each pixel in the bitmap
I have found that you can set the pixel depth to 16, 24, or 32 bits, but haven't found monochrome and I have no idea how to read the pixel data.
Suggestions are welcome.
**UPDATE:** I cannot use Win32 PInvokes... has to be platform neutral!
**FOLLOW UP:** The following code works for me now. (Just in case anybody needs it)
```
private static byte[] GetLedBytes(Bitmap bitmap)
{
int threshold = 127;
int index = 0;
int dimensions = bitmap.Height * bitmap.Width;
BitArray bits = new BitArray(dimensions);
//Vertically
for (int y = 0; y < bitmap.Height; y++)
{
//Horizontally
for (int x = 0; x < bitmap.Width; x++)
{
Color c = bitmap.GetPixel(x, y);
int luminance = (int)(c.R * 0.3 + c.G * 0.59 + c.B * 0.11);
bits[index] = (luminance > threshold);
index++;
}
}
byte[] data = new byte[dimensions / 8];
bits.CopyTo(data, 0);
return data;
}
``` | I'd compute the luminance of each pixel a then compare it to some threshold value.
```
y=0.3*R+0.59G*G+0.11*B
```
Say the threshold value is 127:
```
const int threshold = 127;
Bitmap bm = { some source bitmap };
byte[,] buffer = new byte[64,256];
for(int y=0;y<bm.Height;y++)
{
for(int x=0;x<bm.Width;x++)
{
Color c=source.GetPixel(x,y);
int luminance = (int)(c.R*0.3 + c.G*0.59+ c.B*0.11);
buffer[x,y] = (luminance > 127) ? 1 : 0;
}
}
``` | I don't know C#. There are possibly many ways to do it. Here is a simple way.
1. Create a blank black bitmap image of size equal to your device requirement. Draw on it whatever you wish to draw like text, figures etc.
2. Now threshold the image i.e. set the pixel of image below an intensity value to zero else set it to. e.g. set all intensity values > 0 to 1.
3. Now convert to the format required by your device. Create a byte array of the size (64 \* 256)/8. Set the corresponding bits to 1 where the corresponding pixel values in earlier bitmap are 1, else reset them to 0.
Edit: Step 3. Use bitwise operators to set the bits. | Reading monochrome bitmap pixel colors | [
"",
"c#",
".net",
"graphics",
"drawing",
"bitmap",
""
] |
I just got a new quad core computer and noticed that nmake is only using 1 process.
I used to use make which had the switch -j4 for launching 4 processes. What is the nmake equivalent?
[edit]
Based on the information below I have been able to add a command to my qmake project file:
QMAKE\_CXXFLAGS += /MP
Which effectively did it for me. Many thanks. | According to [MSDN](http://msdn.microsoft.com/en-us/library/afyyse50(VS.71).aspx), there's no such option for `nmake`.
You can however make the compiler build multiple files in parallel by using the `/MP` option with the VC++ command line compiler and passing multiple files at the same time:
```
> cl /MP a.cpp b.cpp c.cpp
```
However note that most Makefiles don't call the compiler like this - they usual invoke the compiler separate for each individual source file, which would prevent the `/MP` option from doing anything useful. | Another generic, non-Qt-related way to tell `nmake` to use all the cores is to set environmental variable `CL` to `/MP`:
```
set CL=/MP
nmake
```
will use all the CPU cores. | How do I utilise all the cores for nmake? | [
"",
"c++",
"eclipse",
"qt",
"multicore",
"nmake",
""
] |
We're developing in C++ under Linux and about to set up automated tests. We intend to use a testing framework like CppUnit oder CxxTest. We're using Ant to build the software and we will also use it to run the tests.
As some tests are going to involve database access, we are looking for a tool or framework which facilitates the tasks of preparing and cleaning up test data in the database - just like DbUnit (a JUnit extension) in the Java world.
Another option may be to employ the actual DbUnit - a Java VM is available. Making use of DbUnit's Ant task seems to be most promising. Any related field reports are welcome! | As there seems to be no DbUnit-like tool for C++ development, we've built a little framework of our own. Basically it's an adaptor for calling actual DbUnit operations from within C/C++ testrunners. It makes use of the [Ant tasks](http://www.dbunit.org/anttask.html) provided by DbUnit.
We defined some macros like `TS_DB_INSERT(filename)` which call `system("ant -Ddb.dataset=filename db.insert")` and the like.
In this case, `db.insert` is an Ant target which executes a DbUnit task performing an INSERT operation on the database. The `filename` references an XML dataset containing the data to insert.
There's also an assertion macro which wraps a DbUnit `compare`.
The test case might look like this:
```
void testDatabaseStuff
{
TS_DB_INSERT("input.xml");
TestedClass::doSomething();
TS_DB_ASSERT("expected.xml");
}
``` | I would recommend [boost unit testing](http://www.boost.org/doc/libs/1_35_0/libs/test/doc/components/utf/index.html). You would probably have to use the setup and teardown to manually clean up the database. Of course, you could build your own C++ DbUnit in ODBC. IF you do let me know because I could use this as well! | DbUnit for C++? | [
"",
"c++",
"ant",
"dbunit",
"data-driven-tests",
""
] |
What is the difference between the JIT compiler and CLR? If you compile your code to il and CLR runs that code then what is the JIT doing? How has JIT compilation changed with the addition of generics to the CLR? | The JIT is one aspect of the CLR.
Specifically it is the part responsible for changing CIL (hereafter called IL) produced by the original language's compiler (csc.exe for Microsoft c# for example) into machine code native to the current processor (and architecture that it exposes in the current process, for example 32/64bit). If the assembly in question was ngen'd then the the JIT process is completely unnecessary and the CLR will run this code just fine without it.
Before a method is used which has not yet been converted from the intermediate representation it is the JIT's responsibility to convert it.
Exactly *when* the JIT will kick in is implementation specific, and subject to change. However the CLR design mandates that the JIT happens *before* the relevant code executes, JVMs in contrast would be free to interpret the code for a while while a separate thread creates a machine code representation.
The 'normal' CLR uses a [pre-JIT stub approach](http://codeidol.com/csharp/net-framework/Inside-the-CLR/Just-In-Time-(JIT)-Compilation/) where by methods are JIT compiled only as they are used. This involves having the initial native method stub be an indirection to instruct the JIT to compile the method then modify the original call to skip past the initial stub. The current compact edition instead compiles all methods on a type when it is loaded.
To address the addition of Generics.
This was the last major change to the IL specification and JIT in terms of its semantics as opposed to its internal implementation details.
Several new IL instructions were added, and more meta data options were provided for instrumenting types and members.
Constraints were added at the IL level as well.
When the JIT compiles a method which has generic arguments (either explicitly or implicitly through the containing class) it may set up different code paths (machine code instructions) for each type used. In practice the JIT uses a shared implementation for all reference types since variables for these will exhibit the same semantics and occupy the same space (IntPtr.Size).
Each value type will get specific code generated for it, dealing with the reduced / increased size of the variables on the stack/heap is a major reason for this. Also by emitting the constrained opcode before method calls many invocations on non reference types need not box the value to call the method (this optimization is used in non generic cases as well). This also allows the default`<T>` behaviour to be correctly handled and for comparisons to null to be stripped out as no ops (always false) when a non Nullable value type is used.
If an attempt is made at runtime to create an instance of a generic type via reflection then the type parameters will be validated by the runtime to ensure they pass any constraints. This does not directly affect the JIT unless this is used within the type system (unlikely though possible). | You compile your code to IL which gets executed and compiled to machine code during runtime, this is what's called JIT.
**Edit**, to flesh out the answer some more (still overly simplified):
When you compile your C# code in visual studio it gets turned into IL that the CLR understands, the IL is the same for all languages running on top of the CLR (which is what enables the .NET runtime to use several languages and inter-op between them easily).
During runtime the IL is interpreted into machine code (which is specific to the architecture you're on) and then it's executed. This process is called Just In Time compilation or JIT for short. Only the IL that is needed is transformed into machine code (and only once, it's "cached" once it's compiled into machinecode), **just in time** before it's executed, hence the name JIT.
This is what it would look like for C#
> C# Code `>` C# Compiler `>` IL `>` .NET Runtime `>` JIT Compiler `>` Machinecode `>` Execution
And this is what it would look like for VB
> VB Code `>` VB Compiler `>` IL `>` .NET Runtime `>` JIT Compiler `>` Machinecode `>` Execution
And as you can see only the two first steps are unique to each language, and everything after it's been turned into IL is the same which is, as I said before, the reason you can run several different languages on top of .NET | CLR vs JIT | [
"",
"c#",
"compiler-construction",
"clr",
"jit",
""
] |
Is there a better way to get the Property name when passed in via a lambda expression?
Here is what i currently have.
eg.
```
GetSortingInfo<User>(u => u.UserId);
```
It worked by casting it as a memberexpression only when the property was a string. because not all properties are strings i had to use object but then it would return a unaryexpression for those.
```
public static RouteValueDictionary GetInfo<T>(this HtmlHelper html,
Expression<Func<T, object>> action) where T : class
{
var expression = GetMemberInfo(action);
string name = expression.Member.Name;
return GetInfo(html, name);
}
private static MemberExpression GetMemberInfo(Expression method)
{
LambdaExpression lambda = method as LambdaExpression;
if (lambda == null)
throw new ArgumentNullException("method");
MemberExpression memberExpr = null;
if (lambda.Body.NodeType == ExpressionType.Convert)
{
memberExpr =
((UnaryExpression)lambda.Body).Operand as MemberExpression;
}
else if (lambda.Body.NodeType == ExpressionType.MemberAccess)
{
memberExpr = lambda.Body as MemberExpression;
}
if (memberExpr == null)
throw new ArgumentException("method");
return memberExpr;
}
``` | I found another way you can do it was to have the source and property strongly typed and explicitly infer the input for the lambda. Not sure if that is correct terminology but here is the result.
```
public static RouteValueDictionary GetInfo<T,P>(this HtmlHelper html, Expression<Func<T, P>> action) where T : class
{
var expression = (MemberExpression)action.Body;
string name = expression.Member.Name;
return GetInfo(html, name);
}
```
And then call it like so.
```
GetInfo((User u) => u.UserId);
```
and voila it works. | I recently did a very similar thing to make a type safe OnPropertyChanged method.
Here's a method that'll return the PropertyInfo object for the expression. It throws an exception if the expression is not a property.
```
public static PropertyInfo GetPropertyInfo<TSource, TProperty>(
TSource source,
Expression<Func<TSource, TProperty>> propertyLambda)
{
if (propertyLambda.Body is not MemberExpression member)
{
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
propertyLambda.ToString()));
}
if (member.Member is not PropertyInfo propInfo)
{
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
propertyLambda.ToString()));
}
Type type = typeof(TSource);
if (propInfo.ReflectedType != null && type != propInfo.ReflectedType && !type.IsSubclassOf(propInfo.ReflectedType))
{
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a property that is not from type {1}.",
propertyLambda.ToString(),
type));
}
return propInfo;
}
```
The `source` parameter is used so the compiler can do type inference on the method call. You can do the following
```
var propertyInfo = GetPropertyInfo(someUserObject, u => u.UserID);
``` | Retrieving Property name from lambda expression | [
"",
"c#",
"linq",
"lambda",
"expression-trees",
""
] |
Whats the best way to read Xml from either an XmlDocument or a String into a DataGrid?
Does the xml have to be in a particular format?
Do I have to use A DataSet as an intermediary?
I'm working on a client that consumes Xml sent over from a Server which is being developed by one of my colleagues, I can get him to change the format of the Xml to match what a DataGrid requires. | We have a partial answer to get the data into a dataset but it reads it in as a set of tables with relational links.
```
DataSet ds = new DataSet();
XmlTextReader xmlreader = new XmlTextReader(xmlSource, XmlNodeType.Document, null);
ds.ReadXml(xmlreader);
``` | It depends on which version of .NET you are running on. If you can use Linq2Xml then it is easy. Just create an XDocument and select the child nodes as a list of an anonymous type.
If you can't use Linq2Xml then you have a few other options. Using a DataSet is one, this can work well, but it depends on the xml you are receiving. An other option is to create a class that describes the entity you will read from the xml and step through the xml nodes manually. A third option would be to use Xml serialization and deserialize the xml into a list of objects. This can work well as long as you have classes that are setup for it.
The easiest option will be either to create an XDocument or to create a DataSet as you suggest. | Reading Xml into a datagrid in C# | [
"",
"c#",
"xml",
"datagrid",
""
] |
I have an application to build in Java, and I've got some questions to put.
Is there some way to know if one URL of a webpage is real? The user enters the URL and I have to test if it's real, or not.
How can I konw if one webpage has changes since one date, or what is the date of the last update?
In java how can I put an application running on pc boot, the application must run since the user turns on the computer. | I'm not sure what kind of application you want to build. I'll assume it's a desktop application. In order to check if a URL exists, you should make a **HTTP HEAD Request**, and parse the results. HEAD can be used to check if the page has been modified. In order for an application to start when the PC boots, you have to add a registry entry under Windows; this process is explained [here](http://ask-leo.com/auto_start_how_do_i_run_a_program_automatically_when_windows_starts.html) | To check whether a url is valid you could try using a regular expression ([regex for urls](http://regexlib.com/Search.aspx?k=URL)).
To know if a webpage has changed you can take a look at the http headers ([reading http headers in java](http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Request-Headers.html)).
You can't make the program startup automatically on boot, the user must do that. However, you can write code to help the user set the program as startup app; this however depends on the operating system. | Multiple questions in Java (Validating URLs, adding applications to startup, etc.) | [
"",
"java",
""
] |
Is there any way to add `Field` (or `FieldInfo`, maybe this is the same) to a class at runtime? | You can't alter a class definition at runtime. However, you can create a new class that inherits from the original class (if it's not `sealed`) and declares the field. You can do this by emitting the appropriate IL code using `System.Reflection.Emit`. | No, C# doesn't allow [monkey-patching](http://en.wikipedia.org/wiki/Monkey_patch).
You can generate *new* classes using either CodeDOM or Reflection.Emit, but you can't modify existing ones. | How can I dynamically add a field to a class in C# | [
"",
"c#",
"reflection",
""
] |
I want to add two numbers together but when one of those numbers is null then the result is null. Is there a way around this. I could simply do it in the code but I would rather have it done in the query. This is a oracle database.
**The table structure**
```
hours_t
type craft regular overtime
A 1 5 0
A 1 3 1
B 2 9 <null>
B 1 4 4
```
**The query**
```
select type, craft, sum(regular + overtime) as total_hours
from hours_t
group by type, craft
order by type, craft
```
**The unwanted results**
```
type craft total_hours
A 1 9
B 1 8
B 2 <null>
```
**The wanted results**
```
type craft total_hours
A 1 9
B 1 8
B 2 9
``` | ```
select type, craft, sum(nvl(regular,0) + nvl(overtime,0)) as total_hours
from hours_t
group by type, craft
order by type, craft
``` | NVL(value, default) is the function you are looking for.
```
select type, craft, sum(NVL(regular, 0) + NVL(overtime, 0) ) as total_hours
from hours_t
group by type, craft
order by type, craft
```
Oracle have 5 NULL-related functions:
1. NVL
2. NVL2
3. COALESCE
4. NULLIF
5. LNNVL
[**NVL**](http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions105.htm#i91798):
```
NVL(expr1, expr2)
```
> NVL lets you replace null (returned as a blank) with a string in the results of a query. If expr1 is null, then NVL returns expr2. If expr1 is not null, then NVL returns expr1.
[**NVL2**](http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions106.htm#i91806) :
```
NVL2(expr1, expr2, expr3)
```
> NVL2 lets you determine the value returned by a query based on whether a specified expression is null or not null. If expr1 is not null, then NVL2 returns expr2. If expr1 is null, then NVL2 returns expr3.
[**COALESCE**](http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions023.htm#i1001341)
```
COALESCE(expr1, expr2, ...)
```
> COALESCE returns the first non-null expr in the expression list. At least one expr must not be the literal NULL. If all occurrences of expr evaluate to null, then the function returns null.
[**NULLIF**](http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions102.htm#i1001340)
```
NULLIF(expr1, expr2)
```
> NULLIF compares expr1 and expr2. If they are equal, then the function returns null. If they are not equal, then the function returns expr1. You cannot specify the literal NULL for expr1.
[**LNNVL**](http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions078.htm#i1479295)
```
LNNVL(condition)
```
> LNNVL provides a concise way to evaluate a condition when one or both operands of the condition may be null.
More info on [Oracle SQL Functions](http://download.oracle.com/docs/cd/B19306_01/server.102/b14200/functions001.htm) | Sum columns with null values in oracle | [
"",
"sql",
"oracle",
""
] |
Context: I was going to build app using mod\_rewrite (front page loading child pages), but got stuck on loading session\_enabled pages from the front controller page.
Problem: The problem is that I use session\_start() call twise, PHP page stops responding. Which is strange, the session\_start function is harmless and they are called on different pages.
I've narrowed down the problem to this sample:
child.php file:
parent.php file:
Call to parent.php will make browser load infinitely. As soon as you comment one of session\_start() calls - it loads instantly.
What is the source of the problem?
I badly need session-enabled pages.
PS I can work it around by including pages, but they rely on URL params, I would like to avoid fixing them for sake of some kind of parameter proxies. | Besides that only one session can be used at a time. You need to call the [`session_regenerate_id` function](http://docs.php.net/session_regenerate_id) to generate a new ID:
```
if (session_id() != '') {
session_write_close();
}
session_start();
session_regenerate_id();
```
Otherwise the parent’s session ID would also be used for the child’s session. | You need to call `session_write_close()` once you no longer need to write to the session. Currently as both your scripts have the session open for their entire duration, you will only be able to have one running at a time.
From [the manua](http://uk.php.net/session_write_close)l:
> Session data is usually stored after
> your script terminated without the
> need to call `session_write_close()`,
> but as session data is locked to
> prevent concurrent writes only one
> script may operate on a session at any
> time. When using framesets together
> with sessions you will experience the
> frames loading one by one due to this
> locking. You can reduce the time
> needed to load all the frames by
> ending the session as soon as all
> changes to session variables are done. | two session_starts() hang PHP app | [
"",
"php",
"file",
"session",
"front-controller",
""
] |
I need to build a GWT application that will be called by an external application with specific URL parameters.
For example:
<http://www.somehost.com/com.app.client.Order.html?orderId=99999>.
How do I capture the orderId parameter inside the GWT application? | Try,
```
String value = com.google.gwt.user.client.Window.Location.getParameter("orderId");
// parse the value to int
```
P.S. GWT can invoke native javascript which means if javascript can do the stuff, GWT can do it too; e.g. in GWT, you can write
```
public static native void alert(String msg)
/*-{
$wnd.alert("Hey I am javascript");
}-*/;
```
In this case, you can even use existing javascript lib to extract param's value in the querystring. | GWT has a facility to get params from the URL:
```
String value = Window.Location.getParameter("param");
```
Make sure your URLs are in the form of:
<http://app.com/?param=value#place> instead of <http://app.com/#place¶m=value>
In order to get all params in a map, use:
```
Map<String, List<String>> map = Window.Location.getParameterMap();
``` | GWT: Capturing URL parameters in GET request | [
"",
"java",
"gwt",
""
] |
I've seen this in a few pieces of code and I didn't want to "assume" it was unimportant but this is a copy of the Google Analytics code:
```
<script type="text/javascript">
var gaJsHost = (("https:" == document.location.protocol) ? "https://ssl." : "http://www.");
document.write(unescape("%3Cscript src='" + gaJsHost + "google-analytics.com/ga.js' type='text/javascript'%3E%3C/script%3E"));
</script>
<script type="text/javascript">
try {
var pageTracker = _gat._getTracker("UA-xxxxxx");
pageTracker._trackPageview();
} catch(err) {}
</script>
```
You'll notice there are two open / close script tags. Is there any reason why encapsulating the code bits in two different script tags is beneficial? My first reaction would be simply to remove the redundancy. | The first block writes a `<script>` tag to the page. I think if the code was all in one block there would be no guarantee the written `<script>` would be loaded before the second part of the code executed.
By using two blocks, the written `<script>` will load (which contains the `_gat` object) before the second block executes. | I guess the two script blocks were created by different source modules (classes/objects/whatever). | Any value in double script tags? | [
"",
"javascript",
"html",
""
] |
What is the best way to display underlined text and output the result as image with GD or any other library? | You can try using the Unicode underline combining character `U+0332`.
```
<?php
// Set the content-type
header('Content-type: image/png');
// Create the image
$im = imagecreatetruecolor(400, 30);
// Create some colors
$white = imagecolorallocate($im, 255, 255, 255);
$black = imagecolorallocate($im, 0, 0, 0);
imagefilledrectangle($im, 0, 0, 399, 29, $white);
// The text to draw
$text = "̲U̲d̲e̲r̲l̲i̲n̲e";
// Replace path by your own font path
$font = 'arial.ttf';
// Add the text
imagettftext($im, 20, 0, 10, 20, $black, $font, $text);
// Using imagepng() results in clearer text compared with imagejpeg()
imagepng($im);
imagedestroy($im);
?>
``` | There are lots of FREE PHP CAPTCHA out there that come with a lot of customization, download one and see what exactly happens behind the scene. Also have a look at this [link](http://www.thesitewizard.com/php/create-image.shtml)
HTH | Outputting image with underlined text using php GD library | [
"",
"php",
"gd",
""
] |
I'm possibly teaching an **undergraduate PHP/MySQL course** in the Fall and was wondering if anyone has any recommendations for good textbooks.
The books have to be geared towards a **beginner/medium level** (I'm assuming/hoping my students will have C++ and MsSQL classes prior to mine).
Topics I want to cover in **PHP:**
* Variables/Constants
* Conditionals
* Loops/Loop Control
* Functions
+ Strings
+ Arrays
+ Dates
+ Custom
* Form Data
* Session/Cookie/Server variables
* MySQL integration
+ Query/Error
+ Prepared Statements
+ MySQLi Class
In **MySQL:**
* Schema/Users/Tables/Columns/Rows
* Primary/Foreign/Constraints
* Data Types
* Queries
+ Select/Update/Insert/Delete/Truncate
+ Limit/Order By/Group By
Possibly deal with:
* Stored Procedures/Triggers
* Image Manipulation/Custom Classes | Welling & Thomson's *PHP and MySQL Web Development* is the gold standard:
[http://www.amazon.com/PHP-MySQL-Development-Developers-Library/dp/0672329166/ref=pd\_bbs\_sr\_1?ie=UTF8&s=books&qid=1236994701&sr=8-1](https://rads.stackoverflow.com/amzn/click/com/0672329166) | I don't know anyone who learned PHP from a book, just online tutorials or the PHP manual. I would say look on Amazon to find a book that covers the topics you want in your course.
Maybe like this. [http://www.amazon.com/Beginning-PHP-MySQL-Novice-Professional/dp/1590598628/ref=pd\_bbs\_3?ie=UTF8&s=books&qid=1236970221&sr=8-3](https://rads.stackoverflow.com/amzn/click/com/1590598628) | What PHP/MySQL book would be good as a textbook? | [
"",
"php",
"mysql",
""
] |
I have a StringUtilities.cs file in the CommonFunctions Project that holds a UppercaseFirst function that Uppercases the first word in a string. Currently in the .aspx.cs in a separate Project (in the same Solution) that is utilizing this function is called using **MyProject.CommonFunctions.StringUtilities.UppercaseFirst("hello world");**
Is it possible to shorten it to just **UppercaseFirst("hello world");** ? Readability will be so much better.
StringUtilities.cs in the CommonFunctions Project:
```
namespace MyProject.CommonFunctions
{
public class StringUtilities
{
public static string UppercaseFirst(string s)
{//blah code}
}
}
```
Default.aspx.cs
```
using MyProject.CommonFunctions;
...
protected void Page_Load(object sender, EventArgs e)
{
MyProject.CommonFunctions.StringUtilities.UppercaseFirst("hello world");
}
``` | You can't cut it all the way down to just the method name, but given that you've already got the `using MyProject.CommonFunction;` line in place, you could shorten it to:
```
StringUtilities.UppercaseFirst("hello world");
``` | If you're using c# 3.0 (.NET 3.5) you can use extension methods:
```
namespace MyProject.CommonFunctions
{
public static class StringUtilities
{
public static string UppercaseFirst(this string s)
{//blah code}
}
}
```
Once you set your usings in appropriate file you can then go:
```
using MyProject.CommonFunctions;
...
protected void Page_Load(object sender, EventArgs e)
{
"hello world".UppercaseFirst();
}
``` | Minimalizing namespaces for custom functions | [
"",
"c#",
"asp.net",
""
] |
I want to experiment/play around with non-relational databases, it'd be best if the solution was:
* portable, meaning it doesn't require an installation. ideally just copy-pasting the directory to someplace would make it work. I don't mind if it requires editing some configuration files or running a configuration tool for first time usage.
* accessible from python
* works on both windows and linux
What can you recommend for me?
Essentially, I would like to be able to install this system on a shared linux server where I have little user privileges. | I recommend you consider [BerkelyDB](http://en.wikipedia.org/wiki/Berkeley_DB) **with awareness of the licensing issues.**
I am getting very tired of people recommending BerkleyDB without qualification - you can only distribute BDB systems under GPL or some unknown and not publicly visible licensing fee from Oracle.
For "local" playing around where it is not in use by external parties, it's probably a good idea. Just be aware that there is a license waiting to bite you.
This is also a reminder that it is a good idea when asking for technology recommendations to say whether or not GPL is acceptable.
From [my own question](https://stackoverflow.com/questions/525065/which-embedded-database-capable-of-100-million-records-has-the-best-c-api) about a portable C API database, whilst a range of other products were suggested, none of the embedded ones have Python bindings. | [Metakit](http://www.equi4.com/metakit/) is an interesting non-relational embedded database that supports Python.
Installation requires just copying a single shared library and .py file. It works on Windows, Linux and Mac and is open-source (MIT licensed). | portable non-relational database | [
"",
"python",
"non-relational-database",
"portable-database",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.