问:
PHP: Injecting the same database connection into multiple objects
Suppose that there are two classes that define objects of vastly different function such that in the datastore, the information they require is divided into two separate databases.

For example, the classes Employee and SteelExtruder may be placed in the databases `human_resources` and `capital` respectively. Rather than hard code the connections to their respective databases:

```<code>class Employee {
    protected $dbc;
    public function __construct() {
        $this->dbc = new mysqli('localhost', 'user', 'pass', 'human_resources');
    }
}
</code>```

I can see the advantages in flexibility that come from injecting the database connection into the constructor:

```<code>class Employee {
    protected $dbc;
    public function __construct(mysqli $dbc) {
        $this->dbc = $dbc;
    }
}
</code>```

However, I fail to see how to implement it properly. I have read that singletons and database class libraries are bad practice, since they merely mask the fact that they are really just global variables. On the other hand, the alternatives do not seem fantastic either:

A) Declare any necessary connections globally in a loader file. Functionally identical to a database library class, but smells worse:

```<code>loader.php:
$dbc_human_resources = new mysqli('localhost', 'user', 'pass', 'human_resources');
$dbc_capital = new mysqli('localhost', 'user', 'pass', 'capital');

index.php:
$employees = array(
    new Employee($dbc_human_resources),
    new Employee($dbc_human_resources),
    ...
    );
</code>```

B) Create a new connection every time a new object is created. Unless there is some sort of optimization I am not aware of, this seems carelessly inefficient.

```<code>$employees = array(
    new Employee(new mysqli('localhost', 'user', 'pass', 'human_resources')),
    new Employee(new mysqli('localhost', 'user', 'pass', 'human_resources')),
    ...
);
</code>```

C) Store all the objects into a library object that takes a single connection, which doesn't look so bad but feels wrong:

```<code>Employee.php:
class Employee {
    //non-database properties
    public function __construct($args = array()) {
        //non-database initialization
    }
}

EmployeeLibrary.php:
class EmployeeLibrary {
    protected $dbc, $employees;
    public function __construct(mysqli $dbc) {
        $this->dbc = $dbc;
    }
    public function add_new_employee($args) {
        array_push($this->employees, new Employee($args));
    }
    //do things with database connection
}

loader.php:
$employee_library = new EmployeeLibrary(new mysqli('localhost', 'user', 'pass', 'human_resources');

index.php:
$employee_library->add_new_employee(...);
$employee_library->add_new_employee(...);
</code>```

I am sure this isn't a rare problem. Is there an accepted way to do this?

答:
All three are wrong, because you are storing connection strings in source code. Source code is not the right place for configuration, because you are not expected to have to change your code (and so, do all the regression testing) every time your database moves or every time you move from development database to staging and to production database.

Instead:

Store the connection string in a configuration file.

Create a class which accesses configuration file options.

The class should provide the callers with the simple interface to those options; callers shouldn't care where the configuration file is or how options are stored inside.

This abstraction makes it possible later to switch from, for instance, a configuration stored in a JSON file, to a configuration stored in an XML file, or even move configuration to a database such as Redis.

Create an instance of this class every time you need to access the configuration options.

You don't need a singleton here; if one day, performance becomes an issue (that is, the time needed to open and parse the configuration file becomes prohibitive), use caching.

If you are absolutely sure (beware of YAGNI) that you'll have to move to a different storage mechanism soon (for example from JSON file to Redis), you may use Dependency Injection by creating the configuration object at the top of the stack, and then pass it to the callers. This will ensure that when moving to a different mechanism, you'll change no more than one line in your code base, replacing:

```<code>$configuration = new JsonFileAppConfiguration();
</code>```

by:

```<code>$configuration = new RedisAppConfiguration();
</code>```

but everything else will rely only on the interface IAppConfiguration that both those classes implement.

Body:
All three are wrong, because you are storing connection strings in source code. Source code is not the right place for configuration, because you are not expected to have to change your code (and so, do all the regression testing) every time your database moves or every time you move from development database to staging and to production database.

Instead:

Store the connection string in a configuration file.

Create a class which accesses configuration file options.

The class should provide the callers with the simple interface to those options; callers shouldn't care where the configuration file is or how options are stored inside.

This abstraction makes it possible later to switch from, for instance, a configuration stored in a JSON file, to a configuration stored in an XML file, or even move configuration to a database such as Redis.

Create an instance of this class every time you need to access the configuration options.

You don't need a singleton here; if one day, performance becomes an issue (that is, the time needed to open and parse the configuration file becomes prohibitive), use caching.

If you are absolutely sure (beware of YAGNI) that you'll have to move to a different storage mechanism soon (for example from JSON file to Redis), you may use Dependency Injection by creating the configuration object at the top of the stack, and then pass it to the callers. This will ensure that when moving to a different mechanism, you'll change no more than one line in your code base, replacing:

$configuration = new JsonFileAppConfiguration();

by:

$configuration = new RedisAppConfiguration();

but everything else will rely only on the interface IAppConfiguration that both those classes implement.


问:
Strategies to analyze collected exceptions
We want to add error feedback to our application. I had a look at existing solutions (e.g. raygun.io), but these work "in the cloud", which is a no-go for us:

most installations of our application are offline, so we will need to export the collected logs to a file and then send it per email.

I don't feel comfortable uploading exception details to a third party server because of privacy concerns. (some of our clients would probably kill us).

Now, just logging these exceptions is not that hard. I have attached handlers to AppDomain.UnhandledException and AppDomain.FirstChanceException and then write them out to a small SQLite DB.

But the question for me is how to best analyze them. Analyzing them by hand would cost too much time, so we need to at least be able to group them into "buckets" and order them by number of occurrences, etc.

I do have some ideas in mind where I compare callstacks and messages, etc, but I feel like someone else MUST have done the same already.

Do you know of good strategies to classify exceptions and group them?

答:
Collecting exceptions

When collecting exceptions, be careful with two things:

What will happen if an exception occurs, and while reporting it, the reporting mechanism throws another exception?

The worst case is to start reporting the new exception, which may trigger a new one, resulting in thousands of new exceptions thrown in a loop. You absolutely need to avoid that.

What if you can't report an exception?

Sending an exception to a server may fail because the server is not responding. Storing an exception to Windows Events may fail because of the lack of permissions. Saving the exception to a local database may fail because the database is, for some reason, down. Even appending the exception to a text file can be problematic: you may simply be out of space or lack the permissions.

Usually, you need to have two or three ways to log the exceptions, doing a fallback from the one which failed to the one which should be more reliable (say report to a server; database; simple text file).

It is essential, once the original problem which prevented the exceptions from being logged properly is solved, to be able to retrieve the exceptions from all those sources and to analyze them carefully. For example, how do you collect the exceptions which were stored in a text file when both the network and the database were down?

When it comes to sensitive data, be sure to encrypt the exceptions when sending them to a third-party server (or even your servers), in order to prevent access to stack trace to unauthorized persons. Make sure that developers never include sensitive information in the messages of the exceptions. For instance, AccessDeniedException shouldn't have as message:

Failed to authenticate the user John: the password "sihjdfogdhf" is invalid.

Among the information you collect, make sure you have:

The exact version of the application. If you don't have the version, debugging an exception may quickly become a nightmare.

The information about the environment. An application which throws an exception on Windows XP won't necessarily throw it on Windows 8.1. An application which throws an exception with FAT32 system may work well with NTFS. An application may behave strangely because there is less than 1 MB of disk space left, or because the RAM is full and the OS has to swap everything, leading to slow response rates and lots of timeout exceptions.

Something which identifies the customer (if appropriate). This makes it possible to contact the customer to ask for more information.

Analyzing exceptions

The most important step is to deduplicate information about the exceptions you collect. Many exceptions will be similar, but not identical: it is crucial to identify how close they are and to group them. The goal is to be able to focus on exceptions which are the most frequent: if you have an exception which affected one user twice for the past year, and an exception which affected thousands of users thousands of times for the same period of time, the first exception may not be your top priority.

You probably won't get the grouping right from scratch; instead, study the exceptions you already gathered, try a grouping approach and see how it's working, then modify it until you get what you need. The grouping is tricky, because there are practically no absolute duplicates, and because the gap between what makes it a duplicate and what doesn't is fuzzy.

For instance:

If you receive two AccessDeniedExceptions reported at login window button OnClick event, one concerning John, another one concerning Mary, those may be grouped, despite the different message strings.

On the other hand, there may be another AccessDeniedException concerning Mary which happens somewhere else in the application, and which shouldn't be grouped with the first two.

Now there is an AccessDeniedException thrown by a different revision of your app: the stack trace is different, but the exception is still the same than the first two.

etc.

When grouping, make sure you keep the individual information as well. For example, the report may tell that there were 94 AccessDeniedExceptions thrown for the past day for users John, Mary and 14 others in versions 4.0.17 and 4.0.18 with the given stack traces by customers 1, 2, 3 and 4.

ContentLicense: CC BY-SA 3.0


问:
What problem do algebraic data types solve?
Fair warning, I'm new to functional programming so I may hold many bad assumptions.

I've been learning about algebraic types. Many functional languages seem to have them, and they are fairly useful in conjunction with pattern matching. However, what problem do they actually solve? I can implement a seemingly (sort-of) algebraic type in C# like this:

```<code>public abstract class Option { }
public class None : Option { }
public class Some<T> : Option
{
    public T Value { get; set; }
}

var result = GetSomeValue();
if(result is None)
{
}
else
{
}
</code>```

But I think most would agree this is a bastardization of object oriented programming, and you shouldn't ever do it. So does functional programming just add a cleaner syntax that makes this style of programming seem less gross? What else am I missing?

答:
Classes with interfaces and inheritance present an open world: Anyone can add a new kind of data. For a given interface, there may be classes implementing it all over the world, in different files, in different projects, at different companies. They make it easy to add cases to the data structures, but because the implementations of the interface are decentralized, it is hard to add a new method to the interface. Once an interface is public, it is basically frozen. Nobody knows all the possible implementations.

