问:
Directly modifying superglobals
I've seen people (who generally write good code) directly alter the $_POST array with code like this:

```<code>// Add some value that wasn't actually posted
$_POST['last_activity'] = time();

// Alter an existing post value
$_POST['name'] = trim($_POST['name']);

// Our pretend function
// Pass the entire $_POST array as data to work with in the function
// The function update_record() will read only the values we actually need
update_record($_POST);

// ...That sure was easier than creating a new array
//  with only the $_POST values we actually need.
</code>```

It makes sense that update_record() should not access $_POST directly, so we can pass other arrays of data to it for instance, but surely this is lazy, bad design, or possibly just wrong? However, we are still passing a valid array to update_record(), so why create a new one?

This is not the point of the question, just an example of usage. However, I have heard plenty of people say that this should not be done with $_REQUEST data, and it's bad practice. But why? Looks harmless enough.

Examples:

Setting a default $_GET (or post) value that doesn't really exist

Adding $_POST values that weren't actually posted after a form submission

Directly sanitizing or filtering the $_GET array values or keys very early in the script (fallback sanitation... why not?)

Setting a $_POST value manually before form submission to populate an input with a default value (when the input reads $_POST for it's default value; I have done this)

Making up your own $_SERVER values? Sure, hey why not?

How about the others, like $_COOKIE and $_SESSION? Of course we have to modify those directly right? Then why not the others?

Should direct modification of superglobals never be done, or is it OK to do in some instances?

答:
After initially answering this question by saying there should be no reason to modify superglobals, I'm editing this answer with an example of a time when I've decided to.

I'm currently working on a URL rewrite database table whereby the request column directs the user to its corresponding target column.

For instance, a request might be blog/title-here and its target might be blog.php?id=1.

Since blog.php is expecting $_GET variables, and I don't want to change the header("Location:"), I'm left doing something like this:

```<code>$uri    = explode('?', $uri_request)[0];
$params = explode('?', $uri_request)[1];
parse_str($params, $_GET);
</code>```

This creates a $_GET array containing the intended parameters passed by the target column.

Ultimately, I would strongly advise against modifying superglobals unless you absolutely have to.

OwnerDisplayName: Wesley Murch

Title: Directly modifying superglobals

Body:
After initially answering this question by saying there should be no reason to modify superglobals, I'm editing this answer with an example of a time when I've decided to.

I'm currently working on a URL rewrite database table whereby the request column directs the user to its corresponding target column.

For instance, a request might be blog/title-here and its target might be blog.php?id=1.

Since blog.php is expecting $_GET variables, and I don't want to change the header("Location:"), I'm left doing something like this:

$uri    = explode('?', $uri_request)[0];
$params = explode('?', $uri_request)[1];
parse_str($params, $_GET);

This creates a $_GET array containing the intended parameters passed by the target column.

Ultimately, I would strongly advise against modifying superglobals unless you absolutely have to.


问:
Data retrieval and indexing
I have around 800,000 rows of data stored in the boost shared memory from the database. The data are in the form:

```<code>Id        Color        Length          Size

1        1                 2            4
2        3                 4            5
3        2                 2            0
4        1                 2            4......and so on
</code>```

The Colors can be the value from 1-12 the length 1-4 and the size 1-5. The Id,Length,Color,Size are stored in seperate vector of 800,000 size in the shared memory. So there is Id vector for Id, Color vector for Color and so on.

I want to filter the data before I perform some computation. So I want data for which Color is 1 and length is 2 and Size 4 i.e row 1 and 4 in above case. Is there any efficient way to filter the data without using for loop and going through all the 800,000 images and checking the condition?

Right now I am just using mysql statement to get the Ids of the data which satisify the condition.

```<code>"select Id from features_table where Color=1 and Length=2 and Size =4"
</code>```

But is there a faster way to do this? Or should I stick to this method? I am looking for a faster method so I am not sure whether fetching the Ids from the database will increase the execution time of the algorithm.

What are the other options that I can consider in this case? I read about Hash table, B-Tree, Binary Search tree and I am confused which is suitable for this case. Will kd-tree be helpful in this case? Because many images may have the same combination of color,length and size. I am not sure if kd-tree is the right thing to do. I read about FLANN in opencv used for kd-tree. Is there any example or resources which may be helpful in this case? Or are there  any built in c++ libraries?

答:
You've a lot of data duplication there, as the number of possible combinations of Color, Length and Size values is way too smaller than the number of rows.

A better alternative is storing a set of row indexes for each possible  tuple:

```<code>struct Rows
{
    std::tuple<Color, Length, Size> properties;
    std::vector<int> rowids;
} ;
</code>```

This way, queries are straightforward.

If the number of possible tuples is high enough, then it'd be worth to set indexes in the form of row set hashes, one hash per property: std::map<Color, Rows *> and so on.

ContentLicense: CC BY-SA 3.0

Title: Data retrieval and indexing

Body:
You've a lot of data duplication there, as the number of possible combinations of Color, Length and Size values is way too smaller than the number of rows.

A better alternative is storing a set of row indexes for each possible  tuple:

struct Rows
{
    std::tuple<Color, Length, Size> properties;
    std::vector<int> rowids;
} ;

This way, queries are straightforward.

If the number of possible tuples is high enough, then it'd be worth to set indexes in the form of row set hashes, one hash per property: std::map<Color, Rows *> and so on.


问:
Does limiting commitment in Scrum lead to complacency?
In my organization Scrum teams almost never finish all of their stories 100%. I suggested that we commit to fewer stories each Sprint, but the R&D manager says if we do that people will still not complete the work, but will just do less of it thus slowing down development. He says there is a Student Syndrome at work here.

What is your take on that?

答:
Your manager needs to understand that Student Syndrome / Parkinson's Law becomes a significantly larger problem when there is zero hope of hitting targets. Suddenly the time available for a task's completion is infinite. As an old colleague of mine used to put it, "Deadlines are just things that pass by here. We miss them, they get moved back, we miss them again."

And that was entirely a result of unreasonable deadlines in the first place. These people weren't naturally lazy, they just saw no hope of hitting a target and no consequence of not hitting it, so why worry about it?

My point being that your manager might well be right. But he needs to understand that he's creating the problem.

When a team does sprint planning well, they start working as a team to hit their deadlines. Any one person doesn't pull their weight, they fail as a team. If that happens continually, the team deals with that person.

There is a possibility that you will cut the velocity too much and achieve less than you might have. But you will have succeeded. Feelings in the team will be positive. Someone is likely to say "Honestly, I think we can achieve a couple more points next sprint."

Eventually, you'll find your balance point and start predicting correctly the amount of work you can actually achieve in an iteration.


问:
It is bad practice to hard couple logging interface/implementation with business model classes?
Should we avoid using logging in business model classes and try to move logging to service/controller classes?

In for example java context, logging in model classes will hard couple the code with dependencies on slf4j or commons-logging etc.

答:
One way of keeping your BL decoupled from the various logging libraries is to create a logging interface in one of your core libraries, which will be referenced by the BL. You can then have the concrete implementations in another library and inject them in the BL. This way your BL will remain oblivious to your logging library of choice.

As for logging in business model, it really depends on what you want to log. If it's just exceptions, you can let them bubble up and catch/log them in the upper layers. If you want to log more than exceptions, you'll have to add the logging code inside your BL classes, which isn't that bad. After all, logging is a cross-cutting concern and you're supposed to scatter it across all the layers of your application.

Long story short: no, it is not a bad practice.


问:
Are HSQLDB unit tests an anti pattern?
HSQLDB is great. It (also) has an embedded mode (no dedicated server needed), which allows for quick prototyping of stuff like Proof of Concepts, and it can also be great in production-ready applications, as a quick and simple storage of various data.

However, at least 90% of the projects I've worked on in the past years, if they deal in any way with an SQL database, they will unavoidably have unit tests that use an embedded HSQLDB.

Sure-enough, these projects (which use the standard Maven structure most of the times), have a ton of "unit tests" (or, at least, some kind of tests, but which are located in the "unit-test" area of the project (like "src/test/java")) which use one or more embedded instances of HSQLDB in order to do some CRUD operations and check the results.

My question is: is this an anti-pattern? Does the fact that HSQLDB is easy to integrate and the embedded server is very lightweight make it so that it can be overlooked as "mock-up" of an actual database, when it shouldn't be the case? Shouldn't such tests be treated more like integration-tests (since each of them is composed of "something" AND that "something"'s integration with a database server)? Or am I missing something in the "unit test" definition, and we can infact say that using HSQLDB like this simply adheres to the "mock the dependencies, and test only the unit" part of the "unit test" definition?

答:
Use the same database for (unit-)tests as you are using in your production environment.

The reason is simple: Databases behave differently. Each database has their own proprietary functions. Even if you use an ORM layer for database access, your database can behave differently, also performance-wise.

Of course, the advantage of an embedded database for unit tests is that you do not have to configure anything. But installing a database on every developer machine and configure it to be used for unit tests is not that hard.

I had the same situation in a project some time ago. We used JDBC to run SQL-statements on the database. When we decided to write tests for our application, we used an embedded database. That lead to situations where some bugs could not be reproduced with unit tests, and some parts of the application could not be tested because the embedded database did not support the functions of our production database. So every developer installed the same database we also used in the production environment on the PC to run the tests, which worked much better.

Title: Are HSQLDB unit tests an anti pattern?


问:
Good idea to put bug numbers in a comment in the beginning of the source file?
Is it a good practice to put bug numbers in the file itself inside a header comment?

The comments would look something like this:

```<code> MODIFIED    (MM/DD/YY)
 abc 01/21/14 - Bug 17452317 - npe in drill across in dashboard edit mode

 cde 01/17/14 - Bug 2314558  - some other error description
</code>```

It seems helpful, but is it considered bad practice?

答:
I definitely wouldn't put such information at the start of the file - usually such a thing belongs into a ticket system.

There are however some cases where references into the ticket system and / or other documentation make sense. For instance, if there is a lengthy explanation of the design, or description of alternatives. Or information how to test things, or explanations why it was done exactly that way.
If that's short, it belongs into the file itself; if it is long and / or is about a larger picture, you'll probably want to put it somewhere else and reference it.


答:
In my organization Scrum teams almost never finish all of their stories 100%.
  I suggested that we commit to fewer stories each Sprint, but the R&D manager says if we do that people will still not complete the work, but will just do less of it thus slowing down development.
  He says there is a Student Syndrome at work here.

From my limited experience with [what poses for] Agile, I'm not surprised.
Everything I've read about Agile suggests that everybody needs far more organised than in other development technique but, like you, I'm seeing little, if any, evidence of it.

Estimating Story Points is not an exact science, especially in "cutting-edge" areas like R&D.  It could easily be that your Developers are mis-estimating their Story Points (IME, usually over-estimating their own abilities) or it might be that there's some "target" number of Points that they're supposed to produce in each Sprint (IMHO, an utterly flawed way to manage, which brings me to ...).

Your manager needs to be investigating this and finding out what's not working.  It's their responsibility to get stuff delivered to the clients (or it ought to be), and so their "neck on the block" when the users start complaining.

[cynicism]Of course it won't be, because they have all the necessary training/ skills to make sure none of the blame sticks to them. [/cynicism]

And insulting their workers, branding them with any kind of "syndrome", is never acceptable behaviour - it just shows management's lack of commitment to the Team and their desire to "distance" themselves from it.

Development is being slowed down either way, but doing the job slowly and more conscientiously (i.e. actually making stuff work) is far, far better than simply not delivering anything at all.

Title: Does limiting commitment in Scrum lead to complacency?

Body:
In my organization Scrum teams almost never finish all of their stories 100%. I suggested that we commit to fewer stories each Sprint, but the R&D manager says if we do that people will still not complete the work, but will just do less of it thus slowing down development. He says there is a Student Syndrome at work here.

What is your take on that?


问:
High-Level SQL Interoperability
In a server -> client scenario, wouldn't it be simpler and faster to grant a public user access to a Stored Procedure rather than using web services (XML, REST, SOAP, etc) and other interoperable solutions?

That way you could connect directly to a database and get relevant content and do what you will with it in the same way across all languages and systems?

答:
I think the key is right in your question:

In a server -> client scenario, wouldn't it be simpler and faster to
  grant a public user access to a Stored Procedure rather than using web
  services (XML, REST, SOAP, etc) and other interoperable solutions?

As any form of service provider, there are tradeoffs you make, one of these is often trading the flexibility of direct-access to something that power-user types appreciate, with the ease-of-use of a more interoperable solution.

Security Concerns

So let's start off by saying there are security concerns. They may not be so much the SQL server itself, but rather the risks inherent everytime you expose a computer to the internet. The benefit of doing this with your web server instead of your database server is one of risk mitigation.

The train of thought generally goes like this: If your OS has a security flaw found, and your database server is exposed to the internet, someone may take advantage of that flaw to get admin on that exposed machine - voila All your data are belong to them. So what's usually done is web-servers that don't have any data and have hardly any permissions on the DB are exposed to the internet. If someone get's root on these, they should ideally only have permissions to do what the website can do so the abuser has really gained nothing.

Ideal World (it still doesn't make sense)

Security concerns are (probably) the number 1 reason people don't do this in practice, but we'll assume an ideal world where an exposed database server doesn't have security concerns for a moment.

In this ideal world, what happens when you have some data you want exposed and you create and expose the stored procedure? Who have you just exposed this data to? The entire internet? Sort of. The reality is you just exposed this data to everyone with the skills, tools, and time to create a connection and access your stored procedure.

Now let's ask a slightly different version of the above question: what happens when you have some data you want exposed - who do you want it exposed to? If your main target is to expose that data to the internet at large, you'll want to create a web-page that displays that data. At this point, you've created the interoperable solution already, so now what value does the direct stored procedure access have? Same value as before I guess, except those power users would probably just use your interoperable interface instead of the SQL server one because it's easier.

Let's take another approach to the above thought - What if your main target you want to expose the data to is third party developers? Great, they probably have the skill, time, and tools to access your stored procedure directly! But wait a minute, if you have fixed set of consumers of your dataset, do you really need to expose the server to the entire internet? Not really, it's going to simplify things from a security and auditing perspective a lot if you create secure tunnels for your 3rd party consumers which puts them in an effective intranet with your DB - an intranet is exactly how people normally access DBs anyways so now you're back to the typical scenario.

Conclusion

So as I hope I've illustrated with some logical thought experiments and a bit of leading the witness, we can agree the times where such a scenario actually provides value are pretty slim. I suppose you could do it, and there may even be an edge case you hit where it actually makes sense. However as soon as you make that logical leap, you also have to recognize there are security risks. In conclusion: why bother?

Title: High-Level SQL Interoperability


答:
You have exactly 240 unique values for colour, length and size. If the id is strictly ascending as in your example, you don't need to store it and the data could conveniently be packed in a single short int. An array of 800,000 shorts will take 1.6 MB of memory and could be brute force searched in under 1 millisecond. Do you need faster than this?

If the id has to be stored, you need 27 bits but a short and an int may be more convenient. Still only 4.8 MB of memory, still very fast to search.

If you know in advance the searches you want to make then you can build indexes to make the searches even faster. You could use the 240 unique values as the key and the id as the data, with about 3333 ids in each bucket.

Hash table: Yes. The above could be implemented with an unordered multimap, such as the one in the standard library. A custom solution might be faster, however.

B-trees and binary search are for sorted data. You've not indicated this as a requirement.

Kd-trees are for multi-dimensional sorted data, excellent for nearest neighbour searches. Again, does not seem to match your needs.

Title: Data retrieval and indexing

Body:
I have around 800,000 rows of data stored in the boost shared memory from the database. The data are in the form:

```<code>Id        Color        Length          Size

1        1                 2            4
2        3                 4            5
3        2                 2            0
4        1                 2            4......and so on
</code>```

The Colors can be the value from 1-12 the length 1-4 and the size 1-5. The Id,Length,Color,Size are stored in seperate vector of 800,000 size in the shared memory. So there is Id vector for Id, Color vector for Color and so on.

I want to filter the data before I perform some computation. So I want data for which Color is 1 and length is 2 and Size 4 i.e row 1 and 4 in above case. Is there any efficient way to filter the data without using for loop and going through all the 800,000 images and checking the condition?

Right now I am just using mysql statement to get the Ids of the data which satisify the condition.

```<code>"select Id from features_table where Color=1 and Length=2 and Size =4"
</code>```

But is there a faster way to do this? Or should I stick to this method? I am looking for a faster method so I am not sure whether fetching the Ids from the database will increase the execution time of the algorithm.

What are the other options that I can consider in this case? I read about Hash table, B-Tree, Binary Search tree and I am confused which is suitable for this case. Will kd-tree be helpful in this case? Because many images may have the same combination of color,length and size. I am not sure if kd-tree is the right thing to do. I read about FLANN in opencv used for kd-tree. Is there any example or resources which may be helpful in this case? Or are there  any built in c++ libraries?


答:
The downside is that your client now knows that you're providing data from a database via stored procedures, and has to hook directly into that to get at the data. If you wanted to change to e.g. a NoSQL solution, or proxy the call on to somewhere else, or load-balance requests, etc etc etc, this is much harder if you don't have a layer in between the data and the client.

Essentially, if you have;

```<code>Client <====> Interoperability Layer <====> Data
</code>```

Then the layer could be doing anything...or not very much. But you're now free to change what it does at any time, so long as the interface to the client doesn't change.

Title: High-Level SQL Interoperability

Body:
In a server -> client scenario, wouldn't it be simpler and faster to grant a public user access to a Stored Procedure rather than using web services (XML, REST, SOAP, etc) and other interoperable solutions?

That way you could connect directly to a database and get relevant content and do what you will with it in the same way across all languages and systems?

Body:
The downside is that your client now knows that you're providing data from a database via stored procedures, and has to hook directly into that to get at the data. If you wanted to change to e.g. a NoSQL solution, or proxy the call on to somewhere else, or load-balance requests, etc etc etc, this is much harder if you don't have a layer in between the data and the client.

Essentially, if you have;

Client <====> Interoperability Layer <====> Data

Then the layer could be doing anything...or not very much. But you're now free to change what it does at any time, so long as the interface to the client doesn't change.


问:
Etiquette using code found on GitHub and using Code beyond included Libraries
I've been trying to find what I'm supposed to do when I want to use code I find on GitHub. I think this post had some good information but I'm still somewhat confused.

I want to use code found in this repository https://github.com/wcdolphin/python-bcrypt

So according to the answer given the post, I'm to take the content in the LICENSE file of that repository and add it to the LICENSE in my project? I understand that I should give acknowledgement to the creator, how do I do that? Do I create a .txt file in the directory that holds the module that is their code and say something like "Created by wcdolphin, found at https://github.com/wcdolphin/python-bcrypt"?

Also, I haven't used used libraries beyond what is included with the Python library before. I see installation instructions there, but that would only work on my machine right? Can I download and add these files into my project directory and use them as modules? I found this post but I'm not sure if I can custom install stuff on Google App Engine. I intend on hosting my project up there(I'm not going to try to homebrew encrypt super sensitive information, it's more of a demonstration) and I think, with my limited knowledge, uploading the source with my source would be the best way.

Thanks

答:
It's not that hard, it's copyright law (not etiquette) and you don't need a lawyer unless there is money involved. You just need to sensibly consider the following situations.

If you're just going to use the code and distribute nothing your obligations are minimal. Just don't delete any notices from source code you use.

If you're going to distribute anything you have to decide what licence you are going to use, and it must be a licence compatible with any other components you use. Pick one you like and include it in your distribution. BSD is good. GPL or proprietary or public domain would not be good choices.

If you distribute binaries, you need a copyright acknowledgment notice in your distribution. A copy of the LICENSE file would do the job. You can combine it with your licence or not as you choose.

If you're going to distribute source code then you must leave the notices in the files. This is particularly important if you merge files or just distribute parts.

It's mostly just common sense. Drop an email to the authors if you have doubts. Spending money on lawyers is silly when there is no money involved, but you do need to read and think about this stuff.

If you plan on selling stuff and/or getting involved in any activities that might draw the attention of governments and/or people who can afford big lawyers then find yourself a good lawyer. You might well need it!


问:
An alternative to an array of functions?
I'm programming an app (php) which requires a very long list of similar yet different functions, which are being called by a set of keys:

```<code>$functions = [
    "do this" => function() {
        // does this
    },
    "do that" => function() {
        // does that
    }
]
etc.
</code>```

I've chosen to place the similar functions in an array because they are not similar enough - getting the same result with one big function which is full of conditional statements isn't gonna work. And I do need to be able to call them only by key, for example:

```<code>$program = ["do this", "do that", "do this"];
foreach ($program as $k => $v) {
    $functions[$v]();
}
</code>```

Thing is this functions-array structure is causing many problems, for example I'm having a hard time calling one array function from within another array function, e.g. this doesn't work:

```<code>"do that" => function() {
    $functions["do this"]();
}
</code>```

nor this:

```<code>"do that" => function() {
    global $functions;
    $functions["do this"]();
}
</code>```

or this:

```<code>"do that" => function($functions) {
    $functions["do this"]();
}

$functions["do that"]($functions);
</code>```

I guess I could have one giant function with a long switch statement:

```<code>function similar_functions($key) {
    switch ($key) {
        case "do this":
            // does this
        break;
        case "do that":
            // does that
        break;
    }
}
</code>```

But that doens't really seem like good practice. Or maybe it is?

So, what are my alternatives? Should I go with the switch structure? Or is there another, better solution?

答:
Expanding on @lortabac's comment:

You can pass around pointers to functions just by passing the function name, e.g.:

```<code>function fn1()
{
    // ...
}

function fn2($fn)
{
    $fn();
}

fn2(fn1);
</code>```

So you should be able to populate your array like so:

```<code>$functions = [
    "do this" => fn1,
    "do that" => fn2
]
</code>```

or, if you want to be able to have the functions be able to call each other using the references set up in the array, you can define the array first, then write the functions, then set the references to the functions in the array after that.

Body:
Expanding on @lortabac's comment:

You can pass around pointers to functions just by passing the function name, e.g.:

function fn1()
{
    // ...
}

function fn2($fn)
{
    $fn();
}

fn2(fn1);

So you should be able to populate your array like so:

$functions = [
    "do this" => fn1,
    "do that" => fn2
]

or, if you want to be able to have the functions be able to call each other using the references set up in the array, you can define the array first, then write the functions, then set the references to the functions in the array after that.


问:
Entity Translation Should be in the Data Layer or Business Layer
From my understanding I though the data layer should isolate the Data Technology from the rest of the application, for me this also include the schema in this case the data entity. Recently I've been looking at the Silk project from Patterns & Practices http://silk.codeplex.com/, and noticed that data entities are translated in the business layer rather than in the data layer.

I think the advantage is that it avoid the data layer to reference an assembly containing the business model. However the fact that it expose data entities publicly is from my understanding a disadvantage because external components may be dependent of the data schema.

I would like to understand why they translate data entities in the business layer and what are the advantages?

I know that they use code first entity framework, so that the entities doesn't have data technology related dependency, however there responsibility is still to structure the data model not the business model.

Thanks

答:
You can't make things totally independent and you have to make your picks.
But I think what counts is to have translation on one side.

Which part could possibly change more often?
Pick this part and try to depend on it as small as you can.

```<code>because external components may be dependent of the data schema
</code>```

If your project data layer would be changing a lot then it is disatvantage.
If data layer is more stabile then there is no problem.

Body:
You can't make things totally independent and you have to make your picks.
But I think what counts is to have translation on one side.

Which part could possibly change more often?
Pick this part and try to depend on it as small as you can.

because external components may be dependent of the data schema

If your project data layer would be changing a lot then it is disatvantage.
If data layer is more stabile then there is no problem.


答:
I imagine the conversion is done in the Business Layer as opposed to the Data Layer so that the Data Layer doesn't need to know every case of its use.

With the current approach it is the responsibility of the calling code to know how to use the Data Layer.  If the conversion happened in the Data Layer, then it would need to be aware of all the calling code cases.

This may be pretty straight forward at first because you probably have a close to 1:1 mapping between Business Objects/Entities and the storage schema, but that won't necessarily always be the case.

Take the example of two Departments in a business working with a similar concept... let's say an Approval Workflow.  Dept A calls each step in the workflow a Bla.  Dept B likes that Dept A has its workflow automated and wants the same, but it calls its workflow steps BongoBlas.  It is a fundamental fact of the business domain that the two workflows are identical and will always be, but the business process is such that the steps have different names (and some of the metadata fields have different names as well).

In this case you could develop a second Business Entity which uses the same persistence as the first.

If the Data Layer was responsible for conversions then it would now need to be extended to handle BongoBla conversions as well as its existing Bla conversions.  This seems a bit odd because as far as the Data Layer is concerned this is none of its concern.

The Data Layer is consumer agnostic.

This is why it makes more sense for the consumers of the Data Layer to be responsible for the data conversions.  When new consumers are added then only the consumer code needs to be written.  The Data Layer can remain untouched.  And this makes sense because the concerns of the Data Layer haven't actually changed.

Note: Sorry for the lame example scenario above.  If I think of anything better I'll update the answer.

Title: Entity Translation Should be in the Data Layer or Business Layer

Body:
From my understanding I though the data layer should isolate the Data Technology from the rest of the application, for me this also include the schema in this case the data entity. Recently I've been looking at the Silk project from Patterns & Practices http://silk.codeplex.com/, and noticed that data entities are translated in the business layer rather than in the data layer.

I think the advantage is that it avoid the data layer to reference an assembly containing the business model. However the fact that it expose data entities publicly is from my understanding a disadvantage because external components may be dependent of the data schema.

I would like to understand why they translate data entities in the business layer and what are the advantages?

I know that they use code first entity framework, so that the entities doesn't have data technology related dependency, however there responsibility is still to structure the data model not the business model.

Thanks


问:
how to check email address exist or not in php
I have tried a lot but could not find a way by which I will find if an email id exists or not.

My problem is that I do not want to make visitor to email me with fake email Id. Is there any solution for this? I do not want to use smpt service as it send mail to solve this.

答:
The only way to check if

the address is valid

the mailbox is working

the email was given by the owner

is to send a confirmation email with a link and a unique token. The recipient will then click on the link and confirm that the he got the email.

Summarized:

Generate a unique ID and store it along with the hashed supplied email address

Send an email to the address with a URL to your validation application/script (e.g., https://example.com/validate/id=UNIQUEID&email=HASHEDEMAIL)

When the URL is clicked your application will check if the unique ID corresponds to what you generated and sent to the user


问:
Is it normal for developers to suggest feature ideas to product owners?
I've started working as a developer fairly recently, having worked as a systems administrator before.

My understanding of how a software development team using Agile functions is that the "what we need to implement" communication happens mostly in one direction, from the product owner to the developers. Developers can express their concerns to the product owner about technical debt, but coming up with feature ideas should not be one of their main responsibilities.

The company I'm working at has a different view. To them, developers should not only go to the product owners of their own team to suggest feature ideas, but also to the product owners of other teams if they think they have something to contribute to that team's product. The idea is that we're all one big Team <company name>, and all developers should use their expertise to push features they think will be useful.

Is such an approach "normal", for lack of a better word? Am I being too passive, should I take the initiative and start pushing ideas to product owners? Conversely, has the company got it completely wrong and I should look for employment elsewhere?

答:
The reason a lot of developers are "passive," as you put it, is because it takes a certain amount of domain knowledge and experience before good product ideas come to you. But if they do come, there's no reason not to suggest them and champion them.

Keep in mind - developers, product owners, sales people, etc., are all on the same team, with the same goal: building a successful product. Work towards that goal however you can.


答:
Yes, it is quite normal.

There is well known 80% work - 20% innovation model at google, where people 20% of their time devote to something they like. This way, not only they get new features, but a whole new products and services.

Am I being too passive, should I take the initiative and start pushing ideas to product owners?

That depends on your personality. I have worked with really passionate people, but also with people without any emotion that do their 8 hours shift and go home.

Title: Is it normal for developers to suggest feature ideas to product owners?

Body:
I've started working as a developer fairly recently, having worked as a systems administrator before.

My understanding of how a software development team using Agile functions is that the "what we need to implement" communication happens mostly in one direction, from the product owner to the developers. Developers can express their concerns to the product owner about technical debt, but coming up with feature ideas should not be one of their main responsibilities.

The company I'm working at has a different view. To them, developers should not only go to the product owners of their own team to suggest feature ideas, but also to the product owners of other teams if they think they have something to contribute to that team's product. The idea is that we're all one big Team <company name>, and all developers should use their expertise to push features they think will be useful.

Is such an approach "normal", for lack of a better word? Am I being too passive, should I take the initiative and start pushing ideas to product owners? Conversely, has the company got it completely wrong and I should look for employment elsewhere?


问:
Should I lock a list of objects while a socket is receiving messages?
I have a scenario where I will be receiving messages through a socket connection. I also need to keep a list of 100 messages (such as List) and periodically toss out old messages from the list when a condition is met.

```<code>List<Message> MessageList = new List<Message>();
Message CurrentMessage = new Message();

public void ReceiveSocketMessage (SocketMessage Message) {

    if (Message.Type == duplicate) {
        CurrentMessage = MessageList.FirstOrDefault(x=> x.MessageText == Message.Text);
        CurrentMessage.Time = DateTime.Now;
    } else {
        MessageList.Add(Message);
    }
}
</code>```

Since the socket sends messages very quickly, it seems like any other method that attempts to access MessageList will cause a problem. Other methods will need to access the list at many random points in time.

I just can't get my head wrapped around working on the list of objects without causing trouble. What is the traditional method of handling this?

UPDATE: Would it be simpler just to maintain a list of items in a database table instead of a list of c# objects? A database would surely have all the major locking problems ironed out to a point where I shouldn't need to worry about it.

答:
I would encapsulate the standard list in a custom list class, which is to be made thread-safe. How it arrives at thread-safety is nicely encapsulated, and can the implementation can be tweaked for best performance given it's typical usage.

First try if a simple lock on every access to the list gives acceptable performance. If so, you're done!

If this is too slow, you should profile the list usage. Are there a lot of reads from multiple threads and only few writes? You could try ReaderWriterLock, which would allow the reads to be in parallel. And maybe some buffering to do a bulk update, which minimizes the write lock time.


答:
Don't have them enter an email.

Instead rely on a different company to validate the email. Use something like OAUTH/2 with google or twitter... IE: google wants the same thing as you, no fake accounts. They go through lengths to confirm that the account that is created is real and connected to someone real so have your application/page/etc ask them to connect to their google account which will provide you with a valid email.

https://developers.google.com/accounts/docs/OAuth2

Title: how to check email address exist or not in php

Body:
I have tried a lot but could not find a way by which I will find if an email id exists or not.

My problem is that I do not want to make visitor to email me with fake email Id. Is there any solution for this? I do not want to use smpt service as it send mail to solve this.


问:
Establishing an API to provide end-user apps/scripts access to multiple types of databases

Question and Context

I am currently working on a project where the main question is, how do we insert an API between the database and end-users who may develop applications/scripts of their own that will work with or on top of the database?

The database type I am working with is Postgresql, and this project is in-house, so the end-users are users in other development groups.

Aims

What I am looking to satisfy are the following:

Avoid a wide-interface.

Require authentication from the application that is to use the API - provide end-user a single unique token or key to access the application.  No user/password management.

Have the option to make it open - no authentication required.

Allow users to create and read records.

Restrict users from deleting and updating existing records.

(Optional) Track who is using the API - number of requests, records, etc.

(Optional) Track amount of time spent completing a request.

Some Thoughts

My initial thought is to establish a RESTful API by building my own servlet to handle the requests, and of course, customize it to meet my aims.  However, I have a feeling there are already many versions of this wheel out there so I would like to avoid reinventing it.

An additional question to this would be, what is this kind of API/layer called (aside from DAL)?

Update

How would the advantages of putting a common API in place be if there are multiple databases of varying types e.g. postgres, ms sql, oracle, etc.?

答:
<answer>

I'm late to the question, but I'll echo what James Anderson said: implementing some kind of data warehouse may be a better option.

Go through your existing databases and model the information in a consistent way that all your groups can use. (You were already planning some of this work when creating your API. Change your thinking from Objects to Relations.)

Think from an entire organization perspective, with current and past software. You may have entity/data types that have certain elements where one system is master of one part of the entity and another is master over other aspects. (e.g. The Student system is master over all student records but transportation system knows all the buses they may ride).

Model all the data to fit into the same database, with as close to the native format for information for that data elements master system (e.g. Student system has 1 field for a bus number, but transportation categorizes 4 different buses for a student)

Create views that can be used for reading the data. Keeping the data in a separate database makes updates and deletions not an option. You're fully in control of which users have access to what.

I don't have a simple answer for allowing users to create new records or tracking usage and response time. For creating records, maybe some combination of creating rules or triggers to update the origin DB using dblink or postgres_fdw could accomplish what you want. Analytics would consist of watching the logs.

Other things to Consider
- Do all of your dev groups know how to work with a REST based resource (or whatever your API is going to use)?
- Can you pull data into excel with your API? There is a huge ecosystem built around reports, data extraction, business intelligence using SQL based tools.

</answer>

Sidebar

Based on your Update, I think I have a similar problem to yours in my organization and was about to post a separate question about it. I was leaning towards writing a bunch of APIs using Apache Thrift based services that have the "knowledge" of how to query different data elements the right way. My reasoning was:

Scripts wouldn't need to fight with DB drivers since they'd use the service. Especially important if I wanted to try out a different language that didn't have the DB driver implemented. (NodeJS and Go work with Thrift, I can't get any Oracle drivers to work on Windows)

I could have a standard way of pulling data elements from multiple vendor versions of our primary line of business application (2 software conversions with a 6 month implementation time in the time span of 4 years makes it hard to query historical data)

My answer reflects why I am settling on the SQL based approach. The API would be phase 2 of the project.


答:
I have done this in the past in PHP using SwiftMailer, but you could probably achieve the same in straight php.

If you send your email with a from address like no-reply@mydomain.com (which is a real address to which you have access) the email will be sent back to that box.

From there, you can have a planned task to check for emails in that box, grab the email to which you sent it and flag de user as a user with an invalid address and don't send anymore communication to them. After processing the email, you could either delete the email in the box or store it in an other folder.

When I did it, I an a requirement to keep a copy of every email sent by the application. To identify every unsuccessful deliveries, I added a unique key to the email headers which was grabed back by the code analysing the rebound mailbox and I could flag every correspondances sent (ex: 2 first message were successfully delivered, but the 3rd and 4th were not)


答:
It depends what you mean by feature ideas.

In the planning game, it isn't uncommon for developers to provide input about a story which might end up in the iteration. However, this is very different from developers coming up with stories on their own.

In mature systems, developers may suggest a way round a known issue which could make it into an iteration.

Enhancements could be OK e.g. adding a graph for a report, but alarm bells would ring for me if developers were coming up with bona fide new stories. If there was real value in this, I'd question why there wasn't an existing unimplemented story for this or why it never came up in the retrospective.


问:
Why is BigDecimal the best data type for currency?
I was reading this question and the accepted answer says that BigDecimal is the best type for representing currency values. I've also seen several other questions support the use of big decimal.

Why is BigDecimal the best type? I don't understand the relevance of arguments such as precise calculations or  people with large net worth. I am pretty sure that there are no currencies that round to the 10th decimal place, and almost no one has 8-bytes worth of money (if it were to store it as a long).

For taxes and other intermediary calculations, I can see how it is important to make sure you are using a proper type that doesn't round/truncate values prematurely, but that doesn't seem relevant to me either since an error of 0.0000000001 cents on the dollar does not seem that big to me.

It may be due to my lack of understanding of the importance of accuracy when it comes to financial statements, so perhaps someone can also clarify whether a millionth of a cent is significant as a final number.

答:
The right type to represent currency values depends of the application.

Two plausible choices are a type capable of exact arithmetic or a
floating point type. Please remember two facts:

In floating point arithmetic, usual algebraic identities (like
commutativity and associativity) does not hold any more. They still
hold in exact arithmetic.

In exact arithmetic, it is not possible to work with functions
other than polynomials, so we cannot use the square root or the
exponential functions.  Floating point arithmetics allows to use
them.

In a double accounting personal finance software, exact arithmetic is
preferrable.  We expect all of the cashflows recorded to sum up to
zero.  Since this is an algebraic identity, we can only verify it if
we use exact arithmetics.  Here using a floating point would make the
whole principe of double accounting useless.

In an internal software used by a clearing house, exact arithmetic is
also mandatory, basically for the same reason as previously.  There is
a conservation principle, so that cashflows should always sum up to
zero.  Since the program has to satisfy an invariant of an algebraic
nature, it must rely on exact arithmetics.

In a pricing or risk management software implementing methods of mathematical finance, complex computations reminescent of
physics simulations are performed and expectations estimates are
computed.  The very nature of this problem require the use of floating
point numbers.


问:
Hadoop and Object Reuse, Why?
In Hadoop, objects passed to reducers are reused. This is extremely surprising and hard to track down if you're not expecting it. Furthermore, the original tracker for this "feature" doesn't offer any evidence that this change actually improved performance (unless I missed it).

It would speed up the system substantially if we reused the keys and values [...] but I think it is worth doing.

This seems completely counter to this very popular answer. Is there some credence to the Hadoop developer's claim? Is there something "special" about Hadoop that would invalidate the notion of object creation being cheap?

答:
If you read the article you linked, it says

Running a simple unit test on your desktop machine should highlight
  that creating 1x10^6 new String objects with random byte content is
  slower than using a single Text object and calling the set method to
  configure the underlying byte contents

Well, that is self-evident. Creating a million new strings is always going to be slower than using a StringBuilder to manipulate a single string; everyone knows that.   But this may be a straw man; last time I checked, you still needed an individual string for each key in a collection.

If his argument is that allocating a million new strings to make a copy of the collection is expensive, well, yes it is.  Strings are reference types, after all; you could just store references to the original strings.

I guess we'll have to wait for him to complete his benchmarks.

Title: Hadoop and Object Reuse, Why?


答:
Your guiding factors here should be how much traffic you expect to see through your queue, how important it is, and the relationship between reads and writes.

There are now some pretty handy built in collections in the .Net framework that can help you out with concurrency stuff and save a lot of time and effort but of course once you are playing with locking and unlocking resources you will almost certainly bump into some obscure blocking circumstances sooner or later. Certainly a ConcurrentQueue or similar should be able to help you with the problem you have outlined. Of course Queues expect a push-pop type of workflow, which may be what you want but if not, you may be well served looking into other thread safe collections.

If these are incoming messages that you essentially need to put into a "received" queue and then process, then you might look at using a message queue of some kind rather than simply dropping the data in the database- this can offer you the benefits of having your queue data stored in such a way that if the system goes down it should be recoverable ( which may or may not be important to you ) and it also potentially means if you need to distribute your workload in future you can simply plug other clients into the queue and process it as necessary. There are a bunch of Message Queue tools out there that may be able to help you, but obviously the need for this is rather dependent on your context.

Title: Should I lock a list of objects while a socket is receiving messages?

Body:
I have a scenario where I will be receiving messages through a socket connection. I also need to keep a list of 100 messages (such as List) and periodically toss out old messages from the list when a condition is met.

```<code>List<Message> MessageList = new List<Message>();
Message CurrentMessage = new Message();

public void ReceiveSocketMessage (SocketMessage Message) {

    if (Message.Type == duplicate) {
        CurrentMessage = MessageList.FirstOrDefault(x=> x.MessageText == Message.Text);
        CurrentMessage.Time = DateTime.Now;
    } else {
        MessageList.Add(Message);
    }
}
</code>```

Since the socket sends messages very quickly, it seems like any other method that attempts to access MessageList will cause a problem. Other methods will need to access the list at many random points in time.

I just can't get my head wrapped around working on the list of objects without causing trouble. What is the traditional method of handling this?

UPDATE: Would it be simpler just to maintain a list of items in a database table instead of a list of c# objects? A database would surely have all the major locking problems ironed out to a point where I shouldn't need to worry about it.


答:
It all comes down to precision, and Java's BigDecimal seems the correct answer on that platform because it gives you the best support for specifying and preserving what can be highly variable precision.

A millionth of a cent is only 10-5 from a shift in payable amount, and it's not that hard to come up with a situation where that level of precision matters.

Company A is publicly traded, with fifty million (5x106) shares outstanding and a current price of $10.

Person B buys $1 of Company A, through a broker.  They now own one-tenth of a share, or a one five-hundred-millionth of Company A.  (10-7).

Company A is found to be absurdly over-valued, and after a bit of a scandal winds up accepting a stock-swap purchase by Company C at a value of $1,000  (103), with each shareholder getting the equivalent number to be paid out equally to the shareholders in either cash or stock.

How much cash or stock can Person B get?  Note that if you get the number wrong, Person B (who happens to be an out-of-work lawyer in his 30s) can mess up the entire deal and possibly earn himself a paycheck by suing for his value lost plus legal fees.

Now, the valuation is fairly absurd on purpose, but the same "you need to get it right or it explodes" details even if the numbers are only off by a minuscule amount.

Title: Why is BigDecimal the best data type for currency?

Body:
I was reading this question and the accepted answer says that BigDecimal is the best type for representing currency values. I've also seen several other questions support the use of big decimal.

Why is BigDecimal the best type? I don't understand the relevance of arguments such as precise calculations or  people with large net worth. I am pretty sure that there are no currencies that round to the 10th decimal place, and almost no one has 8-bytes worth of money (if it were to store it as a long).

For taxes and other intermediary calculations, I can see how it is important to make sure you are using a proper type that doesn't round/truncate values prematurely, but that doesn't seem relevant to me either since an error of 0.0000000001 cents on the dollar does not seem that big to me.

It may be due to my lack of understanding of the importance of accuracy when it comes to financial statements, so perhaps someone can also clarify whether a millionth of a cent is significant as a final number.


问:
How do you deal with time estimates?
If given too little time, quality suffers. If given too much time, developers will find a way to use all alloted time, no matter what. What would be a good way with dealing with estimates? Are they a necessary evil?</p>

答:
Delevopers should be the ones producing estimates for their own work, not you. (Or, rephrased, you should only be estimating your own work.)

Time and experience will allow you to estimate more accurately, especially if you track your own estimates.

The real problem with programming is that for a particular language, on a particular project, you might be able to give highly accurate estimates to routine feature requests. But a lot of the time you have to give an estimate on something that you haven't done before (and possibly in a language you don't know, and/or with a framework you don't know). In which case your estimate is, in some form, a guess. Try guess anyway, keep track of your estimates, and reflect.

ContentLicense: CC BY-SA 2.5

Title: How do you deal with time estimates?


问:
How to provide a custom ID to a downloadable application?
I've noticed that with remote support services, a technician usually sends you a download link to an executable. When you click on that link, it installs a software which automatically connects with the remote technician and allows him/her to access your computer. Basically, what's happening is that somehow the installed application has a session ID which it's using to identify and connect with the technician. How is that session ID passed onto the downloaded application?

Is a custom executable compiled/generated for each session and the executable has that session ID embedded within it's resources? any other method of achieving the same?

答:
The ID can be embedded as a resource in the executable, which gets overwritten on the server before it is distributed to individual users.  Or simply tacked on to the end of the executable's file.  When the program runs, it either loads the resource, or 'opens' itself and reads the ID.

It might get a little more complicated if the executables are digitally signed.  They may have to sign each one on the server side.  But the certainly wouldn't need to re-compile.


问:
In python, do we have class encapsulation at the level of the object?
I was bitten by using the is operator when i should have been using ==.  Am aware that the former tests for equality of the objects' identities and that the latter tests for equality of the objects' contents.

Using is, i thought, also implicitly tests for the equality of the contents.  For example if a is b is true, then the contents must be the same.  This was the working assumption and i believe that it's still true.  But what was discovered, and should have been known, is that if if a is b is false, then the contents of a and b may or may not be the same.

Example (Python 3.3.3):

```<code>class Food:
    def favourite_restaurant(self):
        return "the foo diner"

if __name__ == '__main__':

    fr = "the juice bar"
    print('%r  is  %r: %r' % (fr, 'the juice bar', (fr is 'the juice bar')))
    print('%r  ==  %r: %r' % (fr, 'the juice bar', (fr == 'the juice bar')))

    f = Food()
    result = f.favourite_restaurant()
    print('%r  is  %r: %r' % (result, 'the foo diner', (result is 'the foo diner')))
    print('%r  ==  %r: %r' % (result, 'the foo diner', (result == 'the foo diner')))
</code>```

The first print block says:

```<code>'the juice bar'  is  'the juice bar': True
'the juice bar'  ==  'the juice bar': True
</code>```

The second print block says:

```<code>result: 'the foo diner'
'the foo diner'  is  'the foo diner': False
'the foo diner'  ==  'the foo diner': True
</code>```

It seems that objects instantiated within the instance of a class have their own group of ids, separate from objects outside the class.

My understanding that encapsulation in python is really a matter for 'consenting adults'.  Do we actually have encapsulation at some lower level?

答:
This has nothing to do with encapsulation, and everything with a Python implementation detail as to when string literals produce a string object.

What is specifically happening here is that Python uses constants to store literal values used in code. Your 'the juice bar' value is such a constant.

The compiler has stored 'the juice bar' with the code block object for the module, and is reusing that object. You are not creating new string values in the __name__ == '__main__' block.

Functions get their own code blocks, which includes their own constants, and thus their own string objects.

Demonstration:

```<code>>>> import dis
>>> code = compile('''\
... fr = "the juice bar"
... print('%r  is  %r: %r' % (fr, 'the juice bar', (fr is 'the juice bar')))
... print('%r  ==  %r: %r' % (fr, 'the juice bar', (fr == 'the juice bar')))
... ''', '<stdin>', 'exec')
>>> code.co_consts
('the juice bar', '%r  is  %r: %r', '%r  ==  %r: %r', None)
>>> dis.dis(code)
  1           0 LOAD_CONST               0 ('the juice bar')
              3 STORE_NAME               0 (fr)

  2           6 LOAD_NAME                1 (print)
              9 LOAD_CONST               1 ('%r  is  %r: %r')
             12 LOAD_NAME                0 (fr)
             15 LOAD_CONST               0 ('the juice bar')
             18 LOAD_NAME                0 (fr)
             21 LOAD_CONST               0 ('the juice bar')
             24 COMPARE_OP               8 (is)
             27 BUILD_TUPLE              3
             30 BINARY_MODULO
             31 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             34 POP_TOP

  3          35 LOAD_NAME                1 (print)
             38 LOAD_CONST               2 ('%r  ==  %r: %r')
             41 LOAD_NAME                0 (fr)
             44 LOAD_CONST               0 ('the juice bar')
             47 LOAD_NAME                0 (fr)
             50 LOAD_CONST               0 ('the juice bar')
             53 COMPARE_OP               2 (==)
             56 BUILD_TUPLE              3
             59 BINARY_MODULO
             60 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             63 POP_TOP
             64 LOAD_CONST               3 (None)
             67 RETURN_VALUE
</code>```

This is a disassembly of the bytecode for just the fr test; note the LOAD_CONST references; these load a constant (stored at position 0 to both set fr and to later compare if fr is 'the juice bar') is the same object.

The function object has a similar co_const construct, which is what Python dutifully returns when called:

```<code>>>> class Food:
...     def favourite_restaurant(self):
...         return "the foo diner"
...
>>> Food.favourite_restaurant.__code__.co_consts
(None, 'the foo diner')
>>> dis.dis(Food.favourite_restaurant)
  3           0 LOAD_CONST               1 ('the foo diner')
              3 RETURN_VALUE
</code>```

As a result, the 'the foo diner' string in the method is not the same object as the 'the foo diner' string used in your __name__ == '__main__' block further down.

Armed with this knowledge you can generate wholly new string objects:

```<code>>>> a = 'foo'
>>> b = 'bar'
>>> ab = a + ' ' + b
>>> ab is a + ' ' + b
False
>>> ab == a + ' ' + b
True
</code>```

Generally speaking, you are right. is always tests for identity, == for equality. If the identity test passes, then it is usually true that the objects are equal too.

There is one big exception in the standard library:

```<code>>>> nan = float('nan')
>>> nan is nan
True
>>> nan == nan
False
</code>```

The Not-a-number floating point constant is never equal to anything. Not even with itself.

It should be noted that Python translates op1 == op2 into a call to the object.__eq__() special hook method, which is free to return whatever it likes. Usually that's a boolean, but that is not required:

By convention, False and True are returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of an if statement), Python will call bool() on the value to determine if the result is true or false.

Body:
This has nothing to do with encapsulation, and everything with a Python implementation detail as to when string literals produce a string object.

What is specifically happening here is that Python uses constants to store literal values used in code. Your 'the juice bar' value is such a constant.

The compiler has stored 'the juice bar' with the code block object for the module, and is reusing that object. You are not creating new string values in the __name__ == '__main__' block.

Functions get their own code blocks, which includes their own constants, and thus their own string objects.

Demonstration:

>>> import dis
>>> code = compile('''\
... fr = "the juice bar"
... print('%r  is  %r: %r' % (fr, 'the juice bar', (fr is 'the juice bar')))
... print('%r  ==  %r: %r' % (fr, 'the juice bar', (fr == 'the juice bar')))
... ''', '<stdin>', 'exec')
>>> code.co_consts
('the juice bar', '%r  is  %r: %r', '%r  ==  %r: %r', None)
>>> dis.dis(code)
  1           0 LOAD_CONST               0 ('the juice bar')
              3 STORE_NAME               0 (fr)

  2           6 LOAD_NAME                1 (print)
              9 LOAD_CONST               1 ('%r  is  %r: %r')
             12 LOAD_NAME                0 (fr)
             15 LOAD_CONST               0 ('the juice bar')
             18 LOAD_NAME                0 (fr)
             21 LOAD_CONST               0 ('the juice bar')
             24 COMPARE_OP               8 (is)
             27 BUILD_TUPLE              3
             30 BINARY_MODULO
             31 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             34 POP_TOP

  3          35 LOAD_NAME                1 (print)
             38 LOAD_CONST               2 ('%r  ==  %r: %r')
             41 LOAD_NAME                0 (fr)
             44 LOAD_CONST               0 ('the juice bar')
             47 LOAD_NAME                0 (fr)
             50 LOAD_CONST               0 ('the juice bar')
             53 COMPARE_OP               2 (==)
             56 BUILD_TUPLE              3
             59 BINARY_MODULO
             60 CALL_FUNCTION            1 (1 positional, 0 keyword pair)
             63 POP_TOP
             64 LOAD_CONST               3 (None)
             67 RETURN_VALUE

This is a disassembly of the bytecode for just the fr test; note the LOAD_CONST references; these load a constant (stored at position 0 to both set fr and to later compare if fr is 'the juice bar') is the same object.

The function object has a similar co_const construct, which is what Python dutifully returns when called:

>>> class Food:
...     def favourite_restaurant(self):
...         return "the foo diner"
...
>>> Food.favourite_restaurant.__code__.co_consts
(None, 'the foo diner')
>>> dis.dis(Food.favourite_restaurant)
  3           0 LOAD_CONST               1 ('the foo diner')
              3 RETURN_VALUE

As a result, the 'the foo diner' string in the method is not the same object as the 'the foo diner' string used in your __name__ == '__main__' block further down.

Armed with this knowledge you can generate wholly new string objects:

>>> a = 'foo'
>>> b = 'bar'
>>> ab = a + ' ' + b
>>> ab is a + ' ' + b
False
>>> ab == a + ' ' + b
True

Generally speaking, you are right. is always tests for identity, == for equality. If the identity test passes, then it is usually true that the objects are equal too.

There is one big exception in the standard library:

>>> nan = float('nan')
>>> nan is nan
True
>>> nan == nan
False

The Not-a-number floating point constant is never equal to anything. Not even with itself.

It should be noted that Python translates op1 == op2 into a call to the object.__eq__() special hook method, which is free to return whatever it likes. Usually that's a boolean, but that is not required:

By convention, False and True are returned for a successful comparison. However, these methods can return any value, so if the comparison operator is used in a Boolean context (e.g., in the condition of an if statement), Python will call bool() on the value to determine if the result is true or false.


问:
GPLv3 code in non-GPL software -- linking vs. CLI
Suppose there's a GPLv3 app that has a GUI and a CLI. Can I legally expand its CLI (to give me access to functionality hitherto only available via the app's API), release the result under GPL and then create a non-GPL (perhaps proprietary) app that depends on this modified GPL app (via the expanded CLI)?</p>

答:
Short answer:

Maybe.

Long answer:

There are a couple of exception paths that might enable you to do what you're suggesting.

The first approach is to have the GPL'd app only provide data to the second non-GPL app.  See here for additional details.

Another approach relies upon creating a plugin structure, but this is a tricky approach.  See here for FSF's comments on this approach.

Depending upon the original GPL program, you might be able to write a module with additional permissions, but this is likely going to be tricky to do as well.  See this related FSF FAQ

Finally, if you never distribute your second application then you are not required to distribute the source as per the terms of the GPL.


问:
Are there established algorithms for spacing out objects of unequal size?
I'm working on visualizing a hierarchy.  There will be clusters of objects, each cluster containing rectangles of fixed width but variable height.  I'd like to arrange these within a rectangular space so as to have equal visual spacing between them, something like this:

Before I spend a day inventing the wheel, are there standard algorithms for this kind of distribution and space-filling?  If the objects were all the same size, I'd just use a grid.

I'll be using this algorithm at two levels: once to lay out the clusters, and again to lay out the objects within each cluster.  The latter would look best if they were arranged within a roughly circular space, but if that complicates things excessively I'm OK with rectangular.

I won't be showing relationships between these objects, so distance minimization is not necessary.

There's a similar question (https://ux.stackexchange.com/questions/29220/what-would-be-the-best-way-to-fill-space-in-an-user-interface-for-irregular-im) about laying out rectangular images while eliminating or minimizing white space.  In my case, I want to equalize white space, clusters will be circular, and some clusters will be much larger than others.

答:
I've tackled a similar problem by randomising the positions of each object, then measuring the distance and angle (or normalised gradient) to each other object and nudging them a small amount towards or away from each other based on their relationship to the other object (related=close, unrelated=far), then repeating until the distances start to fall within an acceptable range of what you want.
Depending on the size of the data set it can take a while but gives good final results and can look cool in the process! :)</p>