Algebraic data types are the dual to that, they are closed. All the cases of the data are listed in one place and operations not only can list the variants exhaustively, they are encouraged to do so. Consequently writing a new function operating on an algebraic data type is trivial: Just write the damn function. In return, adding new cases is complicated because you need to go over basically the entire code base and extend every match. Similar to the situation with interfaces, in the Rust standard library, adding a new variant is a breaking change (for public types).

These are two sides of the expression problem. Algebraic data types are an incomplete solution to them, but so is OOP. Both have advantages depending on how many cases of data there are, how often those cases change, and how frequently the operations are extended or changed. (Which is why many modern languages provide both, or something similar, or go straight for more powerful and more complicated mechanisms that try to subsume both approaches.)


答:
So does functional programming just add a cleaner syntax that makes this style of programming seem less gross?

That is a simplification perhaps, but yes.

What else am I missing?

Let's be clear on what algebraic data types are (summarizing this fine link from Learn you as Haskell):

A sum type that says "this value can be an A or a B".

A product type that says "this value is both an A and a B".

your example only really works with the first.

What you're perhaps missing is that by providing these two basic operations, functional languages let you build everything else. C# has structs, classes, enums, generics on top of those, and piles of rules to govern how these things behave.

Combined with some syntax to help, the functional languages can decompose operations down to these two paths, providing a clean, simple and elegant approach to types.

What problem do algebraic data types solve?

They solve the same problem as any other type system: "what values are legal to use here?" - they just take a different approach to it.

Body:
Fair warning, I'm new to functional programming so I may hold many bad assumptions.

I've been learning about algebraic types. Many functional languages seem to have them, and they are fairly useful in conjunction with pattern matching. However, what problem do they actually solve? I can implement a seemingly (sort-of) algebraic type in C# like this:

```<code>public abstract class Option { }
public class None : Option { }
public class Some<T> : Option
{
    public T Value { get; set; }
}

var result = GetSomeValue();
if(result is None)
{
}
else
{
}
</code>```

But I think most would agree this is a bastardization of object oriented programming, and you shouldn't ever do it. So does functional programming just add a cleaner syntax that makes this style of programming seem less gross? What else am I missing?


问:
How do you pass/fail performance tests?

Example:

A certain test is run five times on the current build, to compare it to release 1.0, where the same test was also run five times.

Build 1.4

22 ms, 26 ms, 23 ms, 25 ms, 20 ms

Release 1.0

15 ms, 18 ms, 16 ms, 20 ms, 17 ms

Question

The requirement is that Build 1.4 is no worse than Release 1.0.

How would I test that? I've seen different methods used, including simple average comparison and statistical T-Tests (assuming normal distributions).

None of the tools, i.e. testing frameworks and CI systems, I've come across provide anything to help with calculating and passing/failing such tests. Why? Performance testing seems to be popular, so how are people approving or rejecting them?

Often it's way too impractical or even impossible to go in and manually determine acceptable ranges or distributions for every test.

答:
I can't promise that this is optimal, only that it's how I have been handling performance tests with moderate success.

Fairly substantial "real-world" integration tests get run under a timer, N repeats per test. Stash the results in a database. Periodically a set of results gets tagged as a waterline and subsequent runs are compared to that one, e.g. for a release, or when the testing hardware changes, or when we've implemented something cunning and everything runs faster.

The magic number used for comparison is the minimum of the results set. A fail occurs if it is greater than some fixed number (half a second or so) and is more than k% slower than the current waterline.

The minimum time seems to be pretty stable, but because the performance tests are run on a windows machine the worst case time jumps all over the shop. Periodically the test run collides with an antivirus scan or windows updates for instance. There's consequently an automated retry failed tests step which runs at the end to try to cut out some difficult to reproduce failures.

The manual tuning involved in the k% and the fixed time is unfortunate. I suspect a stronger solution involves looking for statistically significant trends and triggering a failure based on a probabilistic metric. Still, the above is simple yet still catches performance regressions.

Title: How do you pass/fail performance tests?


问:
DDD Architecture in a MVC web application
I am putting together a web application using DDD however am strugleing to put the text book DDD model into a real world MVC application.

I currently have these layers:

Controllers > ViewModelsBuilders > Domain Services > Aggregates, Remote API's and Repositories

Controllers

The action results need a view model

ViewModelsBuilder

These build the view model needed from a set of Domain Services.

Domain Services

These are the entry point to my domain and use Aggregates (for complex domain logic) passing in data from Remote API's and Repositories

Aggregates and Entities

These are all limited to the scope of the assembly and contain the business logic

Questions:

Is this the correct structure, should it be the domain services or the view model builders pulling everything together?

The objects returned from the Domain Services should these be simple DTO or the actual entities, hiding the methods with access levels?

Should the Domain services be the gatekeeper or should the view model builders access the aggregate root, repositories etc?

答:
The approach that I have used in the past that can be applied in MVC & WebAPI projects follows:

End Point (Controllers, ApiController) return ViewModels (DTOs)

Business Layer / Application Layer / Domain Service - return application data

Data Access Layer - Repository Pattern - returns DB Model Entities

Each layer is responsible for its own data.


问:
Is it possible to avoid abstraction inversion in this scenario?
I'm designing a library built on web scraping that tries to provide an API to a popular news site. I am representing each of its articles as a collection of 'elements' (IElement), such as images, videos, blocks of text, soundtracks, etc. The problem is, I can't think of anything each 'element' has in common.

Text? Nope, images (and videos, and soundtracks) don't have text.

A URL to access the file? Nope; while I will be visiting a remote URL to access an image or a video (since it's not practical to pass those around), I don't need to go to a URL to get the text (I can just pass it as a string).

The only thing I can think of is having a member that describes what type the element is, but that could potentially lead to a very unintuitive API. I don't want my API to end up looking like this:

```<code>// API code
enum ElementType
{
    Text, Hyperlink, Image, Video, Soundtrack
}

interface IArticle
{
    IEnumerable<IElement> Contents { get; }
}

interface IElement
{
    ElementType Type { get; }
}

class TextElement : IElement { /*details*/ }
class ImageElement : IElement { /*details*/ }

// .. and so on

// Usage in app code
foreach (var element in article.Contents)
{
    switch (element.Type)
    {
        case ElementType.Text:
            RenderText(((TextElement)element).Text);
            break;
        case ElementType.Image:
            DisplayImage(GetImageFromUri(((ImageElement)element).ImageUri));
            break;
        // and so on
    }
}
</code>```

As you can see, a lot of verbosity is added in this scenario because the user has to 1) switch on the element's type, 2) check for each ElementType, and then 3) downcast it to use implementation-specific features.

Is there an alternative to messy runtime type checking / downcasting in this scenario? How do other client apps (i.e. Facebook / Twitter clients) handle this kind of problem?

答:
Use OOP, if you can.  When you call an interface method or a base class method that is overridden, the language will cast the object to the implementing type and provide it as the this pointer.  You won't need casting or a switch statement.

In this case, you might have a method like public void DoIt (), which is implemented in each class differently.  The code in your switch cases moves into the specific subtypes' implementation of DoIt ()


问:
Shipping test code. Why wouldn't you?
I would like to ship test code alongside a product. Specifically, provide an option so that anyone with a copy of our program can hit a "self-test" button or pass --self-test on the command line and run through the complete suite of unit | integration tests.

I mostly want to do this to help debug problems discovered in the field, so when a bug report is incoming from an end user there's a chance of it being supported by "and also, these three tests failed on my machine". I'd like manual testers to be able to run the unit | integration tests as well.

However, the test of the team believes that test code is not production code and therefore shall not be shipped. I don't really get this argument, since most open source projects ship a test suite. It does seem to be unusual in closed software.

I would like supporting evidence or anecdotes for either side of the argument. I've taken my best guess at which stack exchange site would be most appropriate, but please let me know if this is out of place.

答:
Sometimes test code contains snippets of code from third parties, both external and internal to your company.  This happens as users file bugs; your tests (such as regression tests) then incorporate the code supplied by them to reproduce.  Often, the licensing of such code snippets to reproduce bugs is unclear.  So, you should be aware of intellectual property issues.  You don't want to ship test code that accidentally reveals some trade secrets or intellectual property of a different department of your company, or of your external partners either.

On another note, test code is rarely held to production code standards: code reviews aren't necessarily done; coding standards not enforced, etc..  This is unfortunate, yet commonplace, and should not necessarily a reflect poorly on the test team if they didn't have that goal in place at the time these tests were developed.

On the other hand, many tests are simply embarrassingly bad, and don't even test what some think is being test.  That is different issue...

Ultimately, because of all these factors, you might want to classify your tests as those that can be shipped as open source, and those that simply can't.  (You may want to write some custom tests with shipping them in mind, slowly migrating the others into that set.)

Title: Shipping test code. Why wouldn't you?


问:
Drawing concentric circles without gaps
I want to fill a circle with alternate colors like a lollipop by drawing circumferences of increasing radius on a Cell matrix. I am currently using the Midpoint circle algorithm to get the points. The problem I have is that there are some gaps when filling a circle this way.

In the example below (original is number 1) I used pink and white to highlight the various circumferences. (Notice the black pixels)

The code of my implementation (1) is here: https://gist.github.com/beppe9000/e4a29542a76b8ee3b47f

I am looking for an algorithm that does not produce such gaps.

Update

It is important that the circle is filled using concentric passes because i also update some metadata in the cells as I get them in groups (each one corresponding to a circumference). I tried simplifying the problem, so you didn't get it all, I'm sorry if I'm not a great communicator... ;)

Basically I need the circumferences produced to be perfectly contiguous. That means no gaps between circles of radius n and n+1

Update 2

I tried the brute-force algorithm with some results, still lacking the ability to get individual circumferences. In particular I had great hopes for number 3...

答:
The midpoint algorithm gives you the set of points lying "exactely" a given distance from the center.

What you would want to do is to use another algorithm where you test if the distance is lower than (and not equal to) the radius.

The brute force algorithm would be to check every cell in the grid, but if you really want to be efficient, you could perform neighbourhood testing (similar to the midpoint algorithm) and perform some sort of line scan starting from the top (x_start = x_radius; y_start = y_radius + radius).

An example in pseudo-code:

```<code>foreach i in i_range:
    foreach j in j_range:
        y = i - ry
        x = j - rx
        if (x^2 + y^2)^0.5 - 0:
           paint_cell(i,j)
</code>```

Title: Drawing concentric circles without gaps

Body:
The midpoint algorithm gives you the set of points lying "exactely" a given distance from the center.

What you would want to do is to use another algorithm where you test if the distance is lower than (and not equal to) the radius.

The brute force algorithm would be to check every cell in the grid, but if you really want to be efficient, you could perform neighbourhood testing (similar to the midpoint algorithm) and perform some sort of line scan starting from the top (x_start = x_radius; y_start = y_radius + radius).

An example in pseudo-code:

foreach i in i_range:
    foreach j in j_range:
        y = i - ry
        x = j - rx
        if (x^2 + y^2)^0.5 - 0:
           paint_cell(i,j)


答:
Not exactly what you asked but I think just a vertical scan is easier:

```<code>line((x_center-r,y_center)-(x_center+r,y_center))
for(y=y_center+1;y_center+r;y++) {
    w=sqrt((r+y)(r-y))
    x_min=x_center-w
    x_max=x_center+w
    y_mirror=2*y_center-y
    line((x_min,y)-(x_max,y))
    line((x_min,y_mirror)-(x_max,y_mirror))
}
</code>```

So if a circle in your screen has 101 pixels diameter, it will require the calculation of 50 square roots and drawing 101 horizontal lines (there are 2 lines of each length).

Title: Drawing concentric circles without gaps

Body:
I want to fill a circle with alternate colors like a lollipop by drawing circumferences of increasing radius on a Cell matrix. I am currently using the Midpoint circle algorithm to get the points. The problem I have is that there are some gaps when filling a circle this way.

In the example below (original is number 1) I used pink and white to highlight the various circumferences. (Notice the black pixels)

The code of my implementation (1) is here: https://gist.github.com/beppe9000/e4a29542a76b8ee3b47f

I am looking for an algorithm that does not produce such gaps.

Update

It is important that the circle is filled using concentric passes because i also update some metadata in the cells as I get them in groups (each one corresponding to a circumference). I tried simplifying the problem, so you didn't get it all, I'm sorry if I'm not a great communicator... ;)

Basically I need the circumferences produced to be perfectly contiguous. That means no gaps between circles of radius n and n+1

Update 2

I tried the brute-force algorithm with some results, still lacking the ability to get individual circumferences. In particular I had great hopes for number 3...

Body:
Not exactly what you asked but I think just a vertical scan is easier:

line((x_center-r,y_center)-(x_center+r,y_center))
for(y=y_center+1;y_center+r;y++) {
    w=sqrt((r+y)(r-y))
    x_min=x_center-w
    x_max=x_center+w
    y_mirror=2*y_center-y
    line((x_min,y)-(x_max,y))
    line((x_min,y_mirror)-(x_max,y_mirror))
}

So if a circle in your screen has 101 pixels diameter, it will require the calculation of 50 square roots and drawing 101 horizontal lines (there are 2 lines of each length).


答:
Part of your problem is that you are trying to reinvent the HTML document object model. Unless the content needs some special processing, it would be better to supply HTML fragments.

The type switch can be eliminated by using the visitor pattern: we define a visitor interface IElementVisitor that lists all cases, and add a void Accept(IElementVisitor) method to the IElement interface that will be implemented in each concrete type as

```<code>void Accept(IElementVisitor v) {
  v.visit(this);
}
</code>```

Then, a RenderVisitor would look like

```<code>class RenderVisitor : IElementVisitor {
  void Render(IElement e) { e.Accept(this); }
  void Visit(TextElement e) {
    RenderText(e);
  }
  void Visit(ImageElement e) {
    RenderImage(e)
  }
  ...
}
</code>```

Instead of the switch, we would now have new RenderVisitor().Render(element);.

Title: Is it possible to avoid abstraction inversion in this scenario?

Body:
I'm designing a library built on web scraping that tries to provide an API to a popular news site. I am representing each of its articles as a collection of 'elements' (IElement), such as images, videos, blocks of text, soundtracks, etc. The problem is, I can't think of anything each 'element' has in common.

Text? Nope, images (and videos, and soundtracks) don't have text.

A URL to access the file? Nope; while I will be visiting a remote URL to access an image or a video (since it's not practical to pass those around), I don't need to go to a URL to get the text (I can just pass it as a string).

The only thing I can think of is having a member that describes what type the element is, but that could potentially lead to a very unintuitive API. I don't want my API to end up looking like this:

```<code>// API code
enum ElementType
{
    Text, Hyperlink, Image, Video, Soundtrack
}

interface IArticle
{
    IEnumerable<IElement> Contents { get; }
}

interface IElement
{
    ElementType Type { get; }
}

class TextElement : IElement { /*details*/ }
class ImageElement : IElement { /*details*/ }

// .. and so on

// Usage in app code
foreach (var element in article.Contents)
{
    switch (element.Type)
    {
        case ElementType.Text:
            RenderText(((TextElement)element).Text);
            break;
        case ElementType.Image:
            DisplayImage(GetImageFromUri(((ImageElement)element).ImageUri));
            break;
        // and so on
    }
}
</code>```

As you can see, a lot of verbosity is added in this scenario because the user has to 1) switch on the element's type, 2) check for each ElementType, and then 3) downcast it to use implementation-specific features.

Is there an alternative to messy runtime type checking / downcasting in this scenario? How do other client apps (i.e. Facebook / Twitter clients) handle this kind of problem?

Body:
Part of your problem is that you are trying to reinvent the HTML document object model. Unless the content needs some special processing, it would be better to supply HTML fragments.

The type switch can be eliminated by using the visitor pattern: we define a visitor interface IElementVisitor that lists all cases, and add a void Accept(IElementVisitor) method to the IElement interface that will be implemented in each concrete type as

void Accept(IElementVisitor v) {
  v.visit(this);
}

Then, a RenderVisitor would look like

class RenderVisitor : IElementVisitor {
  void Render(IElement e) { e.Accept(this); }
  void Visit(TextElement e) {
    RenderText(e);
  }
  void Visit(ImageElement e) {
    RenderImage(e)
  }
  ...
}

Instead of the switch, we would now have new RenderVisitor().Render(element);.


问:
Simple and clean way of comparing three numbers
I've got some code that has a sequence of ifs that work, but just feel messy. Basically, I want to choose the largest of three integers and set a status flag to say which was chosen. My current code looks like this:

```<code>a = countAs();
b = countBs();
c = countCs();

if (a > b && a > c)
    status = MOSTLY_A;
else if (b > a && b > c)
    status = MOSTLY_B;
else if (c > a && c > b)
    status = MOSTLY_C;
else
    status = DONT_KNOW;
</code>```

This pattern occurs a few times, and with long variable names it gets a little difficult to visually confirm that each if is correct. I feel there might be a better and clearer way to do this; can anyone suggest anything?

There are some potential duplicates, but they don't quite align with this question.

In the suggested duplicate:   Approaches to checking multiple conditions?  all of the suggested solutions seem equally clumsy as the original code, so they do not provide a better solution.

And this post Elegant ways to handle if(if else) else deals only with nesting levels and asymmetry, which is not the problem here.

答:
You probably should use a macro or a function MAX  giving the maximum of two numbers.

Then you just want:

```<code> status = MAX(a,MAX(b,c));
</code>```

You might have defined

```<code> #define MAX(X,Y) (((X)>(Y))?(X):(Y))
</code>```

but be cautious -notably about side effects- when using macros (since MAX(i++,j--)  would behave strangely)

So better define a function

```<code> static inline int max2ints(int x, int y) {
    return (x>y)?x:y;
 }
</code>```