问:
When the ScrumMaster is a technical leader, it's a good or a bad practice?
I know that the ScrumMaster should be a leader, but it's a good practice to have a technical leader as a ScrumMaster. For example: a coordinator.</p>

答:
The ScrumMaster is not really a "leader".  If anything, you can describe them as a "servant leader".  The difference is well worth noting.

On your actual question - is a technical lead a good ScrumMaster?

Maybe.

The skillsets are fairly different, but have intersections, so it really depends on the person in question.  Can they keep their roles separate?  Are they able to dedicate enough time to both?  And, again, can they provide the servant leadership that a Scrum team requires?

I think the right person could fulfill both of these roles very well.  Guiding the team, protecting them from outside forces, allowing them to stay productive, etc, etc.

Keep in mind though, leadership on a scrum team is usually inferred through respect and experience among team members.  It's a team through and through.


答:
Scrum puts the focus on teams. Because of this, self-management, communication and decision making as a team is very important in scrum. Also, the team as a whole is responsible for the outcome of the sprint. This is a very key difference of scrum with traditional methods where a single person could be held responsible for outcome of a team effort.

The scrum master holds the key about the scrum process, and that is the only thing where he/she has the power. When a "lead" person comes to the post of scrum master, there is a chance of conflict of interest. For example, the scrum master might overstep by enforcing certain work on a team member. By overriding own interests over the teams interest, there is a risk of scrum affecting the team chemistry. There is a chance that unknowingly the scrum master will be the responsible person for the outcome of the sprint.