and use it (or at least #define MAX(X,Y) max2ints((X),(Y)) ....)

If you need to understand the origin of the MAX you might have a long macro like
#define COMPUTE_MAX_WITH_CAUSE(Status,Result,X,Y,Z)  which is a long do{ ... }while(0)  macro, perhaps

```<code>#define COMPUTE_MAX_WITH_CAUSE(Status,Result,X,Y,Z) do { \
  int x= (X), y= (Y), z=(Z); \
  if (x > y && y > z) \
    { Status = MOSTLY_FIRST; Result = x; } \
  else if (y > x && y > z) \
    { Status = MOSTLY_SECOND; Result = y; } \
  else if (z > x && z > y) \
    { Status = MOSTLY_THIRD; Result = z; } \
  /* etc */ \
  else { Status = UNKNOWN; Result = ... } \
} while(0)
</code>```

Then you could invoke COMPUTE_MAX_WITH_CAUSE(status,res,a,b,c)  at several places. It is a bit ugly. I defined local variables x, y, z  to lower bad side effects....

Body:
You probably should use a macro or a function MAX  giving the maximum of two numbers.

Then you just want:

 status = MAX(a,MAX(b,c));

You might have defined

 #define MAX(X,Y) (((X)>(Y))?(X):(Y))

but be cautious -notably about side effects- when using macros (since MAX(i++,j--)  would behave strangely)

So better define a function

 static inline int max2ints(int x, int y) {
    return (x>y)?x:y;
 }

and use it (or at least #define MAX(X,Y) max2ints((X),(Y)) ....)

If you need to understand the origin of the MAX you might have a long macro like
#define COMPUTE_MAX_WITH_CAUSE(Status,Result,X,Y,Z)  which is a long do{ ... }while(0)  macro, perhaps

#define COMPUTE_MAX_WITH_CAUSE(Status,Result,X,Y,Z) do { \
  int x= (X), y= (Y), z=(Z); \
  if (x > y && y > z) \
    { Status = MOSTLY_FIRST; Result = x; } \
  else if (y > x && y > z) \
    { Status = MOSTLY_SECOND; Result = y; } \
  else if (z > x && z > y) \
    { Status = MOSTLY_THIRD; Result = z; } \
  /* etc */ \
  else { Status = UNKNOWN; Result = ... } \
} while(0)

Then you could invoke COMPUTE_MAX_WITH_CAUSE(status,res,a,b,c)  at several places. It is a bit ugly. I defined local variables x, y, z  to lower bad side effects....


答:
@msw told you to use an array instead of a,b,c, and @Basile told you refactor the "max" logic into a function. Combining these two ideas leads to

```<code>val[0] = countAs();    // in the real code, one should probably define
val[1] = countBs();    // some enum for the indexes 0,1,2 here
val[2] = countCs();

 int result[]={DONT_KNOW, MOSTLY_A, MOSTLY_B, MOSTLY_C};
</code>```

then provide a function which calculates the max index of an arbitrary array:

```<code>// returns the index of the strict maximum, and -1 when the maximum is not strict
int FindStrictMaxIndex(int *values,int arraysize)
{
    int maxVal=INT_MIN;
    int maxIndex=-1;
    for(int i=0;i<arraysize;++i)
    {
       if(values[i]>maxVal)
       {
         maxVal=values[i];
         maxIndex=i;
       }
       else if (values[i]==maxVal)
       {
         maxIndex=-1;
       }
    }
    return maxIndex;
}
</code>```

and call it like

```<code> return result[FindStrictMaxIndex(val,3)+1];
</code>```

The total number of LOC seems to have increased over the original one, but now you have the core logic in a reusable function, and if you can reuse the function multiple times, it starts to pay off. Moreover, the FindStrictMaxIndex function is not interwoven with your "business requirements" any more (separation of concerns), thus the risk you will have to modify it later is much lower than in your original version (open-closed principle). For example, that function will not have to be changed even if the number of arguments changes, or need to use other return values than MOSTLY_ABC, or you are processing other variables than a,b,c. Moreover, the use of an array instead of 3 different values a, b, c might simplify your code in other places as well.

Of course, if in your whole program there are only one or two places for calling this function, and you do not have any further applications for holding the values in an array, then I would probably leave the original code as it is (or use @coredump's improvement).

Title: Simple and clean way of comparing three numbers

Body:
I've got some code that has a sequence of ifs that work, but just feel messy. Basically, I want to choose the largest of three integers and set a status flag to say which was chosen. My current code looks like this:

```<code>a = countAs();
b = countBs();
c = countCs();

if (a > b && a > c)
    status = MOSTLY_A;
else if (b > a && b > c)
    status = MOSTLY_B;
else if (c > a && c > b)
    status = MOSTLY_C;
else
    status = DONT_KNOW;
</code>```

This pattern occurs a few times, and with long variable names it gets a little difficult to visually confirm that each if is correct. I feel there might be a better and clearer way to do this; can anyone suggest anything?

There are some potential duplicates, but they don't quite align with this question.

In the suggested duplicate:   Approaches to checking multiple conditions?  all of the suggested solutions seem equally clumsy as the original code, so they do not provide a better solution.

And this post Elegant ways to handle if(if else) else deals only with nesting levels and asymmetry, which is not the problem here.

Body:
@msw told you to use an array instead of a,b,c, and @Basile told you refactor the "max" logic into a function. Combining these two ideas leads to

val[0] = countAs();    // in the real code, one should probably define
val[1] = countBs();    // some enum for the indexes 0,1,2 here
val[2] = countCs();

 int result[]={DONT_KNOW, MOSTLY_A, MOSTLY_B, MOSTLY_C};

then provide a function which calculates the max index of an arbitrary array:

// returns the index of the strict maximum, and -1 when the maximum is not strict
int FindStrictMaxIndex(int *values,int arraysize)
{
    int maxVal=INT_MIN;
    int maxIndex=-1;
    for(int i=0;i<arraysize;++i)
    {
       if(values[i]>maxVal)
       {
         maxVal=values[i];
         maxIndex=i;
       }
       else if (values[i]==maxVal)
       {
         maxIndex=-1;
       }
    }
    return maxIndex;
}

and call it like

 return result[FindStrictMaxIndex(val,3)+1];

The total number of LOC seems to have increased over the original one, but now you have the core logic in a reusable function, and if you can reuse the function multiple times, it starts to pay off. Moreover, the FindStrictMaxIndex function is not interwoven with your "business requirements" any more (separation of concerns), thus the risk you will have to modify it later is much lower than in your original version (open-closed principle). For example, that function will not have to be changed even if the number of arguments changes, or need to use other return values than MOSTLY_ABC, or you are processing other variables than a,b,c. Moreover, the use of an array instead of 3 different values a, b, c might simplify your code in other places as well.

Of course, if in your whole program there are only one or two places for calling this function, and you do not have any further applications for holding the values in an array, then I would probably leave the original code as it is (or use @coredump's improvement).


问:
REST API - Updating a Variable
If you are updating a variable in a RESTful API, for example person's weight, how should this be laid out?

What I have thought of:

PUT /person/1/weight?weight=150

PUT /person/1/weight

{"weight": 150}

PUT /person/1/weight

150

There's been a few answers on this but I don't feel like it's been answered in a clear, solid way.

答:
Since you are updating just part of the resource you should consider using PATCH HTTP method.

Request format depends on your other API calls. Prefer consistency. If you use JSON elsewhere use JSON. Same goes for XML or whatever language you use.

I suggest using JSON, but I don't know how complex your API is.

Do, I'd do this:

```<code>PATCH person/1
Content-Type: application/json

{"weight": 150}
</code>```

Title: REST API - Updating a Variable

Body:
Since you are updating just part of the resource you should consider using PATCH HTTP method.

Request format depends on your other API calls. Prefer consistency. If you use JSON elsewhere use JSON. Same goes for XML or whatever language you use.

I suggest using JSON, but I don't know how complex your API is.

Do, I'd do this:

PATCH person/1
Content-Type: application/json

{"weight": 150}


问:
Naming convention for getting the primitive backing a type?
I have a class that is backed by a double value, and I am wondering about accessor method names that preserve abstraction. Based on my experience in Java, there seems to be at least two precedents:

toDouble(), which mirrors toString()

doubleValue(), similar to Double.doubleValue() and BigInteger.doubleValue()

I need access to this value to perform some computations. Would it be most appropriate to return a double value as I've mentioned, or provide public multiply(), add(), etc. methods?

Is there any common practice or precedent for a class used in this way?

答:
Let's tackle this:

Would it be most appropriate to return a double value as I've mentioned, or provide public multiply(), add(), etc. methods?

Should said class know how to multiply and add? Sounds like you are building a calculator implementation... I would say it really depends on which part of the calculator you are building this for. If this is the 'engine', then giving the class multiply() and add() methods may be feasible. If this is only representing part of the user input (e.g. a Value instance that wraps the String keyboard input of "2", only to return 2 as a number for calculation later), then maybe you want to defer such operations to the 'engine'.


答:
The most simple approach I can think of is: start with a fully filled circle in pink, and (use @Mandrill's answer for example), and draw only the white circles afterwards over the pink circle, using your existing Midpoint algorithm. That will leave no black spots, all the black spots get the color you started with.

However, if you do not want to draw anything twice, here is an idea how to approach this:

draw the "circumferences" in the order of increasing radius

modify the midpoint algorithm the following way: whenever you set a cell in the left half of your circle to a specific color, test if there are black spots next to the right of that cell, in the same row. If that is the case, fill them with the current color, too, until you reach a non-black spot or the middle column. Do the same if you are coloring a cell in the right half, but for those cells fill the black spots to the left in the current row.

For example:

The advantage of this approach is that your "intermediate circles" always fulfill your requirements, not just the final result. And the "black spots" are not filled all with the the same "preferred color", but you get a more evenly distributed ratio of white-to-pink. The running time is still proportional to number of colored cells.

This can be easily modified to create an algorithm which produces the coordinates of "circumference" of a specific radius in any order you like. Create a function

```<code>  IEnumerable<Point> MidpointCircle(int radius,Point center){...}
</code>```

Then use it like this way (rough outline in C#, beware, air code):

  IEnumerable<Point> Circumference(int radius,Point center)
  {
       if(radius==0)
          yield break;
       var points = MidpointCircle(radius,center);
       var innerPoints =new Hashset(MidpointCircle(radius-1,center));
       foreach(var p in points)
       {
            yield return p;
            if(p.X<center.X)
            {
               Point q = new Point(p.X+1,p.Y);
               while(q.X<center.X && !innerPoints.Contain(q))
               {
                  yield return q;
                  q = new Point(p.X+1,p.Y);
               }
            }
            else
            {
               // similar code for points right from the center
            }
       }
  }
```

This should produce you the result you are looking for.

Title: Drawing concentric circles without gaps

Body:
The most simple approach I can think of is: start with a fully filled circle in pink, and (use @Mandrill's answer for example), and draw only the white circles afterwards over the pink circle, using your existing Midpoint algorithm. That will leave no black spots, all the black spots get the color you started with.

However, if you do not want to draw anything twice, here is an idea how to approach this:

draw the "circumferences" in the order of increasing radius

modify the midpoint algorithm the following way: whenever you set a cell in the left half of your circle to a specific color, test if there are black spots next to the right of that cell, in the same row. If that is the case, fill them with the current color, too, until you reach a non-black spot or the middle column. Do the same if you are coloring a cell in the right half, but for those cells fill the black spots to the left in the current row.

For example:

The advantage of this approach is that your "intermediate circles" always fulfill your requirements, not just the final result. And the "black spots" are not filled all with the the same "preferred color", but you get a more evenly distributed ratio of white-to-pink. The running time is still proportional to number of colored cells.

This can be easily modified to create an algorithm which produces the coordinates of "circumference" of a specific radius in any order you like. Create a function

  IEnumerable<Point> MidpointCircle(int radius,Point center){...}

Then use it like this way (rough outline in C#, beware, air code):

  IEnumerable<Point> Circumference(int radius,Point center)
  {
       if(radius==0)
          yield break;
       var points = MidpointCircle(radius,center);
       var innerPoints =new Hashset(MidpointCircle(radius-1,center));
       foreach(var p in points)
       {
            yield return p;
            if(p.X<center.X)
            {
               Point q = new Point(p.X+1,p.Y);
               while(q.X<center.X && !innerPoints.Contain(q))
               {
                  yield return q;
                  q = new Point(p.X+1,p.Y);
               }
            }
            else
            {
               // similar code for points right from the center
            }
       }
  }

This should produce you the result you are looking for.


答:
Shipping tests? Yes.
Shipping Unit tests? No.

As you say in the comment, problem you may face when running the product on a client computer will include problems such as linking with the wrong dll, generally this is not something a unit test will catch (which will no doubt have mocked the dll out to test the code).

Now, shipping an integration test suite, that calls the UI that calls the logic that calls the dll... that will work much better. Integration tests can show other aspects of failed installations that unit tests would not show up. (eg my current product requires an installation of k-lite codecs, which we are not allowed to bundle due to licensing. Unit tests may show our code working fine, but still not working to the customers satisfaction. Similarly, our configuration of the codecs may not have worked correctly, unit tests would also not show that up).

So - ship some of your integration tests instead, which would be exactly what you want for a installed, integrated, product.

Title: Shipping test code. Why wouldn't you?

Body:
I would like to ship test code alongside a product. Specifically, provide an option so that anyone with a copy of our program can hit a "self-test" button or pass --self-test on the command line and run through the complete suite of unit | integration tests.

I mostly want to do this to help debug problems discovered in the field, so when a bug report is incoming from an end user there's a chance of it being supported by "and also, these three tests failed on my machine". I'd like manual testers to be able to run the unit | integration tests as well.

However, the test of the team believes that test code is not production code and therefore shall not be shipped. I don't really get this argument, since most open source projects ship a test suite. It does seem to be unusual in closed software.

I would like supporting evidence or anecdotes for either side of the argument. I've taken my best guess at which stack exchange site would be most appropriate, but please let me know if this is out of place.


问:
Virtualization vs Container
Most of cloud computing technologies are based on virtualization. The advertisement of cloud computing technologies often refers reliability and reduction of costs. But when compared with container technologies such as Java VM, live migration and hardware abstraction of virtualization is much more difficult.

So what is the reason for virtualization-based cloud computing getting more popular than container-based technologies?

答:
The flexibility.

If you use shared hosting where your application is running within a container, you are restricted to a small set of very specific tasks you can perform.

If you use a virtual machine, you're restricted by the operating system and the hypervisor, but your room for maneuver is much larger.

For example, on a VM, you may access all the files, which also means that you can install anything you want. This makes it possible to do things you can't do on a shared hosting platform. Examples:

If you need Redis as a caching solution, you can do it. In a case of a container, you don't have this freedom.

If you need to have a partition in RAM for very fast access, a Linux VM will let you do it; on shared hosting, there will be no way to have this sort of customization.

Additionally, you have the benefit of tools which were used for years or decades by system administrators to manage servers. For instance, if you have a VM, you can usually access it with SSH or through RDP. In a case of container-based server, the only things you can use as a customer are the (usually badly made) tools provided by the hosting company. This makes it extremely difficult to impossible to profile or debug the applications, and even a simplest task as generating a dump or reading log files can become unnecessarily complicated.

There is nothing wrong with container approach per se. It has its perfectly valid uses. But it's not the answer to everything: sometimes, an actual virtualization is needed.

Title: Virtualization vs Container


答:
Factorize logic, return early

As suggested in comments, it would be sufficient to simply wrap your logic in a function and exit early with return's in order to simplify things a lot. Also, you could factorize a bit of functionnality by delegating tests to another function. More concretely:

```<code>bool mostly(max,u,v) {
   return max > u && max > v;
}

status_t strictly_max_3(a,b,c)
{
  if mostly(a,b,c) return MOSTLY_A;
  if mostly(b,a,c) return MOSTLY_B;
  if mostly(c,a,b) return MOSTLY_C;
  return DONT_KNOW;
}
</code>```

This is shorter than my previous attempt:

```<code>status_t index_of_max_3(a,b,c)
{
  if (a > b) {
    if (a == c)
      return DONT_KNOW;
    if (a > c)
      return MOSTLY_A;
    else
      return MOSTLY_C;
  } else {
    if (a == b)
      return DONT_KNOW;
    if (b > c)
      return MOSTLY_B;
    else
      return MOSTLY_C;
  }
}
</code>```

The above is a little more verbose, but is easy to read IMHO and does not recompute comparisons multiple times.

Visual confirmation

In your answer you say:

my issue was mostly visual confirmation that all comparisons used the
  same variables

... also, in your question, you say:

This pattern occurs a few times, and with long variable names it gets
  a little difficult to visually confirm that each if is correct.

I may not understand what you are trying to achieve: do you want to copy-paste the pattern everywhere you need it? With a function like the one above, you capture the pattern once, and you check once for all that all comparisons use a, b and c as required. Then, you don't need to worry anymore when you call the function. Of course, maybe in practice your problem is a little more complex than the one you described: if so, please add some details if possible.

Body:
Factorize logic, return early

As suggested in comments, it would be sufficient to simply wrap your logic in a function and exit early with return's in order to simplify things a lot. Also, you could factorize a bit of functionnality by delegating tests to another function. More concretely:

bool mostly(max,u,v) {
   return max > u && max > v;
}

status_t strictly_max_3(a,b,c)
{
  if mostly(a,b,c) return MOSTLY_A;
  if mostly(b,a,c) return MOSTLY_B;
  if mostly(c,a,b) return MOSTLY_C;
  return DONT_KNOW;
}

This is shorter than my previous attempt:

status_t index_of_max_3(a,b,c)
{
  if (a > b) {
    if (a == c)
      return DONT_KNOW;
    if (a > c)
      return MOSTLY_A;
    else
      return MOSTLY_C;
  } else {
    if (a == b)
      return DONT_KNOW;
    if (b > c)
      return MOSTLY_B;
    else
      return MOSTLY_C;
  }
}

The above is a little more verbose, but is easy to read IMHO and does not recompute comparisons multiple times.

Visual confirmation

In your answer you say:

my issue was mostly visual confirmation that all comparisons used the
  same variables

... also, in your question, you say:

This pattern occurs a few times, and with long variable names it gets
  a little difficult to visually confirm that each if is correct.

I may not understand what you are trying to achieve: do you want to copy-paste the pattern everywhere you need it? With a function like the one above, you capture the pattern once, and you check once for all that all comparisons use a, b and c as required. Then, you don't need to worry anymore when you call the function. Of course, maybe in practice your problem is a little more complex than the one you described: if so, please add some details if possible.


问:
Should a domain object wrap/contain a DTO interface?
Using .NET - I have an interface IPerson.  This interface is implemented by classes in  multiple, separate repositories, e.g. EF6 (EfPerson), custom SQL (SqlPerson), or even custom assembly connecting to a web service (WebPerson).

Assuming rich domain model, my idea is that my lovely rich domain object 'Person' could have a private member variable _PersonDto of type IPerson, supplied via constructor.  The members of Person would be the only way to access data from the _PersonDto.

Q. Is there anything actually inherently wrong with that approach?  (Assume I'm not lazy loading, and that I will possibly have a service layer for cross-cutting stuff).

Please note I'm using DTO here to simply mean the anaemic objects I get back from my repositories.

答:
There's nothing wrong with the backing state DTO approach, in fact it's recommended by some DDD people.

However, populating a domain object from heterogeneous sources is not the main reason for it. It's more about solving the entity encapsulation vs persistability paradox by having an object that is easily accessible and mappable by ORMs.

EfPerson/SqlPerson/WebPerson and the IPerson interface are unnecessary IMO, because the backing state object is just a dumb data bag that will contain exactly the same thing in all cases.

Data gathering and mapping logic should rather be placed in anticorruption layers between the various source systems and your own system, or in different concrete Repository implementations.


问:
Checking for emptiness of collections with (in)equalities - what's the best practice?
For a long time now I've been in the habit of checking whether a collection (array, dictionary, whatever) is non-empty with a nonequality. Like this:

```<code>if ( MyArray.Length < 1 )
{
    // Do something if the array is empty
}
</code>```

Sometimes I do this for strings too, and other kinds of collections. In practice, this should be the same as

```<code>if ( MyArray.Length == 0 )
{
    // Do something if the array is empty
}
</code>```

Because the length of collection should never be less than 0 anyway, right? So I always thought - what the heck, I'll include the inequality and be double-safe even in the case the sky falls down.

But today a though struck me that the second version might be more readable than the first. It expresses more clearly that the case I'm looking for is the empty array, which is not immediately apparent from the first version. So maybe I should use that instead? Since, you know, if a collection length is less than 0, then I'm screwed anyway.

Which version do you use, and which would you suggest others to use (and why)?

Clarification: This was meant as a question about simple collections, where obtaining .Length is O(1) or otherwise inexpensive. If .Length itself is a nontrivial operation (such as necessitating the iteration through a linked list, or contacting the DB), then this is the wrong approach altogether.

The question was about x < 1 vs x == 0 where x is a nonnegative integer (although it might not be typed as such).

答:
I would first check if there is a method named "empty", "isEmpty" or similar. The reason: Your check MyArray.Length < 1 determines the length of the array, even though you are not interested in the length at all, only in the fact that it is 0 or not 0. For some instances with a huge length, determining the length might be quite time consuming, while detecting that the length is not zero is immediate.

Say you have a string class, with "length" returning the number of Unicode code points. But internally the string is stored in UTF-8 format. If there is a million bytes, then to determine the "length" you need to look at each single byte. On the other hand, checking that the lengthis not zero is trivial.

Or take a linked list. Checking that it has more than 0 elements is trivial, but actually calculating the length can be quite time consuming.


问:
Responsibility of an ESB
When using an enterprise service bus, is it responsible for;

a. the successful delivery of a message to a consuming application

b. to  successfully deliver a message until the application's logic completes successfully (up to a retry threshold) ?

c. something else

With RESTful calls, a request will always have a response and it's up to the client in how it should deal with it. With an ESB it's slightly different as such the client doesn't care about how other services are consuming its published messages.

So if the client doesn't care if a consuming application throws an exception, should the ESB be concerned about the applications result that it is delivering the message to ?

答:
It depends.

The point of a message passing architecture is that the sender doesn't care who receives the message, and while this means a fire-and-forget approach works very well, it isn't suitable for some situations where either guaranteed delivery is required, or a acknowledgement is received.

Fortunately the latter approach is very easy - the receiver simply sends off a message back to whoever sent it as needed. Note that in these cases, its the applications that care, the ESB should not need to know if a response is required by the sender or not, all it needs to do is provide a way for these services to send each other messages.

The guaranteed-delivery, that's a responsibility of the architecture. Some have 2 types of message, one that's guaranteed and one that's less resource intensive to track.

Title: Responsibility of an ESB


问:
problems compiling a function with a trait Add in Rust
I'm trying to write a generic function summ in rust - but to no avail. Could someone please elucidate the problem?</p>

```<code>fn summ<T:Add>(a:T,b:T)->T  {
    a+b
}
</code>```

答: I don't know much about Rust, but I'm assuming that since there are no constraints on T, there's no way to know that it even has a + operator. You should probably constrain T to implement std::ops::Add.


问:
Providing views to an std::container
I want to maintain a buffer of 5 seconds of sensor data.
The sensor  data consists, among other things, of accelerometer readings in x,y,z dimensions, gyroscope readings in x,y,z dimension and magnetometer readings in x,y,z dimension.

My initial idea is to use an std::deque<SensorReading> which stores 5 seconds of the following SensorReading struct:

```<code>struct SensorReading {
   double time
   gyroscope g;
   accelerometer a;
   magnetometer m;
  //more substructs
} S;
</code>```

A common operation on the buffer is that the user provides a start and end time and wants two Iterators marking the first and last reading of the gyroscope (or magnetometer or accelerometer) within this time interval from the buffer (deqeue). (Sometimes the user of the gyroscope reading might also be interested in the corresponding time stamps of the parent struct S.)

In my mind I have the idea of providing some sort of “views” of the buffer, which lets the user only see the substructure he is interested in.
But I have no clear idea how to achieve this.

The only conceptual solution I have so far, is to introduce custom Iterators to the deque, a magnetometerIterator, gyroscopeIterator, accelerometerIterator and then expose only the corresponding substructure to the user.

I do not like the idea of maintaining multiple buffers, one for each substructure, because it adds redundancy to the code.

What would be a way to achieve this?

答:
It's certainly do-able, but it's not small. An incomplete minimal example looks something like:

```<code>template <typename BaseIterator, typename FieldType, FieldType SensorReading::*FieldPtr>
class FilteredIterator {
    BaseIterator base_;
    typedef FilteredIterator<BaseIterator, FieldType, FieldPtr> self_type;
public:
    // iterator type traits
    typedef FieldType value_type;
    typedef typename BaseIterator::difference_type difference_type;
    typedef typename BaseIterator::iterator_category iterator_category;
    typedef typename std::add_lvalue_reference<FieldType>::type reference_type;
    typedef typename std::add_pointer<FieldType>::type pointer_type;
    // construction and assignment
    FilteredIterator() = delete;
    explicit FilteredIterator(BaseIterator base) : base_(base) {}
    FilteredIterator(self_type const &) = default;
    FilteredIterator(self_type &&) = default;
    FilteredIterator& operator=(self_type const &) = default;
    FilteredIterator& operator=(self_type &&) = default;
    // increment/traversal
    self_type& operator++()    { ++base_; return *this; }
    self_type  operator++(int) { self_type tmp(*this); ++*this; return tmp; }
    // dereference
    reference_type operator* () { return (*base_).*FieldPtr; }
    std::add_const<reference_type> operator* () const { return (*base_).*FieldPtr; }
};

template <typename FieldType, FieldType SensorReading::*FieldPtr, typename BaseIterator>
FilteredIterator<BaseIterator, FieldType, FieldPtr> member_filter(BaseIterator iter) {
    return FilteredIterator<BaseIterator, FieldType, FieldPtr>(iter);
}
</code>```

example use:

```<code>std::deque<SensorReading> d;
// populate d
auto fi = member_filter<accelerometer, &SensorReading::a>(d.begin());
assert (&*fi == &(d.begin()->a));
</code>```

Note that this still omits:

decrement and reverse iteration

comparison (<, >, ==, etc.)

distance/subtraction

operator->

etc...

correct handling of cv-qualified, reference and pointer members

A simpler approach is to use the Boost.Iterator Adaptor as a starting point.

Title: Providing views to an std::container

Body:
It's certainly do-able, but it's not small. An incomplete minimal example looks something like:

template <typename BaseIterator, typename FieldType, FieldType SensorReading::*FieldPtr>
class FilteredIterator {
    BaseIterator base_;
    typedef FilteredIterator<BaseIterator, FieldType, FieldPtr> self_type;
public:
    // iterator type traits
    typedef FieldType value_type;
    typedef typename BaseIterator::difference_type difference_type;
    typedef typename BaseIterator::iterator_category iterator_category;
    typedef typename std::add_lvalue_reference<FieldType>::type reference_type;
    typedef typename std::add_pointer<FieldType>::type pointer_type;
    // construction and assignment
    FilteredIterator() = delete;
    explicit FilteredIterator(BaseIterator base) : base_(base) {}
    FilteredIterator(self_type const &) = default;
    FilteredIterator(self_type &&) = default;
    FilteredIterator& operator=(self_type const &) = default;
    FilteredIterator& operator=(self_type &&) = default;
    // increment/traversal
    self_type& operator++()    { ++base_; return *this; }
    self_type  operator++(int) { self_type tmp(*this); ++*this; return tmp; }
    // dereference
    reference_type operator* () { return (*base_).*FieldPtr; }
    std::add_const<reference_type> operator* () const { return (*base_).*FieldPtr; }
};

template <typename FieldType, FieldType SensorReading::*FieldPtr, typename BaseIterator>
FilteredIterator<BaseIterator, FieldType, FieldPtr> member_filter(BaseIterator iter) {
    return FilteredIterator<BaseIterator, FieldType, FieldPtr>(iter);
}

example use:

std::deque<SensorReading> d;
// populate d
auto fi = member_filter<accelerometer, &SensorReading::a>(d.begin());
assert (&*fi == &(d.begin()->a));

Note that this still omits:

decrement and reverse iteration

comparison (<, >, ==, etc.)

distance/subtraction

operator->

etc...

correct handling of cv-qualified, reference and pointer members

A simpler approach is to use the Boost.Iterator Adaptor as a starting point.


问:
Is continuous integration more than just automatically testing code?
Is continuous integration about more than just automatically testing code, either periodically or after every commit to the main repository?

Before today, I'd heard the term CI, and about CI services such as Jenkins, and RunCodeRun, and assumed that it was merely about having a server independent of developers' machines that checked that the automated tests of a project passed, and alerting people if it doesn't.

However, Wikipedia's definition seems to be different.

If my understanding of what CI is is incorrect, is there any term that merely refers to automatically running tests on an independent server?

答:
Continuous Integration is a process of continually integrating new changes with other peoples changes.  The goal being to eliminate merge problems developing over time when many developers are changing the code independently in different directions.

It is fashionable in commercial environments to have a centralised source control with an automated build server with various testing and reporting metrics run on the code in response to a code change whilst allowing developers to work in a seperate branch whilst integrating other peoples completed changes but not sharing their changes till their work is complete - and to call that continuous integration.

However, i disagree.  This kind of approach will allow developers working on sperate features both making large radical changes to avoid integration until the first developer finishes their feature. Whenb they merging their changes into the common branch they then dump the kind of merge hell onto their collegue that continuous integration is intended to avoid.

True continuous integration has developers commiting often (many times daily) to the same branch, ensuring that all code changes are integrated before significant divergence can occur.

As an approach, CI provides some advantages in reducing the impact that unexpected surprises at merge time can have, but creates problems else where in the business process of releasing and delivering software. (e.g. trying to develop new features whilst fixing bugs for the imminant release)

My advice is to avoid religious devotion to a methodology, but to implement processes that support your team and business environment that reflect how you work, how your business works around you and enables you to focus on software delivery and not process management.


答:
ESB:
Reliable delivery of a message is the responsibility of the transport. Successful delivery can mean very different things depending on context, see Quality of Service (QoS) 1, 2, 3. An ESB in a Service Oriented Architecture is normally responsible for routing and transformation as well as value add options such as monitoring, auditing etc.

RESTful calls:
A REST call should be an action on an object. It shouldn't take that long to complete and normally would be able to do the processing and return a HTTP response before it was a problem.

Async calls
If you really need to send off an asynchronous message once a HTTP request comes in because the action takes a long time, then you are not going to be able to wait for the response. In this case it's not really the responsibility of your ESB to do something about it. You are really going to have to decide how your program deals with this. Your ESB may be able to help you with this, for example by coordinating a global transaction for you. If you have already replied to your HTTP requestor that the action has been taken in hand, just as an MQTT client is responsible for the message once it has acknowledge the message status with the server to the specified level of QoS, you need to treat this process failing as a failing transaction and either undo everything that happened or compensate for things that can't be rolled back. The originator then needs to be coded with the assumption of the same behaviour and know that it needs to check up on what really happened or inform the client.

Title: Responsibility of an ESB

Body:
When using an enterprise service bus, is it responsible for;

a. the successful delivery of a message to a consuming application

b. to  successfully deliver a message until the application's logic completes successfully (up to a retry threshold) ?

c. something else

With RESTful calls, a request will always have a response and it's up to the client in how it should deal with it. With an ESB it's slightly different as such the client doesn't care about how other services are consuming its published messages.

So if the client doesn't care if a consuming application throws an exception, should the ESB be concerned about the applications result that it is delivering the message to ?


问:
Does it affect the burn down chart?
We finished the development and closed the sprint(two weeks). But the code has not been reviewed. So in the third week we don't start a new sprint and keep clean up(refactor) the code. The scrum master told us that we can still log the time to the previous tasks.

My question is that since we close the sprint, does it effect the sprint's burn down chart?

答:
If your definition of done (1, 2, 3) requires that you review your implementation to complete a story, then you cannot take credit for completing the story and the burn down chart does not reflect a completed story. Keep in mind that a story is either completed or not, and the burn down chart doesn't reflect credit for completing the work until the definition of done is met and the story is complete.

I would suggest looking at your process, though. If you started so many stories that you couldn't adequately close them, it sounds like you're taking on too much work. Are you estimating your whole definition of done? Are you adjusting your capacity for the Sprint based on your team's velocity? Are your Sprints too short (should you plan for 3-week Sprints instead of two)?

Title: Does it affect the burn down chart?

ContentLicense: CC BY-SA 4.0


答:
Have you closed the sprint or not? Extending it to a 3rd week sounds like you're still working it, unless you have a week's sprint for code review. Either way... who cares. If all your sprints measure code creation (and all review is done afterwards) then yes, close your burndown chart and start a new one when you start your next sprint.

The point of the burndown is to measure how much you actually get done compared to how much you thought you'd get done. That's all. Its solely a tool to help you plan your next sprint.

Title: Does it affect the burn down chart?

Body:
We finished the development and closed the sprint(two weeks). But the code has not been reviewed. So in the third week we don't start a new sprint and keep clean up(refactor) the code. The scrum master told us that we can still log the time to the previous tasks.

My question is that since we close the sprint, does it effect the sprint's burn down chart?


答:
It is important that the circle is filled using concentric passes

You can't draw anything "perfect" using "concentric passes" on Cartesian coordinate system, which is ultimately what you need to do. The pixels just don't align with your N-step-radius circles. But, you can make a good approximate. And the method you use should depend on what your ultimate goal.

... because i also update some metadata in the cells as I get them in
  groups (each one corresponding to a circumference).

This makes it sounds like you need to operate point-by-point on all points that could be part of the circle, determining each one's "relationship to the center" of the circle as you go.

So, what you'll end up with is something very similar to heltonbiker's solution, but that paints and/or sets meta-data for every point as it passes. You may want two functions:

```<code>// a simple distance function
var distanceFrom = function(x, y, cx, cy) {
    return Math.sqrt(
        Math.pow(cx - x, 2) + Math.pow(cy - y, 2)
    );
};

// something to determine the "value" of a pixel, based on the circle center
var getValue = function(x, y) {

    // in your real application, these three vars will be parameters ...
    var radius = 7;
    var center_x = 7;
    var center_y = 7;

    var d = distanceFrom(x, y, center_x, center_y);
    if (d <= radius) {
        return d / radius;
    } else {
        return 1; // white/off
    }
}; // getValue()
</code>```

And a simple loop ... somewhere in an appropriately named method:

```<code>// something that loops through all the relevant pixels.
// ... this does NOT need to look at every pixel. it only
// needs to look at the pixels within the box that bounds
// your circle.
for (var y = 0; y < 15; y++) {
    for (var x = 0; x < 15; x++) {
        paint(x, y, getValue(x, y));
    }
}
</code>```

See this fiddle, scaled up by 32 to show the "pixels."

I think you can see from the result drawing concentric circles would force matches between pixels and circles that are just ugly. The pixel-by-pixel approach not only ensure that every pixel is valued and drawn, but that each pixel can be associated with the most-relevant circle or radius.

If you're looking for a non-gradient pattern, you just need to update your value function:

```<code>// alternating / concentric-ish circles ....
var getValue = function(x, y) {
    var radius = 7;
    var center_x = 7;
    var center_y = 7;
    var d = distanceFrom(x, y, center_x, center_y);
    if (d <= radius) {
        return Math.floor(d) % 2 === 0 ? 0 : 0.5;
    } else {
        return 1; // white/off
    }
}; // getValue()
</code>```

Visible as a fiddle here. And here's what it produces:

And, of course, if you're looking to color a single "circle" that is compatible with your other circles, you could start with the unoptimized approach of scanning the whole circle area, and just drawing the pixels whose floored or rounded distance from the center matches an integer (or floored/rounded) radius.

```<code>var getValue = function(x, y) {
    var radius = 7;
    var center_x = 7;
    var center_y = 7;

    // the radius of the "circle" we're drawing (should be parametized)
    var draw_only = 5;

    var d = distanceFrom(x, y, center_x, center_y);

    // the new condition is tacked on here:
    if (d <= radius && Math.floor(d) === draw_only) {
        return Math.floor(d) % 2 === 0 ? 0 : 0.5;
    } else {
        return 1; // white/off
    }
}; // getValue()
</code>```

It's not efficient, but the rings it draws should align with those from the example with the alternating colors:

See the fiddle.

If you're looking to do what I've done the last example, drawing only a single ring at a time, it can potentially be optimized (for large circles) by walking around the circle and processing blocks of pixels that are "probably" going to be colored. Something similar to this totally untested code ...

```<code>// radius of the circle we want to draw
var radius = 5;
for (var deg = 0; deg < 360; deg++) {
  var radians = 2 * Math.PI * deg/360;

  var focus_x = Math.floor(radius * Math.cos(radians));
  var focus_y = Math.floor(radius * Math.sin(radians));

  // i'm not sure how much "fuzz" you need ... play with it:
  var x1 = focus_x - 2;
  var x2 = focus_x + 2;
  var y1 = focus_y - 2;
  var y2 = focus_y + 2;

  for (var y = y1; y < y2; y++) {
    for (var x = x1; x < x2; x++) {
      paint(x, y, getValue(x, y), radius); // again, radius needs to be parametized
    }
  }
}
</code>```

Disclaimer: Neither this answer nor the associated fiddle are intended to demonstrate good or proper usage of the HTML5 canvas.

Title: Drawing concentric circles without gaps

Body:
It is important that the circle is filled using concentric passes

You can't draw anything "perfect" using "concentric passes" on Cartesian coordinate system, which is ultimately what you need to do. The pixels just don't align with your N-step-radius circles. But, you can make a good approximate. And the method you use should depend on what your ultimate goal.

... because i also update some metadata in the cells as I get them in
  groups (each one corresponding to a circumference).

This makes it sounds like you need to operate point-by-point on all points that could be part of the circle, determining each one's "relationship to the center" of the circle as you go.

So, what you'll end up with is something very similar to heltonbiker's solution, but that paints and/or sets meta-data for every point as it passes. You may want two functions:

// a simple distance function
var distanceFrom = function(x, y, cx, cy) {
    return Math.sqrt(
        Math.pow(cx - x, 2) + Math.pow(cy - y, 2)
    );
};

// something to determine the "value" of a pixel, based on the circle center
var getValue = function(x, y) {

    // in your real application, these three vars will be parameters ...
    var radius = 7;
    var center_x = 7;
    var center_y = 7;

    var d = distanceFrom(x, y, center_x, center_y);
    if (d <= radius) {
        return d / radius;
    } else {
        return 1; // white/off
    }
}; // getValue()

And a simple loop ... somewhere in an appropriately named method:

// something that loops through all the relevant pixels.
// ... this does NOT need to look at every pixel. it only
// needs to look at the pixels within the box that bounds
// your circle.
for (var y = 0; y < 15; y++) {
    for (var x = 0; x < 15; x++) {
        paint(x, y, getValue(x, y));
    }
}

See this fiddle, scaled up by 32 to show the "pixels."

I think you can see from the result drawing concentric circles would force matches between pixels and circles that are just ugly. The pixel-by-pixel approach not only ensure that every pixel is valued and drawn, but that each pixel can be associated with the most-relevant circle or radius.

If you're looking for a non-gradient pattern, you just need to update your value function:

// alternating / concentric-ish circles ....
var getValue = function(x, y) {
    var radius = 7;
    var center_x = 7;
    var center_y = 7;
    var d = distanceFrom(x, y, center_x, center_y);
    if (d <= radius) {
        return Math.floor(d) % 2 === 0 ? 0 : 0.5;
    } else {
        return 1; // white/off
    }
}; // getValue()

Visible as a fiddle here. And here's what it produces:

And, of course, if you're looking to color a single "circle" that is compatible with your other circles, you could start with the unoptimized approach of scanning the whole circle area, and just drawing the pixels whose floored or rounded distance from the center matches an integer (or floored/rounded) radius.

var getValue = function(x, y) {
    var radius = 7;
    var center_x = 7;
    var center_y = 7;

    // the radius of the "circle" we're drawing (should be parametized)
    var draw_only = 5;

    var d = distanceFrom(x, y, center_x, center_y);

    // the new condition is tacked on here:
    if (d <= radius && Math.floor(d) === draw_only) {
        return Math.floor(d) % 2 === 0 ? 0 : 0.5;
    } else {
        return 1; // white/off
    }
}; // getValue()

It's not efficient, but the rings it draws should align with those from the example with the alternating colors:

See the fiddle.

If you're looking to do what I've done the last example, drawing only a single ring at a time, it can potentially be optimized (for large circles) by walking around the circle and processing blocks of pixels that are "probably" going to be colored. Something similar to this totally untested code ...

// radius of the circle we want to draw
var radius = 5;
for (var deg = 0; deg < 360; deg++) {
  var radians = 2 * Math.PI * deg/360;

  var focus_x = Math.floor(radius * Math.cos(radians));
  var focus_y = Math.floor(radius * Math.sin(radians));

  // i'm not sure how much "fuzz" you need ... play with it:
  var x1 = focus_x - 2;
  var x2 = focus_x + 2;
  var y1 = focus_y - 2;
  var y2 = focus_y + 2;

  for (var y = y1; y < y2; y++) {
    for (var x = x1; x < x2; x++) {
      paint(x, y, getValue(x, y), radius); // again, radius needs to be parametized
    }
  }
}

Disclaimer: Neither this answer nor the associated fiddle are intended to demonstrate good or proper usage of the HTML5 canvas.


答:
Add's add method does not return Self - it returns Self::Output. This allows the addition to return a different type than the addends. The return type of summ should reflect that:

```<code>fn summ<T: Add>(a: T, b: T) -> T::Output  {
    a + b
}
</code>```

Title: problems compiling a function with a trait Add in Rust

Body:
I'm trying to write a generic function summ in rust - but to no avail. Could someone please elucidate the problem?</p>

```<code>fn summ<T:Add>(a:T,b:T)->T  {
    a+b
}
</code>```

Body:
Add's add method does not return Self - it returns Self::Output. This allows the addition to return a different type than the addends. The return type of summ should reflect that:

fn summ<T: Add>(a: T, b: T) -> T::Output  {
    a + b
}


问:
What problem do algebraic data types solve?
Fair warning, I'm new to functional programming so I may hold many bad assumptions.

I've been learning about algebraic types. Many functional languages seem to have them, and they are fairly useful in conjunction with pattern matching. However, what problem do they actually solve? I can implement a seemingly (sort-of) algebraic type in C# like this:

```<code>public abstract class Option { }
public class None : Option { }
public class Some<T> : Option
{
    public T Value { get; set; }
}

var result = GetSomeValue();
if(result is None)
{
}
else
{
}
</code>```

But I think most would agree this is a bastardization of object oriented programming, and you shouldn't ever do it. So does functional programming just add a cleaner syntax that makes this style of programming seem less gross? What else am I missing?

答:
It may surprise you to learn that pattern matching is not considered the most idiomatic way to work with Options.  See the documentation of Scala's Options for more about that.  I'm not sure why so many FP tutorials encourage this usage.

Mostly what you're missing is there are a whole bunch of functions created to make working with Options easier.  Consider the main example from the Scala docs:

```<code>val name: Option[String] = request getParameter "name"
val upper = name map { _.trim } filter { _.length != 0 } map { _.toUpperCase }
println(upper getOrElse "")
</code>```

Notice how map and filter let you chain operations on Options, without having to check at each point whether you have None or not.  Then at the end, you use getOrElse to specify a default value.  At no point are you doing something "gross" like checking types.  Any unavoidable type checking is done internal to the library.  Haskell has its own set of analagous functions, not to mention the large set of functions that will work on any monad or functor.

Other algebraic data types have their own idiomatic ways to work with them, and pattern matching is low on the totem pole in most cases.  Likewise, when you create your own types, you're expected to provide similar functions to work with them.

Body:
It may surprise you to learn that pattern matching is not considered the most idiomatic way to work with Options.  See the documentation of Scala's Options for more about that.  I'm not sure why so many FP tutorials encourage this usage.

Mostly what you're missing is there are a whole bunch of functions created to make working with Options easier.  Consider the main example from the Scala docs:

val name: Option[String] = request getParameter "name"
val upper = name map { _.trim } filter { _.length != 0 } map { _.toUpperCase }
println(upper getOrElse "")

Notice how map and filter let you chain operations on Options, without having to check at each point whether you have None or not.  Then at the end, you use getOrElse to specify a default value.  At no point are you doing something "gross" like checking types.  Any unavoidable type checking is done internal to the library.  Haskell has its own set of analagous functions, not to mention the large set of functions that will work on any monad or functor.

Other algebraic data types have their own idiomatic ways to work with them, and pattern matching is low on the totem pole in most cases.  Likewise, when you create your own types, you're expected to provide similar functions to work with them.


问:
Risks of AJAX calls to ASMX
Currently working on an ajax call to an ASP web service (.asmx).

In a situation where I POST to the url/.asmx/WebMethod, am I exposing information of any kind?

In the 'WebMethod' I am running a PostJsonAsync that calls an API and passes along a json string.

As I am still learning, I've been told that calling any public [WebMethod] exposes the code, but I am not sure how that is possible.

Is it possible at all for a user to access the WebMethod server-side code that I have and peek into the API calls that are available?

I've attempted some minor security methods.. We are working with Sitefinity CMS. What I did was call a WebMethod that receives the CurrentUserIdentity and returns a GUID. If the current user is logged in, it returns a valid Guid, if not it returns a Guid full of zeros.

Then, I call the WebMethod containing my API call and post a json object along with the valid or invalid GUID. The server-side WebMethod code will then verify if the GUID is valid and continues based on if a UserProfile can be generated.

To me, this seems to be secure, but I've been told that this still leaves the WebMethod exposed as well as the API. I am however just not understanding what is exposed and what can be used.

If anybody can direct me to any resources that has more information on this, or if anybody can advise me on WebService security, I would appreciate it.

Thanks in advance.

答: no, there is no difference between calling an ASMX web service vs. any other kind of web service.  The code on the server is not exposed because .cs files are by default not served by Asp.Net, or the code for the ASMX is compiled into an assembly in the bin folder, depending on the type of project (Web Site vs. Web Project) deployed.  It may be possible to discover what other calls are available on your web service depending on how things are configured, but this alone is not a security threat as it would be trivial to discover that anyway (since HTTP traffic can be intercepted).  You should be sure that you're using HTTPS to call the service though to protect the data while its in transit.</p>

Title: Risks of AJAX calls to ASMX


问:
Unit testing functions calling other tested functions
I have three functions:

ValidateUsername(), which determines if a string is a valid username according to some rules

SetUsername() which sets a string as a user's Username if it passes validation

AddNewUser(), which creates a new user and, among others, sets a string as his or hers Username using SetUsername()

All three should fail if the supplied username string is incorrect, yet ValidateUsername() is where the rules reside. How would I unit test this? Testing validation only in ValidateUsername() leaves the possibility that someone will mistakenly omit validation and set the username directly in AddNewUser(). On the other hand, repeating all different validation test cases for all functions seems counterproductive. What's the best practice?

答: You can verify that the validation function was called by testing the other two functions with one invalid name and one valid name. Or you can separate the logic into UsernameValidator and UserService, and inject the validator into the user service. Then you test the user service by mocking the validator.</p>


问:
How to structure project where a library and application using the library are concurrently developed?
I am planning to develop a new application that will heavily use a library that will be developed from scratch specifically for the application, but made general enough for it to be used for other programs once it's finished.

So the development of this library is going to be heavily driven by the development of the application. It'll get features based on how important that feature is to the paired application. All the same, I want the library to be completely decoupled from the application. The application uses the library, but the library is unaware of the application and at some point of time, I'll want to ensure that the library can easily be used in other applications.

I'm looking for advice on how to structure this. In particular, where the code for the library should be located (same/different repo, some kind of build tool to keep them separate, etc).

Since this may be language dependent (as a result of build tools and other language differences), I am planning to use Python.

答:
It is not a matter of programming language.

If you'll write your library with 'this is general purpose library' in mind you can be successful. But, if I were your I'd start development of both in the same place, in the same repository. Later you can extract this library into another project.


问:
How should one document permission of contributors to change the licence of a project?
I'm using a Python library which is currently under GPL3. The maintainer has decided that he would like to change the licence to one which does not contaminate larger works (probably either the MIT licence or MPL2 if that makes a difference).

The question is how does he go about changing the licence? In particular, obtaining and documenting permission from the (luckily very few) contributors?

答: I've seen this done via a GitHub Issue comment thread. The author created an issue describing the intent to change the license and asked every contributor to comment if they agree to the change. This creates a public record of the approval of all contributors.</p>


问:
Algorithm to find the optimal trade route (negative cycle with lowest cost per edge in a digraph)
Given the following problem (a slightly simplified description of trading in the computer game Escape Velocity: Nova (system map)):

Given a set of (solar) systems.

Each system is connected by hyperspace travel route to one or more other systems; each route connects two systems.

Making a hyperspace jump has a cost in dollars (covering fuel costs). The cost is the same no matter which jump you're making.

Each system has a trading center with various commodities (food, metal, equipment, etc.) available for trade at a given price. The price varies between systems.

To keep it simple we'll say you can only hold a single unit of a single commodity at any given time.

A trade route is a series of hyperspace jumps that start and end in the same system (a loop), buying and selling commodities along the way.

The profit of a trade route is defined as profit made by buying and selling commodities along the way minus the total cost of the hyperspace jumps made.

I want to be able to answer questions like the following:

What's the most profitable trade route?

What's the most profitable trade route starting and ending in a specific system?

What's the most profitable trade route involving fewer than X jumps?

What's the most profitable trade route involving fewer than X jumps starting and ending in a specific system?

I plan to model this as a digraph:

Each system is a vertex.

For each hyperspace travel route add two edges (one in each direction) connecting the two vertexes with a weight equal to the cost of making a hyperspace jump.

For each system

for each commodity available in that system

for each system where the price of the commodity is lower than in the current system (we'll never make a profit if the cost at the destination is higher so we omit those edges)

add an edge from the current system to that system with weight of (number of jumps to reach that system) * (cost per jump) - (difference in price of the commodity) (i.e. profit to be made by buying in the current system and selling in the destination system)

I believe the technical description of what I'm after is (for question 1): given the above digraph what's the negative cycle with the lowest average cost per edge.

I realize I can use a breadth-first search to answer questions 3 and 4 as long as the maximum number of jumps is small enough that I don't run out of memory, but I suspect it won't be practical to answer 1 or 2 this way.

I've read though the Solving Problems by Searching chapter in AI: A Modern Approach but as far as I can tell the algorithms there require positive edge weights.

A bit of Googling found me the Bellman–Ford algorithm and while that supports negative edge weights my understanding is that it doesn't give accurate costs when negative cycles are involved.

Are there any algorithms I can use to solve this problem more efficiently?

答:
Look into Traveling Salesperson Problems and optimization.

You are basically optimizing a TSP for all your four questions.

The specific details will vary based on your problem size (if you have 10 nodes you can just brute force it, if you have 1000 you will have to be more efficient).

The wikipedia site on TSPs suggests a large number of algorithms to use. It looks like you could use a modified Ant Colony Optimization method based on the total value of the entire trip (ie your first and second questions).