That doesn't mean a lead cannot be a scrum master, but he has to be aware of the potential consequences his power will cause to the team and the effect of that preventing the basic principles of scrum.

Title: When the ScrumMaster is a technical leader, it's a good or a bad practice?

Body: I know that the ScrumMaster should be a leader, but it's a good practice to have a technical leader as a ScrumMaster. For example: a coordinator.</p>


问:
Choosing value in SQL query vs (Java) code
I need to choose one of three values of an integer using the value of a column on a nullable column of a table.

There are at least two approaches: 1) use SQL to do all the work: test null values, and choose between the other values, or 2) read the value and use code -in this case Java- to choose.

Which one is "better", ie. easier to understand & more maintainable? Do you have any other metric use to decide?

As an example, I have the following code:

```<code>// If id is equal to:
//   -1, then make v = 1
//   null, then make v = 2
//   in any other case, make v = 3

// Option 1:
int v;
String query = "SELECT CASE min(Id) WHEN NULL THEN 2 WHEN -1 THEN 1 ELSE 3 END AS Id"
        + "FROM TableA WHERE SomeField IN (SELECT ...blah blah...)";
ResultSet rs = // execute query
if (rs.next()) {
    v = rs.getInt("Id");
} else {
    // TODO something went *very* wrong...
}

// Option 2:
int v;
String query = "SELECT CASE min(Id) Id"
        + "FROM TableA WHERE SomeField IN (SELECT ...blah blah...)";
ResultSet rs = // execute query
if (rs.next()) {
    final int id = rs.getInt("Id");
    if (rs.wasNull()) {
        v = 2;
    } else if (id == -1) {
        v = 1;
    } else {
        v = 3;
    }
} else {
    // TODO something went *very* wrong...
}
</code>```

答:
In the example you give, I don't think it makes a difference.

One important thing is to be consistent with where you put your logic, so you'll know where to look for it later. When querying databases, it's best to only pull the data needed. In your example, it doesn't seem to make a difference (same number of records and amount of data).

What are you going to do when your logic gets more involved? You may find you're better off handling it in Java or some other procedural language of choice. This is probably a personal preference, but could be influenced by which language you're more skilled.

If you wanted to have some sort of code library to reuse this logic, I wouldn't recommend having it in your database code. Not all data come from the same database. What if you want to perform this logic on a different table or different columns? You won't be able to reuse this code.

These recommendations aren't based on trying to pre-optimize or to go out of your way to extend things you don't need. You were probably able to build both solutions with the same amount of effort. If you think any of these potential pit-falls could occur, just go in that direction and be consistent. The next coder will appreciate it even if it is you.

EDIT:  Also, I write a lot of SQL code in my job (as database objects), but can't stand it when I have to write them in strings in other languages. Simple selects are fine. The shorter the better.

IDE - the debugger in Java here will probably be more useful. Of course you can test your sql somewhere else.

Magic Numbers - it would be easier in the Java code to represent your numbers (1,2,3) as descriptive variables/constants.


问:
What is the industry norm for naming standard for gui object event handlers in C#
Lets say you have a button objects on a form with a click event (c#/.Net). How is the event handler normally named throughout the industry?

fooButton_Click

fooButtonClick

(or if you like Hungarian)

btnFoo_Click

btnFooClick

When visual studio creates the event handler it defaults to underscore + EventName.
This seems to violate the norm of using camelCasing and UppderCamelCasing instead of separating words with underscores.

Is there any reason to change it, or practically everyone following what Visual Studio does?

答: I think there are places where the VS default is used, places where it is changed to some kind of different standard and places where it is up to what the individual developer prefers. Don't expect to find any "industry norm". Just find a consensus with your team how strict you want your coding standard to be, and if you want it strict, find some agreement how the code shall look.</p>


答:
We are using well reviewed coding guidelines and standards which forbids the underscore for method (and event handlers) names. And, we are using PascalCase for method names.

Another practice for naming the event handlers is to give them time aware names. For example for the 'Click' event -> Click*ed*. This indicates that the event already happened and you have to deal with the rest. To make this name more time aware, the On prefix is being used. Last but not least, we are indicating the event object within the name, On*CancelButton*Clicked

OnCancelButtonClicked would be my choice.

PS: The underscore for event handlers probably comes from Visual Basic (Classic) to Visual Studio.

Title: What is the industry norm for naming standard for gui object event handlers in C#

Body:
Lets say you have a button objects on a form with a click event (c#/.Net). How is the event handler normally named throughout the industry?

fooButton_Click

fooButtonClick

(or if you like Hungarian)

btnFoo_Click

btnFooClick

When visual studio creates the event handler it defaults to underscore + EventName.
This seems to violate the norm of using camelCasing and UppderCamelCasing instead of separating words with underscores.

Is there any reason to change it, or practically everyone following what Visual Studio does?


问:
Sorting an array when values are decreased by each swap
Recently in an interview I come across a question:

We have an unsorted array, we need to sort it with minimum number of swap. We have in sort a 'tax' of 1 is deducted from the number we are swapping.

so suppose initially we have an array as

```<code>2 4 1 3 5
^   ^
</code>```

on swaping say 2 and 1, the new state of the array is:

```<code>0 4 1 3 5  // 'tax' of 1 is deducted from 1 and 2
^   ^      // so we have 0 and 1 at there place after the swap
</code>```

So we need to sort the array in min. number of swap. Any suggestions regarding the algorithm design?

I thought of doing this with merger sort but still not sure if this is the best approach.

答:
Hi After thinking a bit i came across this solution and now i am feeling like i was avoiding a very basic concept.
SO i implement sorting through merger sort , which basically divides and sort and merger the array . we have tax is deducted for swaping two values but not for comparision .

so I used an alternate array temp in order to merge the values and then copy the value of the same into the original array my C++ code is something like this :

```<code>#include<iostream>

using namespace std;

void merge(int a[],int temp[],int left,int mid,int right);

void mergesort(int a[],int temp[],int low,int high)
{
    int mid;
    if(low < high ){

        mid=(int)(high+low)/2;
        mergesort(a,temp,low,mid);
        mergesort(a,temp,mid+1,high);
        merge(a,temp,low,mid+1,high);
    }
}

void merge(int a[],int temp[],int left,int mid,int right)
{
    int i,left_end,size,temp_pos;
    left_end=mid-1;
    size=right-left+1;
    temp_pos=left;
    while((left <= left_end) && (mid<=right)){
        if(a[left]<=a[mid]){
            temp[temp_pos]=a[left];
            temp_pos=temp_pos+1;
            left=left+1;
        }
        else{
            temp[temp_pos]=a[mid];
            mid=mid+1;
            temp_pos=temp_pos+1;
        }
    }

    while(left<=left_end)
    {
        temp[temp_pos]=a[left];
        left=left+1;
        temp_pos=temp_pos+1;
    }

    while(mid<=right)
    {
        temp[temp_pos]=a[mid];
        mid=mid+1;
        temp_pos=temp_pos+1;
    }

    for(int i=0;i<=size;i++){
        a[right]=temp[right];
        right=right-1;
    }
}

int main(){
    int a[]={5,4,9,8,7,1,2,0,3,6};
    int temp[10];
    mergesort(a,temp,0,9);
    for(int i=0;i<=9;i++)
        cout<<a[i];
    return 0;
}
</code>```

Any suggestion regarding the same is appreciated i would love to know feedback regarding my approach .

Body:
Hi After thinking a bit i came across this solution and now i am feeling like i was avoiding a very basic concept.
SO i implement sorting through merger sort , which basically divides and sort and merger the array . we have tax is deducted for swaping two values but not for comparision .

so I used an alternate array temp in order to merge the values and then copy the value of the same into the original array my C++ code is something like this :

#include<iostream>

using namespace std;

void merge(int a[],int temp[],int left,int mid,int right);

void mergesort(int a[],int temp[],int low,int high)
{
    int mid;
    if(low < high ){

        mid=(int)(high+low)/2;
        mergesort(a,temp,low,mid);
        mergesort(a,temp,mid+1,high);
        merge(a,temp,low,mid+1,high);
    }
}

void merge(int a[],int temp[],int left,int mid,int right)
{
    int i,left_end,size,temp_pos;
    left_end=mid-1;
    size=right-left+1;
    temp_pos=left;
    while((left <= left_end) && (mid<=right)){
        if(a[left]<=a[mid]){
            temp[temp_pos]=a[left];
            temp_pos=temp_pos+1;
            left=left+1;
        }
        else{
            temp[temp_pos]=a[mid];
            mid=mid+1;
            temp_pos=temp_pos+1;
        }
    }

    while(left<=left_end)
    {
        temp[temp_pos]=a[left];
        left=left+1;
        temp_pos=temp_pos+1;
    }

    while(mid<=right)
    {
        temp[temp_pos]=a[mid];
        mid=mid+1;
        temp_pos=temp_pos+1;
    }

    for(int i=0;i<=size;i++){
        a[right]=temp[right];
        right=right-1;
    }
}

int main(){
    int a[]={5,4,9,8,7,1,2,0,3,6};
    int temp[10];
    mergesort(a,temp,0,9);
    for(int i=0;i<=9;i++)
        cout<<a[i];
    return 0;
}

Any suggestion regarding the same is appreciated i would love to know feedback regarding my approach .


答:
```<code> FooButtonClick.
</code>```

Start all method names, class names and properties with a capital letter.

But however which one you choose - be consistent with the choice. That's the best advice I can give.

Body:
 FooButtonClick.

Start all method names, class names and properties with a capital letter.

But however which one you choose - be consistent with the choice. That's the best advice I can give.


答:
The answer is in the language conventions for class library developers on MSDN.

That says that events should be PascalCase like everything else.  The exceptions are parameters and protected field instances and that's it.

Based on your example the name should be FooClick or FooButtonClick if the event source is FooButton.

The specification advises developers not to use Hungarian notation at all.


问:
In objective C, where does the inheritance chain end?
In objective C, classes are objects, but what object owns the class objects?

I am trying to get as detailed an understanding of iOS programming as I can, and this question popped into my head, so I decided I should know the answer.

答:
In objective C, classes are objects, but what object owns the class objects?

For an object to stay around it's not necessary to be owned by someone. They are just never released.

The runtime of course has pointers to all classes, so in a way you could argue class objects are owned by the runtime.

Where does the inheritance chain end?

The inheritance chain (or, rather, superclass chain) starts at the class of an instance and leads up the superclass and superclass's superclass...

It ends at the so called root class (there are several, like NSObject, NSProxy, and you can make your own). Objective-C has another complication: the class's class, called the "meta class". There's a meta class chain as well. See Greg Parker's diagram.

Does each instance of a class inherit pointers to all the other class objects?

No. Each instance has exactly one pointer to its class, the isa pointer.

Why am I able to send class objects messages? Are class objects global variables?

They are symbol references put into the executable by the compiler, a concept very similar to global variables. An @implementation defines the symbol.

You can send messages to classes because that's how the Objective-C syntax is defined.


问:
How to organize software document for the same application supporing both iOS and Android
I have to write software project documentation for an application which will support both iOS and Android. Each platform has its specific features and the mobile app design and requirements are almost the same.

At first, I thought to include all the requirements in one document by separating the platforms side-by-side.

However, why should android devs see the iOS dev part and vice-versa?

Should I write the document separately for each platform or include it in one document? Which one is good for QAs and for the overall professionalism of the software requirement specification ?

答:
Everyone documents a little different but I would say place it into separate documents. I say this because iOS and Android different platforms with different features. This all depends on your scope but scope of a project can change at any time. I feel like it'd would be a bit of a mess.

Let's say Android Dev's scope changes and for some reason now you'll need access to the Phone Contact's Content provider or maybe the addition of a widget? You make the change and ship out the document to all Devs. If I am a iOS Dev why is there a updated documentation telling me that that I'll need access to the Phone Contact's Content Provider(Which is something very android specific)? Or maybe you have to change a piece of your document because the iOS app store denied one of your development practices. The same thing applies and It's a bit confusing. Not to mention if you try to avoid this and decide to make a change in one platform and only update those devs of their change now your documentation is inconsistent and can lead to other problems.

I would assume you have two separate teams? They're writing in two different languages for different mobile application stores with their own rules and regulations as well. It would be simpler and easier to manage if they both had their own documentation.


答:
With your talk of developers and product owners, it seems to me that you have no middle person responsible for the features in your organisation.

Well, in my organisation, I am that person. I am the requirements engineer, the one who learned how to make good specifications and choose features which result in a high quality software with user friendly interaction design. (In other organisations it is the UX person who gets the same job, you might be more familiar with that term).

And I can tell you: Getting a good specification is hard. Of course, developers hate doing it. It is a burden to them - they are there to build a software, not to think about power plays among stakeholders and the mental models of lazy users. But you know what? It is a burden to product owners too. They don't know any better what features their software should contain than the developers or the users do. Creating a viable specification is a learned skill, and if you never learned it, you can't be good at it. Sure, there are lots of developers and product owners who can do it, because they had to do it in previous projects. But the average product owner or developer struggles with it, because it is naturally not their job to do it. Not everybody who can drive a car can design a car; similarly, not everybody who can use software can design a software interface.

Can you develop software without a requirements engineer? Sure you can. But putting the whole weight of the specification of it on the product owner's shoulders is not fair, and not good for the project result. Especially because he is faced with a task which is unusually hard for him, getting input and support from others is very helpful. If you are in such a situation, don't look at your poor product owner and say "tell me what to make for you and I will make you", he genuinely doesn't know what he needs. But a discussion with you will help him articulate his thoughts and explore his ideas.

When there is no requirements engineer in the project structure, there is another problem: there is no moderator. All the developers are on the technical side, all the product owners are on the business side. When the two cultures clash, conflicts can arise, with each side judging the other one stupid and unreasonable (because it uses its own value system to judge). So, do talk with your product owner about possible features, but be polite and patient even when you think he doesn't deserve it; the project success depends on how well you two can get along, and sometimes taking the suboptimal decision is better than taking no decision at all due to conflict. It might be helpful to establish a hierarchy and give one of you two the last word, as this prevents deadlocked conflicts. If he gets the last word, defer to it even if you feel it is unfair.

About the "passive" part: if you don't have ideas, don't try to come up with something just to show activity. If the product owner is already insecure and knows no good criteria for evaluating his or your ideas, strange ideas "just to have something" will make an already difficult situation even more difficult. Coming up with good feature ideas is not magic, but it requires knowledge. If you didn't learn it from textbooks, you will probably need some years of developer experience, especially in projects where you are exposed to users or user-generated usability data (analytics, satisfaction measurements) before your brain sorts out the patterns for itself and you begin to notice: there is a problem here we can solve. The users seem to be missing something on this page, what can it be? Then you will have good ideas to share.

Conclusion 1: In projects with no requirements engineer, it is good to make suggestions when you have them. Do it with sensitivity and tact - it is imperative to avoid conflict even if it means your good idea gets nipped in the bud.

And if you are on a team with a requirements engineer?

I love hearing feature ideas from everybody! Yes, sometimes the ideas of developers are terrible (when they want to make user interface follow programming logic). Ideas of product owners are also often terrible (when they want the sun and the moon on a shoestring budget - oh, and the user is supposed to enter pages of personal information in highest data quality, without getting anything in return). But it is my job to come up with a specification which is good for everybody on the team. And even if your idea is never going to work, hearing it makes me aware that you have a concern. You might have chosen the wrong solution to suggest, but this doesn't make your concern any less valid. If you spotted it, it probably needs to be addressed (or I need to come up with a reason why it is not a threat). If you have a requirements engineer responsible for the specification, don't ever hesitate to go to them with suggestions. If they don't hear you out, they are doing something wrong (note that "consider" doesn't mean "accept").

A requirements engineer has to view the project from the point of view of each stakeholder separately (and sometimes at the same time). We are only human, and we fail at it, often. If you are there to supply your true viewpoint, instead of the viewpoint we think you have, then your input is very valuable.

You can be more free in your behavior here. It is my job to do the sensitivity dance. Don't be openly aggressive, this hinders my work, but you need less self-control and cultural/communicational awareness, because I can take up the slack. You are also not floating, in a situation where there are two conflicting ideas and nobody can judge which is better. I am supposed to know that, and if it doesn't work out, it is my head in the noose.

Conclusion 2: If there is a requirements engineer on the team, go to them with product feature suggestions. You don't need velvet gloves this time.

And lastly, what if there is no requirements engineer, the product owner is overwhelmed and struggling for ideas, the boss is pointedly looking at you, and you have no ideas to offer?

You have a few options. The one is, as you mentioned, to quit. Not all organisations work that way, and if this environment is not suitable for you, find a better one. It will be good for you in the long term.

You can also wait and see if anything changes. The next project can have a more experienced product owner (or one with more leadership). But you can't stall forever.

The third option is to actually learn some requirements engineering by yourself. This is a skill highly sought these days. Even if you don't ever plan to take on positions where you are a full-time requirements engineer, having this skill enhances your value as a developer, as it lets you understand better other members on your team (and your users) and makes the development process go more smoothly. And you don't have to go into the whole depth of it. An entry level textbook which explains tasks, workflows, mental models and user-centered data models will already let you spot lots of improvement opportunities in a software designed by a team of businessmen and developers. Don't go for the thickest books meant as a reference for academics (like the recent Pohl translation to English) - they are more a list of all possible methods for each small step, without an explanation how to actually do them. Choose something practice-oriented.

If you try it and find that you have no personal interest in the area, that's still fine. Don't force yourself to do something you dislike. But you probably should be looking for a job in an organisation with a different team structure.

Conclusion 3: Instead of waiting for years to get an intuitive understanding, read a book or two and you will already have good ideas to supply


问:
Quality Assurance (Testing) in Scrum
I just had a Release Retrospective for my scrum team.  We talked a lot about our release process.

I pointed out that because our company is not able to tolerate bugs in our production environment we are not be able to adhere to the traditional scrum mantra of releasing often.

In short, we are a medical company.  Bugs in production can cause issues with patient care.  (A rapid fix release does not help the patient that was negatively impacted by the bug.)

I pointed out that scrum does not have a formal quality assurance process.  (It is assumed that testing will be done during development.)

I then stated that scrum has an implied expectation of bugs in production.  (Based on the process of releasing early and often.)  The Scrum Process people in the room said that scrum is not that way.  They said that properly done scrum can be bug free in production.

So here is my question:

How does testing and quality assurance work for scrum? (So that there is very low occurrence of bugs in production.)

OR

Is there documentation that bugs are expected to a small degree in Scrum (along with quick follow up releases)?

NOTE: This is for full enterprise level development. We have 6+ WCF services, several Service Buses, 4 databases, a WPF front end application and a Web Interface all written by two separate scrum teams of about 6-8 people each.  This means answers that include just coding it right the first time are not realistic.

NOTE II: I know that no software product is going to be bug free.  But our release process (non-agile) catches the few that get past our development process and brings our software fairly close to the "No Bugs" level.

答:
If you are practicing Test-Driven Development, scrum can be bug free, insofar as the software that you release to your V&V team fulfills all of the expectations set forth by your unit tests.

To put it another way, you may not be able to certify that your software is bug free, but you can certify that it passes all of its unit tests.  The unit tests are something that a supervisor or manager can sign off on.  It's not a medical-grade certification (you still need QA for that), but it does relieve your team of the burden of demonstrating a state of being bug free.

So instead of claiming bug-free software on each release (an assertion that is probably untrue), you demonstrate that the approved Unit Tests prove reliability within their agreed-upon scope.

You can also perform functional tests on the software before releasing it to QA.  QA can help you develop some or all of those tests.

Further Reading

http://en.wikipedia.org/wiki/Therac-25

The Therac 25 is an excellent case study because problems with the development process (and not several specific software bugs that were found) was cited as the primary reason for the failure.

Title: Quality Assurance (Testing) in Scrum