问:
How to effectively split jobs into groups for multiprocessing when the job sizes are unknown
With K processor cores, how to optimally split N jobs into groups, with each group to be processed sequentially by one processor core, when the time to process each job is unknown ahead of time and there is overhead associated with processing each group of jobs?

It is possible to kill a job group before it completes, but then no useful processing progress will be extracted from that job group.

If I just make each group size 1, add them to a queue, and process K of them at once, then the overhead can dominate the total time.  If I split them into K equal sized groups, then the overhead can still dominate the total time and I could get unlucky and have all the slowest jobs in one group further slowing things down.

Is this an example of a general well studied problem with an understood algorithm to optimally process?

For example, suppose I have 326400 jobs, 32 cores, and about 5 seconds overhead associated with processing a group.

3,200 big jobs take 2 minutes each to process if done in four separate groups

3,200 medium jobs take 1 minute each to process if done in four separate groups

the remaining 320,000 small jobs take about 5.001 seconds each to process if done in 320,000 separate groups.

for the 5.001 seconds for the small jobs, 1 millisecond is due to the processing and 5 seconds is due to the overhead of processing any group.  if all the small jobs are done in one group, it takes 325 seconds to process total due to sharing the overhead (320,000 * 1 millisecond + 5 seconds = 325 seconds)

If I just made each group size 1, put the groups in a queue, and ran 32 at a time concurrently on 32 cores, and happened to pick the 3,200 biggest jobs from the queue first, then the 3,200 medium jobs from the queue, it would take 200 minutes for the big jobs to finish, 100 minutes for the medium jobs to finish, and 833.5 minutes for the small jobs to finish: 18 hours total.

Optimally I would process the biggest jobs first (1 job per group), then the medium jobs (1 job per group), then split the remaining small jobs into 32 groups for a total of about 5 hours total to finish.

I am hoping that there is some well studied algorithm that I am ignorant of that handles this situation well.

答:
Yes, this is a well-studied problem. Job scheduling has been a large focus of active research in the high-performance computing community for decades.

Part of the answer to this problem will depend on how the jobs are distributed. If we can assume that whether a given job is short, medium, or long is independent random variable (e.g. its probability of being one type or another is random and doesn't depend on what type the previous job was,) then one of the best ways to solve this would probably be to simply run a queue on each core. Assign groups of jobs that will, on average, be sufficiently long to dominate the 5 second queuing time, but not so long that it will likely be running for hours on end. Once that queue is drained, assign it another group of jobs. This results in a load-balancing effect, as cores that finish their work sooner can go ahead and grab more work.

In your example, the probabilities for a particular job are as follows:

320,000 / 326,400 = .98 of 1 ms

3,200 / 326,400 = 0.01 of 60,000 ms

3,200 / 326,400 = 0.01 of 120,000 ms

This gives an expected duration for a given job of (0.98 * 1) + (0.01 * 60,000) + (0.01 * 120,000) = 601 ms

So, if, for example, you want to get the 5s overhead down to 5% of the expected time of a given job group, you'd need job groups of size (19 * 5000) / 601 = 158 jobs per group. When a core finished those jobs, then just give it that many more from the remaining pool of jobs. This would give you an expected job group runtime of 158 * 601 ms + 5000 ms = 100,000 ms

Where you could run into problems with the above method is if the previously-mentioned assumption of job length being evenly-distributed does not hold. If, for instance, all of your large jobs had a significant likelihood of being adjacent to each other, then you could end up assigning job groups whose length varies dramatically from the expected value. If this is a potential issue in your case, you could mitigate it somewhat by effectively using something like a round-robin algorithm for creating a group of jobs. For instance, rather than grabbing a bunch of adjacent jobs from the pool of remaining jobs when you're creating a job group for a core, you could grab every 32nd job, so that clusters of large jobs together would likely be split up between the different cores.


问:
Should I store x,y coordinates as an array, a class object, or two variables?
I have a MyObject which has an x and y coordinate.

as far as I can see, I can store it in three ways:

```<code>class MyObject:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class MyObject:
    def __init__(self, x, y):
        self.position = [x, y]

class MyObject:
    def __init__(self, x, y):
        self.position = Coord(x,y) #Coord class created elsewhere
</code>```

Is there a best practise either way for this ?

Where I'm thinking this is relevant, is when passing these coordinates into other methods:

eg.

```<code>myObj = MyObject(0,0)
searchLocation(myObj.x, myObj.y)
searchLocation2(myObj.position)
</code>```

答:
How often will you use x without y or vice versa? If your answer is rarely or never, then group them together into a tuple or class. Whether to use a tuple or class is another question. One common rule of thumb is to use a class if it will have two or more methods, and otherwise use a tuple. A namedtuple will get you the naming convenience of class members while being as lightweight as normal tuples.

This answer speaks to using namedtuple with points, as in your example.

ContentLicense: CC BY-SA 3.0


答: If you don't have enough data to decide, chose the most flexible option.  The object choice would allow you to have the other two options as properties.  (Though I would, as the comment suggests, choose a tuple over a list.)</p>

Title: Should I store x,y coordinates as an array, a class object, or two variables?

Body:
I have a MyObject which has an x and y coordinate.

as far as I can see, I can store it in three ways:

```<code>class MyObject:
    def __init__(self, x, y):
        self.x = x
        self.y = y

class MyObject:
    def __init__(self, x, y):
        self.position = [x, y]

class MyObject:
    def __init__(self, x, y):
        self.position = Coord(x,y) #Coord class created elsewhere
</code>```

Is there a best practise either way for this ?

Where I'm thinking this is relevant, is when passing these coordinates into other methods:

eg.

```<code>myObj = MyObject(0,0)
searchLocation(myObj.x, myObj.y)
searchLocation2(myObj.position)
</code>```


问:
Is JBPM the right tool for this?
We have a utility for monitoring directories and taking actions when files appear in those directories. It's in java and takes the form of a standalone jar which launches several threads when started:

One thread periodically (every minute or so) checks for new instructions regarding which directories to monitor.

Another set of threads periodically checks each of the directories being monitored. New files are placed in a notification queue.

Another set of threads service the notification queue and run actions for each new file.

Now, the powers that be want to reimplement this utility within JBPM. The main goal is to permit file arrival to start workflows within JBPM. Secondary goals are to make the process more highly available, and perhaps to simplify deployment by having it run inside Jboss rather than as a standalone utility.

I have past experience with WebSphere process server--IBM's BPM system--but JBPM is completely new to me. I'm struggling to see how to recreate this program as a set of JBPM processes, and it's not even clear to me that JBPM is the right tool for the low-level logic of reading directories and processing lists of files.

I could write a simple one-step business process that just calls into the entry point for the old monitor utility. With more work, I imagine I could decompose the old logic into a couple of different business processes calling each other. I have a hard time seeing the point, though. On a more practical level, the utility is supposed to start up automatically--without being called by anything--and I haven't been able to figure out how to do that for something deployed within jboss.

Should I be pushing back on this requirement to use JBPM? Or suck it up and get coding?

答:
Certainly, jBPM may be overkill for the operations that you describe. However, you get a bunch of items for free (for some definition of free) when you use a modern business process management tool.

Monitoring -- Every process can be monitored with neat visual indicators.

Reporting -- Number of processes triggered, time to handle, delays in the system, etc.

Graphical design of processes -- Adding a new process can often be done using the web tools in the graphical editor, especially if the primitives are to hand.

More importantly than that, to some extent the whole process becomes future-proof. Here are some of the things that might arise in the future;

Human interaction. Some files may have to be reviewed, signed off or redirected by one or more humans. The BPM environment handles human-tasks handing things off to computer-tasks quite readily. Also, the BPM structure allows notification of the humans who have work to do.

Multi-computer interaction. BPM isn't restricted to a single server; you can set up a number of co-operating servers that send each other messages.

Perhaps the most important aspect is that there is a fundamental evolution from file management to document management, and from task management to work flow management. BPM systems can help bridge this gap.

Title: Is JBPM the right tool for this?


问:
Why are for loops needed?
It seems to me that a while loop with the appropriate break statements can replace them entirely. I understand that a break statement may not feel as "smooth" as a for loop that does something a specified number of times, but I also feel that the redundancy in their behavior is unnecessary.</p>

答:
I suspect part of the answer is that it makes compiler optimisation easier, and partly because, for some code variants, it's easier for a human to read a simple 'for' structure than searching for a break statement.

Human readable/maintainable and compiler optimisable code is more important than considerations of functional redundancy in language design - after all, where do you stop, you can write language with a single control flow structure in it (think of a Turing-complete language based on a 'move' from pre-defined function to function in a list popping manner akin to a single instruction machine language), but no one would want to use it.

Title: Why are for loops needed?


问:
Do I have to include the license text when I GPL a web page?
I want to GPL some standalone web pages containing my Javascript/D3.js source code.  How to use GNU licenses for your own software says that to distribute source code under the GPL, I should "include a copy of the license itself somewhere in the distribution of your program."

I could bundle up the web pages into a distribution, e.g. in a github repo, and include
the license file there.  However, in practice, I am actually distributing the source files individually: They're up on the web.  It sounds as if should include the entire license in each of the HTML files (e.g. as a comment in the HTML), making the source file five or six times larger.

I'll of course include a copyright notice, stating that the source is distributed under the GPL, but do I really have to include the entire GPL text in the page source? Can't I just provide a URL to the GPL?

I was unable to find anything relevant to this question in the GPL FAQ.

答:
FSF actually recommends to use GNU Free Documentation License as a copyleft license for textual works of practical use rather than GNU General Public License (which is mostly for code). And they do that for their own online documentation. But since both of them (GPL and FDL) have similar requirements to include the full text of license in distribution, you probably can follow GNU websites as as example.

For instance, there is a manual for GCC; you could see while the copyriht notice is indeed included in source of every page, the copy of FDL is included once as a separate chapter mentioned in TOC.


问:
Java Serialization for long-ish-term storage
I have an application that uses a database of about 15,000 Java objects, which I have to read every time the application starts.  Originally I've been using JSON to store the data, but that has a few issues, mostly that it's slow (it can take 8-10 seconds to read all the objects on my lower-end machine) and also, it's very common for the objects in my database to have fields that point to the same object.  Java serialization handles this by using references to the same object, whereas with JSON, I just have to write the state of each object and then intern them during reading.  This also bloats the file size.

The contents of this database will be updated fairly infrequently (maybe about once a month or so).  I've heard from pretty much every source that Java serialization is always a poor choice for long-term storage, and I understand why.  Given these conditions, however, is there a good reason not to use Java serialization here?

答:
I agree with the comments to the effect that Java serialization is unstable and difficult to maintain as your classes change.   I recommend writing your own read/write routine to a format that is understandable by humans and manually editable (if need be).  You can
probably package this as static data that will be digested into your runtime data
structure mostly by the compiler.</p>


问:
Progress in PHP web application design
I have created an easy database-driven web application (with PHP+MySQL).

It's written procedurally with a few controllers (index.php) in a few
directories and a few template files and one stylesheet. There are a few
functionalities such as access management and utility functions.

As I progress with time, I notice that it's quite difficult to navigate
in my files and search where particular functionality is coded.

Could you recommend me some guidelines, how to structure my application,
to be more easier to navigate in the code and append some new functionalities?

It was my first application. I wanted to learn from the basics, so I made
it as was usual in the old times.

In the answer you could outline how developers started to structure the
procedural code, how they separated the user interface, controllers, templates,
helpful code etc. and how later they moved this to OOP style.

Could you show this progress on some minimal examples or direct me to some design/architecture guidelines, where is captured this historical progress through PHP web application development?

I know that the resulting design will probably be the MVC pattern. What I'm interested in is in the evolution from the chaotic design in the old times
to more and more structural design typical in these days. (It's for educational purposes, to realize the evolution)

答:
Procedural knots

As I progress with time, I notice that it's quite difficult to navigate in my files and search where particular functionality is coded.

This is the classic problem with procedural programming. Code is written where it's needed at the time the need was discovered. This leads to spaghetti code, which is an apt metaphor but alternatively can be understood as a code knot where each addition to your codebase adds a new layer obscuring to the layers beneath, making it harder to unravel and comprehend. At a certain size understanding how a code knot works requires heroic memorization and patience.

For single file programs (like shell scripts) this isn't always bad. Programs composed of less than 50 lines can be read through and understood in a single sitting. Most web applications (especially those backed by a database) do not scale well in a procedural format.

How to know when the knot is going to hang you

Could you recommend me some guidelines, how to structure my application, to be more easier to navigate in the code and append some new functionalities?

That is entirely dependent on the requirements of your application. If you wrote your project in a procedural style then you probably structured your code in ad-hoc manner. As you saw a piece that could be reused you probably turned that into a new file and started "including/requiring" that file.

As you scale this style will always end in tragedy because you've created a rigid temporal coupling between different concerns. The order of execution tends to be specific and therefore very brittle. Each new include adds fragility that ripples across your codebase. Need to customize one of the includes? You want to skip an include, except it contains key logic that another element requires? You need to add a new state but can't figure out where to initialize it? Naming clashes become more common as you scale and all kinds of unwieldy  variables start spreading across your codebase, meaning different things at different times. Suddenly a change in footer.php inexplicably breaks sidebar.php and you have no idea why.

It's at this point you redesign your codebase to isolate concerns, instead of spread them.

One simple way to do this is to encapsulate each kind of knowledge in a class, and using static properties of that class to namespace your different global states. This is the first step towards using objects even though it's just proceduralism in disguise.

How to untie the knot

I know that the resulting design will probably be the MVC pattern. What I'm interested in is in the evolution from the chaotic design in the old times to more and more structural design typical in these days. (It's for educational purposes, to realize the evolution)

This topic really deserves a pamphlet, or small book — it'd be a great work. I've poked around dozens of "MVC" frameworks in a variety of languages. Very few frameworks start procedural and move to OO — it's rarely a smooth, easy to articulate evolution.

Reading OO articles is usually not illuminating, until after you've started writing OO code. Even within an OO codebase there will be lingering elements of procedural cruft, making it hard to see why objects even exist. It's only when you see a bunch of well designed objects working together, in a low-friction, easy to reason about way can you fully grok the elegance of OO.

Designing useful, transparent, illuminating objects is hard, and there is plenty of overly designed OO code that violates the 4th rule of simple design: minimize. Bad OO code will frustrate, mislead, and distract you from the primary goal of high level software: to express intent in a way that both humans and machines can understand reasonably well.

Process to OO

Could you show this progress on some minimal examples or direct me to some design/architecture guidelines, where is captured this historical progress through PHP web application development?

As you struggle with useful conventions in a procedural projects you may never need Object Orientated design to be successful. But as scale your spaghetti you will inevitable run into a genre of frustrations that are much easier to deal with when you know how to design and coordinate, coherent objects.

Moving from procedural to object oriented is a journey, not a destination.

Start by reading: Create your own framework on top of the Symfony components.

Then compare how different frameworks use those same components to excellent effect:

Silex

Laravel

Drupal 8

Symfony 2.

MVC in general

MVC can be a red herring since there is no fixed meaning for what a controller, model, or view object look like (from an interface/public api perspective). I'd characterize a handful of characteristics.

A good application framework should:

follow "Inversion of Control" often implemented using a Dependency Injection (summarized as it's better to depend on a flexible abstract definition over a specific concrete definition)

Have dumb Views and smart Models (aka: views should be logic-light, and presentation heavy)

Offer you a convenient way (via a Controller or some other pattern, like Events + Observers/Presenters) to write simple glue statements that allow you to connect your Models and Views without model objects, or view objects having knowledge (i.e. holding instances) of each other.

Code should be organized into highly cohesive, low coupling modules and packages. Especially reusable code.

As a paragraph:

Views are dumb and work roughly the same across many frameworks (with dozens of similar templating languages). Models are smart they can be organized and conceptualized in a variety of ways but should be the "engine" objects  describing (and driving) the purpose of your application. Controllerish objects usually connect these dots, although they may trigger these connections through some delegation (like Events). In web frameworks controllers tend to be associated with accessing a URL, mouse clicks or any number of user initiated events.

Title: Progress in PHP web application design


答:
For loops are needed because they best express the programmers intent.  Which is why most languages have several types of loops.

Excluding languages like BrainFuck, the point of most languages syntax is to make it easier to express the programmers intent.  Otherwise we'd all stick with the perfectly viable macine code.

Title: Why are for loops needed?

Body: It seems to me that a while loop with the appropriate break statements can replace them entirely. I understand that a break statement may not feel as "smooth" as a for loop that does something a specified number of times, but I also feel that the redundancy in their behavior is unnecessary.</p>


答:
What is more readable and maintainable is the correct way to do most things.

Explicit is better than implicit.

Pseudo Code Examples:

```<code>for (int i=0; i < 10; i++) { /* do something 10 times */ }

for i in range(1,10): # do something 10 times

// assume range is a list, set, vector, array or iterable something
for (final int i : range) { /* do something 10 times */ }
</code>```

vs

```<code>int i = 0;
while (i < 10) { /* do something 10 times */ i++; }
</code>```

which is just syntactic sugar for and not much better than:

```<code>int i = 0;
loop:
    if (i < 10) { /* do something */ } else { goto end; }
    i++; goto loop;
end:
</code>```

Which one immediately tells you what is going on?

What happens if someone moves the i++ in the while version?

what happens if someone forgets the i++ in the while version?

Which one has better locality and cohesion ( hint it is the for version )

the while version has mutable state that is outside the scope of the loop!

Even better are languages, mostly functional ones, that support pattern matching such as Erlang

Here is pseudo code for a pattern matching version.

```<code>function for(n) { /* do something */ for(n--); }
function for(0) { /* do something the last time*/ }
</code>```

Most looping is over some kind of collection

The Visitor Pattern is much more expressive and has high cohesion and low coupling.

Here is a good example in Python with a thorough explanation of why it is so powerful.

Title: Why are for loops needed?

Body:
What is more readable and maintainable is the correct way to do most things.

Explicit is better than implicit.

Pseudo Code Examples:

for (int i=0; i < 10; i++) { /* do something 10 times */ }

for i in range(1,10): # do something 10 times

// assume range is a list, set, vector, array or iterable something
for (final int i : range) { /* do something 10 times */ }

vs

int i = 0;
while (i < 10) { /* do something 10 times */ i++; }

which is just syntactic sugar for and not much better than:

int i = 0;
loop:
    if (i < 10) { /* do something */ } else { goto end; }
    i++; goto loop;
end:

Which one immediately tells you what is going on?

What happens if someone moves the i++ in the while version?

what happens if someone forgets the i++ in the while version?

Which one has better locality and cohesion ( hint it is the for version )

the while version has mutable state that is outside the scope of the loop!

Even better are languages, mostly functional ones, that support pattern matching such as Erlang

Here is pseudo code for a pattern matching version.

function for(n) { /* do something */ for(n--); }
function for(0) { /* do something the last time*/ }

Most looping is over some kind of collection

The Visitor Pattern is much more expressive and has high cohesion and low coupling.

Here is a good example in Python with a thorough explanation of why it is so powerful.


问:
which pattern is most intuitive for a calculator app?
The title says it all. I'm trying to build a calculator application (for self-learning purposes). The application is going to have a very common UI, with plus(+), minus(-), multiply(*) and a divide(/) button. Also, the app can do, real-number as well as complex-number calculations.

So, the situation here is, depending upon the mode(normal or complex), the same button should perform different calculation ? Which pattern should I be using for this situation ? I feel, strategy pattern should be a good fit, but then, I don't exactly know how to implement that - I mean, I'm just not sure about how to design my classes, what to have as Interfaces, and what as delegates.

CURRENTLY, MY DESIGN CONTAINS

```<code>IOperation
{
  Do();
}
Add:IOperation{}
Subtract:IOperation{}
Multiply:IOperation{}
Divide:IOperation{}
Root:IOperation{} //not supported by ComplexNumber
ISupportedOperation
{
   IList<IOperation> SupportedOps {get;}
}
INumber : ISupportedOperation {}
RealNumber:INumber{}
ComplexNumber : INumber {}
</code>```

Interface names starts with I

All others are concrete classes

BUT IT'S A MESS. And, I'm totally lost within my own classes, and interfaces.

PS: Of course, I can do this using if/else, but that's not what I want to do. Not because I forcefully want to use a pattern, but because, those if-else will be scattered everywhere in the program for eg. ReadInput, PlusButtonClick, MinusButtonClick, etc. And, as I understand, design patterns are supposed to avoid these kind of situations of code-repetitions, by clever/tricky re-organization of the existing code.

PPS: Sorry for being too verbose.

答:
How about this...

```<code>interface IOperator
{
    double Calculate(double num1, double num2);

    // ComplexNumber Calculate(ComplexNumber num1, ComplexNumber num2); // up to you
}

class AddOperator : IOperator
{
    public AddOperator() { }

    public double Calculate(double num1, double num2)
    {
        return num1 + num2;
    }

    // ComplexNumber Calculate(ComplexNumber num1, ComplexNumber num2) { ... }
}

class MinusOperator : IOperator
{
    public MinusOperator() { }

    public double Calculate(double num1, double num2)
    {
        return num1 - num2;
    }

    // ComplexNumber Calculate(ComplexNumber num1, ComplexNumber num2) { ... }
}

// ...
</code>```

Factory use to create instance:

```<code>static class Factory
{
    public static T CreateInstance<T>() where T : new()
    {
        return new T();
    }
}
</code>```

Client:

```<code>static void Main(string[] args)
{
    IOperator op = Factory.CreateInstance<AddOperator>();
    Console.WriteLine(op.Calculate(1, 2));

    // Console.WriteLine(op.Calculate(complexNum1, complexNum2));

    Console.Read();
}
</code>```

Now, if I want to add an operator, just add a suboperator class and implement the IOperator. Overload method will determine calculate simple or complex.

This is a update version base on Facotry Method use Generic Type.

Body:
How about this...

interface IOperator
{
    double Calculate(double num1, double num2);

    // ComplexNumber Calculate(ComplexNumber num1, ComplexNumber num2); // up to you
}

class AddOperator : IOperator
{
    public AddOperator() { }

    public double Calculate(double num1, double num2)
    {
        return num1 + num2;
    }

    // ComplexNumber Calculate(ComplexNumber num1, ComplexNumber num2) { ... }
}

class MinusOperator : IOperator
{
    public MinusOperator() { }

    public double Calculate(double num1, double num2)
    {
        return num1 - num2;
    }

    // ComplexNumber Calculate(ComplexNumber num1, ComplexNumber num2) { ... }
}

// ...

Factory use to create instance:

static class Factory
{
    public static T CreateInstance<T>() where T : new()
    {
        return new T();
    }
}

Client:

static void Main(string[] args)
{
    IOperator op = Factory.CreateInstance<AddOperator>();
    Console.WriteLine(op.Calculate(1, 2));

    // Console.WriteLine(op.Calculate(complexNum1, complexNum2));

    Console.Read();
}

Now, if I want to add an operator, just add a suboperator class and implement the IOperator. Overload method will determine calculate simple or complex.

This is a update version base on Facotry Method use Generic Type.


答:
Given you can "link" to the source code:

If you are releasing your program under the GNU AGPL, and it can
  interact with users over a network, the program should offer its
  source to those users in some way. For example, if your program is a
  web application, its interface could display a “Source” link that
  leads users to an archive of the code. The GNU AGPL is flexible enough
  that you can choose a method that's suitable for your specific
  program—see section 13 for details. source

There's no reason that you shouldn't be able to link to the GPL to avoid the download hit per load for your JS app.

include a copy of the license itself somewhere in the distribution of
  your program.

Just means to download and link to the GPL locally within your system; aka website, git, etc.

Where must one put the license notification?

It is sufficient to put the full license notice in the “main” file of
  your document. For example, with the Emacs Lisp Reference Manual, we
  have many files included by elisp.texi. We keep the full notification
  in elisp.texi, and in the other files we simply write:

@c --texinfo-- @c This is part of the GNU Emacs Lisp Reference
  Manual. @c Copyright (C) 1990, 1991, 1992, 1993, 1994, 1999 @c   Free
  Software Foundation, Inc. @c See the file elisp.texi for copying
  conditions.

source

Again, this points to it being fine to place the full license notice in a file that's referenced as needed.

Title: Do I have to include the license text when I GPL a web page?

Body:
I want to GPL some standalone web pages containing my Javascript/D3.js source code.  How to use GNU licenses for your own software says that to distribute source code under the GPL, I should "include a copy of the license itself somewhere in the distribution of your program."

I could bundle up the web pages into a distribution, e.g. in a github repo, and include
the license file there.  However, in practice, I am actually distributing the source files individually: They're up on the web.  It sounds as if should include the entire license in each of the HTML files (e.g. as a comment in the HTML), making the source file five or six times larger.

I'll of course include a copyright notice, stating that the source is distributed under the GPL, but do I really have to include the entire GPL text in the page source? Can't I just provide a URL to the GPL?

I was unable to find anything relevant to this question in the GPL FAQ.


答:
An oft-taught rule of thumb in programming classes, and a generally handy way to think about it, is this:

If you aren't sure how many times a loop might run (it could be one time or a hundred times, like when searching for something in a tree), use while().

If you you can define precisely how many times a loop will execute, such as 10 times, or on a set range of items (like the first n items of a list), use for().

Strictly speaking, you don't need for or while loops in any language that has goto or repeatedly executed main method.

while loops also have the dubious distinction of being probably the most common source of infinite loop bugs in modern programming languages, and they tend to expand the current scope with unneeded iterator variables unless you use a closure (and a language that supports closures, of course). For beginners, they can be a real pain.

For experienced programmers, it's best to understand the idioms of the language and what each type of loop is commonly understood to represent, and to avoid shoe-horning one's one personal preferences onto every problem if the code is ultimately meant for other people's consumption.

I, on the other extreme, tend to prefer for and foreach or for-range (in languages that have them) and have to force myself to use while loops when they seem most appropriate.

It need not be a religious thing - just learn the use of all basic building blocks of language and especially all the finer ins and outs of control structures when you can, and you'll find it's time very well spent.

Title: Why are for loops needed?


问:
Is it better to have separate functions or add more arguments to a function?
Which is the better style to follow for say, changing the voltage on a 4 channel PSU:

```<code>setChannelOneVoltage(voltage)
setChannelTwoVoltage(voltage)
setChannelThreeVoltage(voltage)
setChannelFourVoltage(voltage)
</code>```

or

```<code>setVoltage(channel,voltage)
</code>```

答:
Both.

Use wrapper functions with few parameters to create intuitivity, call a single function with many parameters inside the wrappers to provide compact, coherent code.


答: Under the assumption that the implementations would be very similar, I would suggest having one function so for the sake of DRY. It is however also legitimate to use wrapper functions around this function to make your code more instantly readable</p>

Title: Is it better to have separate functions or add more arguments to a function?

Body:
Which is the better style to follow for say, changing the voltage on a 4 channel PSU:

```<code>setChannelOneVoltage(voltage)
setChannelTwoVoltage(voltage)
setChannelThreeVoltage(voltage)
setChannelFourVoltage(voltage)
</code>```

or

```<code>setVoltage(channel,voltage)
</code>```


答:
I would definitely recommend the latter variant.

It's more flexible. What if you adopt the code for another device which has not just 4 but 8, 16, 32 or even more channels? You would have to add more and more methods and your code would become more and more convoluted. The code could not be shared between the devices, because you would end up with invalid methods. But when your code leaves the number of channels open, you can use the same code for any device.

When you need to set the voltage on multiple channels at the same time (either all to the same value or to different values read from a data structure), you can do this with a simple for-loop. The first version would require to call every single method separately.

By the way, for better code readability, you can replace the channel numbers by constants when you want to. This code might be ambiguous:

```<code>setVoltage(2, 4);  // Does this set channel 2 to 4V or channel 4 to 2V?
</code>```

But this is much more readable:

```<code>setVoltage(CHANNEL_2, 4); // OK, channel 2 is now 4V, but what does channel 2 actually do?
</code>```

This is even more readable:

```<code>setVoltage(FLUX_CAPACIATOR_CHANNEL, 4); // Puts 4V on the Flux Capaciator -- Captain Obvious
</code>```

Body:
I would definitely recommend the latter variant.

It's more flexible. What if you adopt the code for another device which has not just 4 but 8, 16, 32 or even more channels? You would have to add more and more methods and your code would become more and more convoluted. The code could not be shared between the devices, because you would end up with invalid methods. But when your code leaves the number of channels open, you can use the same code for any device.

When you need to set the voltage on multiple channels at the same time (either all to the same value or to different values read from a data structure), you can do this with a simple for-loop. The first version would require to call every single method separately.

By the way, for better code readability, you can replace the channel numbers by constants when you want to. This code might be ambiguous:

setVoltage(2, 4);  // Does this set channel 2 to 4V or channel 4 to 2V?

But this is much more readable:

setVoltage(CHANNEL_2, 4); // OK, channel 2 is now 4V, but what does channel 2 actually do?

This is even more readable:

setVoltage(FLUX_CAPACIATOR_CHANNEL, 4); // Puts 4V on the Flux Capaciator -- Captain Obvious


答:
If you are using an object oriented language, could it make sense to make the channel an object?</p>

```<code>channels = new Channel[4];
channels[0] = new Channel();
...
channels[0].SetVoltage(220);
</code>```

Body:
If you are using an object oriented language, could it make sense to make the channel an object?

channels = new Channel[4];
channels[0] = new Channel();
...
channels[0].SetVoltage(220);


答:
This depends on the context. Both options have its pros and cons and tradeoffs are to be made.

Both at once

Freedom of choice - allowing setChannelOneVoltage(220) as well as setVoltage(1, 220).

Everybody's happy!

But it invites inconsistency. One programmer will be using the former, perhaps unaware of the shortcut, another will prefer the latter.

Third programmer comes over, searches for all usages of setChannelOneVoltage (for some reason) and it may not occur to him that he's overlooking setVoltage(1... calls.

Is it a dealbreaker? No, but it should be taken into account. Every optional shortcut will be used inconsistently and therefore add a bit of noise.

A pet peeve of mine is the coexistence of collection.size() == 0 and collection.isEmpty(), for example. It's noisy. But since both options are equally valid, enforcing a consistent convention is hard, as it boils down to one's taste ultimately.

Shortcut methods only

Now we are hiding the setVoltage(x implementation and only make it accessible by our sugar shortcuts.

But what if you need to quickly set voltage on all channels? Instead of a simple loop, you are now writing:

```<code>setChannelOneVoltage(voltage)
setChannelTwoVoltage(voltage)
setChannelThreeVoltage(voltage)
setChannelFourVoltage(voltage)
</code>```

Okay, we can enwrap this into another shortcut function: setAllChannelsVoltage.

But what if we need to set all channels apart from number 1? Do we follow up with another helper method: setAllChannelsButTheFirst...

Depending on the nature of the task, it may be hard to maintain.

Only the raw, parameterized method

It is now hard to find all usages of setVoltage(1.... You need to resort to text search, and it will fail in case of i = 1; setVoltage(i, 220) or some other of all the endless possibilities.

It makes code more abstract and adds to the number of parameters - if it's a choice between one or two, that's not a big deal, but if the number of parameters has grown beyond that already, you should think twice every time before adding just one more.

If there is only ever 4 channels and no more, setVoltage(int channel puts the code at risk of out of range exceptions, which you are protected from by design if you only provide shortcuts.

Code that contains setVoltage(5 will compile and crash in runtime, but it won't build at all if it contains a call to setChannelFiveVoltage as the method doesn't exist, making the error much easier to catch out.

To sum up

Chosing one of these design approaches requires us to answer certain questions.

Is setting voltage on channel 2 or 3 a special case in its own right so that we might want to identify it in code and easily distinguish from all the others?

Is it likely that we will need to iterate over these channels and set their voltage conditionally?

Or that we would be setting the voltage of a channel whose ordinal number is computed or derived from some other data?

Has the parameterized version been already in use for some time? In such case the resulting inconsistency would strike us harder, because preexisting code won't be using the shortcuts and other programmers won't be used to them either, and stick to what they know.

In other words - which of the pros and cons that I listed above applies in your situation and to what extent? Some may be relevant, while others not so much. Calculate the tradeoffs for the task at hand, there is no silver bullet here; YMMV.

Body:
This depends on the context. Both options have its pros and cons and tradeoffs are to be made.

Both at once

Freedom of choice - allowing setChannelOneVoltage(220) as well as setVoltage(1, 220).

Everybody's happy!

But it invites inconsistency. One programmer will be using the former, perhaps unaware of the shortcut, another will prefer the latter.

Third programmer comes over, searches for all usages of setChannelOneVoltage (for some reason) and it may not occur to him that he's overlooking setVoltage(1... calls.

Is it a dealbreaker? No, but it should be taken into account. Every optional shortcut will be used inconsistently and therefore add a bit of noise.

A pet peeve of mine is the coexistence of collection.size() == 0 and collection.isEmpty(), for example. It's noisy. But since both options are equally valid, enforcing a consistent convention is hard, as it boils down to one's taste ultimately.

Shortcut methods only

Now we are hiding the setVoltage(x implementation and only make it accessible by our sugar shortcuts.

But what if you need to quickly set voltage on all channels? Instead of a simple loop, you are now writing:

setChannelOneVoltage(voltage)
setChannelTwoVoltage(voltage)
setChannelThreeVoltage(voltage)
setChannelFourVoltage(voltage)

Okay, we can enwrap this into another shortcut function: setAllChannelsVoltage.

But what if we need to set all channels apart from number 1? Do we follow up with another helper method: setAllChannelsButTheFirst...

Depending on the nature of the task, it may be hard to maintain.

Only the raw, parameterized method

It is now hard to find all usages of setVoltage(1.... You need to resort to text search, and it will fail in case of i = 1; setVoltage(i, 220) or some other of all the endless possibilities.

It makes code more abstract and adds to the number of parameters - if it's a choice between one or two, that's not a big deal, but if the number of parameters has grown beyond that already, you should think twice every time before adding just one more.

If there is only ever 4 channels and no more, setVoltage(int channel puts the code at risk of out of range exceptions, which you are protected from by design if you only provide shortcuts.

Code that contains setVoltage(5 will compile and crash in runtime, but it won't build at all if it contains a call to setChannelFiveVoltage as the method doesn't exist, making the error much easier to catch out.

To sum up

Chosing one of these design approaches requires us to answer certain questions.

Is setting voltage on channel 2 or 3 a special case in its own right so that we might want to identify it in code and easily distinguish from all the others?

Is it likely that we will need to iterate over these channels and set their voltage conditionally?

Or that we would be setting the voltage of a channel whose ordinal number is computed or derived from some other data?

Has the parameterized version been already in use for some time? In such case the resulting inconsistency would strike us harder, because preexisting code won't be using the shortcuts and other programmers won't be used to them either, and stick to what they know.

In other words - which of the pros and cons that I listed above applies in your situation and to what extent? Some may be relevant, while others not so much. Calculate the tradeoffs for the task at hand, there is no silver bullet here; YMMV.


问:
Is creating subclasses for specific instances a bad practice?
Consider the following design

```<code>public class Person
{
    public virtual string Name { get; }

    public Person (string name)
    {
        this.Name = name;
    }
}

public class Karl : Person
{
    public override string Name
    {
        get
        {
            return "Karl";
        }
    }
}

public class John : Person
{
    public override string Name
    {
        get
        {
            return "John";
        }
    }
}
</code>```

Do you think there is something wrong here? To me Karl and John classes should be just instances instead of classes as they are exactly the same as :

```<code>Person karl = new Person("Karl");
Person john = new Person("John");
</code>```

Why would I create new classes when instances are enough? The classes does not add anything to the instance.

答:
There is a use case: forming a reference to a function or method as a regular object.

You can see this in Java GUI code a lot:

```<code>ActionListener a = new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        /* ... */
    }
};
</code>```

The compiler helps you here by creating a new anonymous subclass.

Body:
There is a use case: forming a reference to a function or method as a regular object.

You can see this in Java GUI code a lot:

ActionListener a = new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {
        /* ... */
    }
};

The compiler helps you here by creating a new anonymous subclass.


答:
The question is twofold. For the current example and the given set of circumstances, use approach 2. In a more general sense the answer would be "it depends" and there are more approaches than just two.

Some more variants on the topic:

Approach 3

```<code>setVoltage( channel, voltage)
setMaxCurrent( channel, maxCurrent)
setMaxWorkingTime( channel, maxHours)
setChannelSettings( channel, voltage, maxCurrent = null, maxHours = null)
</code>```

That one is good if only a few args come into play. It quickly becomes ugly with more than 3 or 4 args.

Approach 4

```<code>struct settings {
  int channel
  nullable double voltage
  nullable double maxCurrent
  nullable double maxHours
  // add new fields here
}

setVoltage( List<settings> settings)
setVoltage( settings)
</code>```

Easily extendable, can be made forward-compatible, but requires the caller to set up a rather complex structure for each call. The list<> version enables to set all values with one call, which may be important if the call is expensive, e.g. if it is an RPC with high latencies.

... and so on. As you see, all approaches have their own advantages and disadvantages, and the question Which option is better? should always be completed with Which option is better for that particular purpose, use case and set of restrictions that we face?.

Body:
The question is twofold. For the current example and the given set of circumstances, use approach 2. In a more general sense the answer would be "it depends" and there are more approaches than just two.

Some more variants on the topic:

Approach 3

setVoltage( channel, voltage)
setMaxCurrent( channel, maxCurrent)
setMaxWorkingTime( channel, maxHours)
setChannelSettings( channel, voltage, maxCurrent = null, maxHours = null)

That one is good if only a few args come into play. It quickly becomes ugly with more than 3 or 4 args.

Approach 4

struct settings {
  int channel
  nullable double voltage
  nullable double maxCurrent
  nullable double maxHours
  // add new fields here
}

setVoltage( List<settings> settings)
setVoltage( settings)

Easily extendable, can be made forward-compatible, but requires the caller to set up a rather complex structure for each call. The list<> version enables to set all values with one call, which may be important if the call is expensive, e.g. if it is an RPC with high latencies.

... and so on. As you see, all approaches have their own advantages and disadvantages, and the question Which option is better? should always be completed with Which option is better for that particular purpose, use case and set of restrictions that we face?.


答:
You could use an enumeration for your channel:

```<code>enum Channel
{
    C1,
    C2,
    C3,
    C4
};
</code>```

then you can use a single method:

```<code>setVoltage(Channel.C1,voltage);
setVoltage(Channel.C2,voltage);
setVoltage(Channel.C3,voltage);
setVoltage(Channel.C4,voltage);
</code>```

and you can use it in a loop:

```<code>for(Channel channel = Channel.C1; channel <= channel.C4; channel++)
{
    setVoltage(channel,voltage);
}
</code>```

Body:
You could use an enumeration for your channel:

enum Channel
{
    C1,
    C2,
    C3,
    C4
};

then you can use a single method:

setVoltage(Channel.C1,voltage);
setVoltage(Channel.C2,voltage);
setVoltage(Channel.C3,voltage);
setVoltage(Channel.C4,voltage);

and you can use it in a loop:

for(Channel channel = Channel.C1; channel <= channel.C4; channel++)
{
    setVoltage(channel,voltage);
}


答:
Assuming that all channels are same, setChannelOneVoltage(voltage) and setChannelTwoVoltage(voltage) are doing the same, but on different channels. If you now can identify those channels easily by a function that takes the channel number as the argument, the second approach, using setVoltage(channelNo,voltage) would be the better one, mainly because of DRY and flexibility.

If identifying the channels is more complex (and perhaps different for each channel), you should consider to wrap each channel into an object. But then again, the second approach would be the better one, now with setVoltage(channelObj,voltage).

But if setting the voltage is significantly different for each channel, the first approach would be better; having a distinct function/method for each channel is better than a construct like

```<code>setVoltage( channel, voltage )
{
   switch( channel )
   {
      case 1: // do it for channel 1
        // Lengthy, complex code going here ...
      case 2: // do it for channel 2
        // Lengthy, complex code going here ...
      ...
   }
}
</code>```

But for convenience, you can offer a setVoltage(channel,voltage) method even in this scenario; it calls the setChannel#Voltage(voltage) methods in a switch - or using reflection, if your programming language do provide such a feature - in C, you can implement something like that as a macro instead.

An alternative approach for an object oriented language would be to define a Channel interface class and setVoltage(voltage) as one of the methods. This would address DRY and flexibility as well as all the distinctions that the different channels may have in retrieval and/or setting the voltage.

Body:
Assuming that all channels are same, setChannelOneVoltage(voltage) and setChannelTwoVoltage(voltage) are doing the same, but on different channels. If you now can identify those channels easily by a function that takes the channel number as the argument, the second approach, using setVoltage(channelNo,voltage) would be the better one, mainly because of DRY and flexibility.

If identifying the channels is more complex (and perhaps different for each channel), you should consider to wrap each channel into an object. But then again, the second approach would be the better one, now with setVoltage(channelObj,voltage).

But if setting the voltage is significantly different for each channel, the first approach would be better; having a distinct function/method for each channel is better than a construct like

setVoltage( channel, voltage )
{
   switch( channel )
   {
      case 1: // do it for channel 1
        // Lengthy, complex code going here ...
      case 2: // do it for channel 2
        // Lengthy, complex code going here ...
      ...
   }
}

But for convenience, you can offer a setVoltage(channel,voltage) method even in this scenario; it calls the setChannel#Voltage(voltage) methods in a switch - or using reflection, if your programming language do provide such a feature - in C, you can implement something like that as a macro instead.

An alternative approach for an object oriented language would be to define a Channel interface class and setVoltage(voltage) as one of the methods. This would address DRY and flexibility as well as all the distinctions that the different channels may have in retrieval and/or setting the voltage.


答:
If you're using c#, make an extension method.
that would allow you to do this:
    var channel1 = new channel(...);
    channel1.SetVoltage(15);

```<code>var channel2 = new channel();
channel2.SetVoltage(56);
</code>```

some more info on extension methods: http://msdn.microsoft.com/en-us/library/bb383977.aspx

Body:
If you're using c#, make an extension method.
that would allow you to do this:
    var channel1 = new channel(...);
    channel1.SetVoltage(15);

var channel2 = new channel();
channel2.SetVoltage(56);

some more info on extension methods: http://msdn.microsoft.com/en-us/library/bb383977.aspx


问:
Distributivity and Associativity for 32/64bit signed integers
I'm looking into 32/64bit signed integers and their algebraic properties. I am quite sure that the the three operators +, - and * fulfill the distributive and associative property (integer division does not because of the information loss) even though we have some kind of information loss due to wrapping of positive <-> negative numbers.

What I'm looking for is some kind of academic publication (if it is not too trivial) that addresses this issue and provides some proof or counterexample.

答:
Integers modulo n (ℤ/nℤ) with addition and multiplication form a Commutative Ring, where multiplication distributes over addition. If n is prime, they even form a finite field.

I don't see why subtracting n/2 from every number (to make it signed) would necessarily change that.

For a definitive answer, Mathematics.SE is probably the better audience.


问:
Patterns for creating adaptive web crawler throttling
Im running a service that crawls many websites daily. The crawlers are run as jobs processed by a bunch of independent background worker processes, that picks up the jobs as they get enqueued.

Now currently I'm doing throttling "in-process" meaning that the threads will do a random sleep between each request. However having many asynchronous background workers running, that from time to time might be processing jobs for the same domain, is causing concurrency trouble, and I need a central monitoring system that my workers can talk to and get directions from. I have been looking into a few patterns e.g. leaky bucket and rate limiting using redis, feeling that I have still to find the silver bullet.

My main concern is, that not only do I have to track the requests and throttle them, but I also need to capture feedback like response code 429's and use it to adapt the rate level on a domain-individual basis.

Do any of you have some good ideas as to patterns you have used, good resources on the topic, general advice and other recommendations.

Thanks!

答:
I would like to suggest an architecture that scales reasonably well, and performs faster than random sleeps.

Each domain is associated with a queue of known pages that are to be crawled, and two additional fields:

The time between requests for this domain.

The earliest time when the next page can be requested.

We now have a priority queue of domains. In this queue, the domains are sorted by the time for the next request. These domain objects are units of work. The worker threads take units of work from the queue, with the queue guaranteeing this will be the earliest domain where the next request shall be made. When a worker receives an unit of work, it first checks whether the specified request time lies in the future. If so, the thread sleeps until then. Otherwise/afterwards:

The next page for that domain is requested and processed. Possibly, new pages are added to that domain to be crawled.

If the server requests rate limiting, then the time between requests for that domain is increased.

The unit of work is given back to the job queue, and a new job is requested.

When the job queue receives back ownership of the domain object, it first checks whether there are any further pages to be crawled. If so, then the time for the next request is calculated. This may be the time between requests added to the time of the previous request, or a random value with that time being the minimum or mean.

This architecture has the advantage that ownership is clearly defined, so only one thread is making requests to any given domain at a time. The disadvantages are the job queue thread doing a lot of work, and the overhead of communication between threads.

There is an additional point to take care of: How are pages to be crawled added to a domain that is still unknown to the system, or that is currently owned by another thread? This should be handled by the job queue in order to avoid concurrency issues.

Performance can be increased by having each worker thread request multiple pages simultaneously using asynchronous operations. This way, the time between sending an HTTP request and receiving an response can be used for working on other things.


问:
Derive subset with sum between two values
I have a set S of size n whose members each have associated with them a number in the range 0.00 to 1.00 inclusive.

I want to select a subset T of size m with this property:

the average of the numbers associated with the members of T must fall within a specified range x to y (for example, 0.65 to 0.75). Expressed differently: the sum of the numbers associated with the members of T must fall within a specified range (for example, 0.65m to 0.75m)

Further, out of all the possible Ts for a given S, x, y, I want to choose one (uniformly) randomly.

My current method is to randomly select m members of S, and then check if the sum falls in the desired range. I repeat until I get a satisfactory result.  Is there an algorithm (possibly dynamic programming?) to get the desired subset without using guess and check?

Example:

S is a set of n = 200 questions, each assigned a difficulty rating between 0 and 1 inclusive. I want to generate a test T with m = 50 questions where the average difficulty is between 0.65 and 0.75 inclusive. Furthermore I want to select a (uniformly) random T, out of all the possible T's that satisfy my conditions.

Another Example:

```<code>S = {0.1, 0.3, 0.5, 0.8, 1.0}
n = 5
m = 3
x = 0.5
y = 0.75

All possible T and their average value
{0.1, 0.3, 0.5} = 0.8 / 3 = 0.26
{0.1, 0.3, 0.8} = 1.2 / 3 = 0.40
{0.1, 0.3, 1.0} = 1.4 / 3 = 0.46
{0.1, 0.5, 0.8} = 1.4 / 3 = 0.46
{0.1, 0.5, 1.0} = 1.6 / 3 = 0.53
{0.1, 0.8, 1.0} = 1.9 / 3 = 0.63
{0.3, 0.5, 0.8} = 1.6 / 3 = 0.53
{0.3, 0.5, 1.0} = 1.8 / 3 = 0.60
{0.3, 0.8, 1.0} = 2.1 / 3 = 0.70
{0.5, 0.8, 1.0} = 2.3 / 3 = 0.76

Subsets of S with size m with average values between x and y
{0.1, 0.5, 1.0}
{0.1, 0.8, 1.0}
{0.3, 0.5, 0.8}
{0.3, 0.5, 1.0}
{0.3, 0.8, 1.0}
</code>```

I am trying to come up with an algorithm to produce one of these 5 subsets at random, without first calculating every subset of S with size m.  It seems that guess and check is the best method.

答:
I do not think it is possible to deterministically build such a random set in "one go", whatever it exactly means. However here is what I think is the closest alternative:

Start with N random numbers. As long as your average is not satisfying, randomly remove a number and replace it with a smaller/larger one. To quickly find the numbers to remove and their substitutes you could either split both your input and output sets in two (numbers below the wanted average versus numbers above the wanted average), or you could sort the input set and use binary searches.

An alternative yet similar idea is to start with an empty set and add "small" or "big" numbers depending on your current average. However you could find yourself with an invalid set in the end and you would then have to resort to method #1, so I think it is more elegant to only use #1.

Finally, regarding redundant values, I suggest to use a pre-processing step: sort your input set, then scan it to find redundant items and randomly pick one.

Rephrased to clarify things up.


问:
Should foreign keys be represented directly when mapping database tables to classes?
Ok, in my database I have a table Event and a table Room. Each Room can have many Event.

```
Room table
roomID-roomName
1     - cafe102
...

Event table
eventID- Time  -type -roomID
1      - 11:20 - 1   - 1
2      - 15:20 - 1   - 1
...
```

So I want to crate a Class structure that mimics the DB structure.

```<code>public class Event{
  private int eventID;
  private String time;
  private int roomID; // or
  private Room room;
  public Event(){
  }
  /// all set and get methods here
}

public class Room{
  private int roomID;
  private String roomName;
  public Room(){
  }
  //all Set and Get methods here
}
</code>```

My question is, in the Event class, should I have type private int roomID; or     private Room room;?

Also is there any reason to put private Event event; into Room class? Or does it just depend on the need and there is no standard?

答:
I do not understand why you would need to have the roomID on the Event on the code itself (you use this relationship just for the DB). I would rather say that you can point directly to the Room Object. (private Room room );

Now, the second question why would you put an Event attribute to a Room? I would say that you can create in your application a list of Events which have the same room, but I do not understand why you would say that a Room have events. Maybe the concept of the room is the list of events it contains?

I hope this helps.


答: If you need a reference to an Event in your Room class I see no reason why you shouldn't. In ORM's such as EntityFramework in .NET, ActiveRecord in Ruby, this is allowed, so I guess it is OK to do it.

Title: Should foreign keys be represented directly when mapping database tables to classes?

Body:
Ok, in my database I have a table Event and a table Room. Each Room can have many Event.

```
Room table
roomID-roomName
1     - cafe102
...

Event table
eventID- Time  -type -roomID
1      - 11:20 - 1   - 1
2      - 15:20 - 1   - 1
...
```

So I want to crate a Class structure that mimics the DB structure.

```<code>public class Event{
  private int eventID;
  private String time;
  private int roomID; // or
  private Room room;
  public Event(){
  }
  /// all set and get methods here
}

public class Room{
  private int roomID;
  private String roomName;
  public Room(){
  }
  //all Set and Get methods here
}
</code>```

My question is, in the Event class, should I have type private int roomID; or     private Room room;?

Also is there any reason to put private Event event; into Room class? Or does it just depend on the need and there is no standard?


答:
ID is a way for the database to connect a room to an event, there's no need to duplicate that in the class. So I'd definitely choose private Room room;. This will create a much better object model than having a bunch of IDs.

As to your other question, I'd say it depends on your needs whether you need a two-way reference or not. From modeling point of view it seems more natural that an event has a room assigned and the room doesn't need to know the events. But if you need to show the booking status of a particular room or something like that, then adding the reference might be a good idea.

However, you should notice that it's a one-to-many relationship, so one room can have more than one event. So if you want the Room class to know the related events, your variable needs to be private List<Event> events; (of course it can also be some other structure than a list).


问:
C++ Chess board design and smart pointers
I wrote a Chess engine in Java and I am porting it over to C++. I am new to C++.

The idea:

I have a Board object which holds a 2-dimensionnal array of Piece objects. Queen, Rook, Bishop, etc are subclasses of Piece. They all have a method getPossibleMoves(). Therefore they need to have a reference to the board to be able to generate the possible moves.

The implementation:

Board class:

```<code>class Board
{
public:
    using PiecePtr = std::shared_ptr<Piece>;
    std::array<std::array<PiecePtr, BOARD_SIZE>, BOARD_SIZE> myPieces;
};
</code>```

Piece class:

```<code>class Piece
{
public:
    std::weak_ptr<Board> myBoard
};
</code>```

I used shared_ptr and weak_ptr because the Board can/should exist whitout Pieces. Is this approach correct?

Note: I know this OOP approch to represent the chess board is not the best for performance. Other approaches (Bitboards for instance) will be more efficient.

答:
A small "being there, done that" suggestion... migrating my chess engine from a 0x88 board representation to bitboard was relatively simple. Obtaining a performance improvement was way harder than I expected.

The fact is that you can have a wonderful design for your board/piece class, perfect modularity, minimum dependencies among classes... but it's sure that you must have arranged your evaluation logic depending on what you can do fast or slow (and this is linked to board representation).

Changing the board representation will trigger changes in the static evaluation logic: that's complex, time consuming and risky.

Moreover, while you change the evaluation logic, you discover that some search extensions aren't needed anymore or that you need a better quiescence search.

Eventually you could have a completely different player.

So you can start with a "temporary" board representation but everything should be done bearing in mind the final representation (strong/weak points of a representation you are not using could be unexpected).

Your implementation is the typical Team/Members relationship.
The Team object (the board) will have pointers to its Members (the pieces) and the members will also have a back pointer to their Team object.

So weak_ptr is used to break the dependency cycle: the "owner" use shared_ptr and the "owned" use a weak_ptr to its parent and convert it temporarily to shared_ptr when it needs access to its parent.

So, from this point of view, it's a correct implementation.

However the getPossibleMoves() function will need the piece position to perform its task.

The function could find out the position scanning the board but this would slow down the move generation. To avoid data redundancy you shouldn't store the coordinates inside Piece and getPossibleMoves() will need two arguments:

```<code>std::list<Move> ThePiece::getPossibleMoves(unsigned row, unsigned column)
{
  // ...
}

// ...
Board b;
// ...
auto moves = b[row][column]->getPossibleMoves(row, column);
</code>```

Now why not remove the myBoard injected dependency from Piece and add one more argument to getPossibleMoves?

```<code>std::list<Move> ThePiece::getPossibleMoves(const Board &b, unsigned row, unsigned column)
{
  // ...
}
</code>```

After this change the shared_ptr aren‘t required anymore... along this way we‘re going to completely change the design.

Body:
A small "being there, done that" suggestion... migrating my chess engine from a 0x88 board representation to bitboard was relatively simple. Obtaining a performance improvement was way harder than I expected.

The fact is that you can have a wonderful design for your board/piece class, perfect modularity, minimum dependencies among classes... but it's sure that you must have arranged your evaluation logic depending on what you can do fast or slow (and this is linked to board representation).

Changing the board representation will trigger changes in the static evaluation logic: that's complex, time consuming and risky.

Moreover, while you change the evaluation logic, you discover that some search extensions aren't needed anymore or that you need a better quiescence search.

Eventually you could have a completely different player.

So you can start with a "temporary" board representation but everything should be done bearing in mind the final representation (strong/weak points of a representation you are not using could be unexpected).

Your implementation is the typical Team/Members relationship.
The Team object (the board) will have pointers to its Members (the pieces) and the members will also have a back pointer to their Team object.

So weak_ptr is used to break the dependency cycle: the "owner" use shared_ptr and the "owned" use a weak_ptr to its parent and convert it temporarily to shared_ptr when it needs access to its parent.

So, from this point of view, it's a correct implementation.

However the getPossibleMoves() function will need the piece position to perform its task.

The function could find out the position scanning the board but this would slow down the move generation. To avoid data redundancy you shouldn't store the coordinates inside Piece and getPossibleMoves() will need two arguments:

std::list<Move> ThePiece::getPossibleMoves(unsigned row, unsigned column)
{
  // ...
}

// ...
Board b;
// ...
auto moves = b[row][column]->getPossibleMoves(row, column);

Now why not remove the myBoard injected dependency from Piece and add one more argument to getPossibleMoves?

std::list<Move> ThePiece::getPossibleMoves(const Board &b, unsigned row, unsigned column)
{
  // ...
}

After this change the shared_ptr aren‘t required anymore... along this way we‘re going to completely change the design.


答:
Please review the background and use cases for weak_ptr. I don’t think this is one of them.

weak_ptr is typically used for as a cache. The owner of the weak_ptr must be ok with the weak_ptr being null. If the weak_ptr is null, the owner can adapt by constructing a new instance or otherwise operating differently.

In your case, a Piece cannot operate without a Board. The weak_ptr should be a smart_ptr.

I would go farther and say that you should not be using pointers at all. The entire system is well defined without any pointers. Try an entirely value based design. For example, the Board for the pieces could be a reference instead of a pointer.

Title: C++ Chess board design and smart pointers

Body:
I wrote a Chess engine in Java and I am porting it over to C++. I am new to C++.

The idea:

I have a Board object which holds a 2-dimensionnal array of Piece objects. Queen, Rook, Bishop, etc are subclasses of Piece. They all have a method getPossibleMoves(). Therefore they need to have a reference to the board to be able to generate the possible moves.

The implementation:

Board class:

```<code>class Board
{
public:
    using PiecePtr = std::shared_ptr<Piece>;
    std::array<std::array<PiecePtr, BOARD_SIZE>, BOARD_SIZE> myPieces;
};
</code>```

Piece class:

```<code>class Piece
{
public:
    std::weak_ptr<Board> myBoard
};
</code>```

I used shared_ptr and weak_ptr because the Board can/should exist whitout Pieces. Is this approach correct?

Note: I know this OOP approch to represent the chess board is not the best for performance. Other approaches (Bitboards for instance) will be more efficient.


问:
Third Party web controls and tight coupling

Disclaimer: I am not against third-party controls because I believe it's for productivity

I have used Telerik asp.net controls, especially the RadGrid because it makes it easier to do CRUD. They have fantastic controls.

I thought I would do the same for asp.net mvc but looking at the code involved scares me.

I saw another site (syncfusion.com) today offering the same mvc controls and when you look at the UI, they are appealing and so arethe functions/features.

My issue with these nice/appealing controls are:

I feel like it is taking the control I have over the HTML which is one of the benefits of asp.net mvc

I cannot see the HTML until the page is run, and viewing the source code

I feel there is a coupling between the data and the design. The web designer needs to learn Telerik/Syncfusion way of doing things. He won't be able to use the HTML he is familiar with

Razor looks like a template mixing with HTML and can be replaced with hand-coded value for presentation and testing which can be replace later

I believe the following code has taken over my HTML and I have little control over them

@section SampleHeading{ Grid/Data Binding/Remote Data}
@section ControlsSection{
@(Html.EJ().Grid<OrdersView>("RemoteBinding")
    .Datasource("http://mvc.syncfusion.com/Services/Northwnd.svc/Orders/")
    .AllowPaging()
    .PageSettings(page => { page.PageSize(9); })
    .Columns(col =>
    {
        col.Field("CustomerID").HeaderText("Customer ID").Width(90).Add();
        col.Field("EmployeeID").HeaderText("Employee ID").TextAlign(TextAlign.Right).Width(75).Add();
        col.Field("Freight").HeaderText("Freight").TextAlign(TextAlign.Right).Width(75).Format("{0:C}").Add();
        col.Field("ShipCity").HeaderText("Ship City").Width(100).Add();
        col.Field("OrderDate").Format("{0:MM/dd/yyyy}").Width(100).TextAlign(TextAlign.Right).Add();
        col.Field("ShipCountry").HeaderText("Ship Country").Width(100).Add();
    })
  )
}
```

Should one sacrifice simplicity/control over productivity? When and why?

答:
Short answer: yes.

While we'd all like to tinker around and build neat things there will always be the need of shipping the darn thing before going out of business.

Long answer: it depends.

Requirements and the skill level of the team can influence the decision of choosing one over the other, having both or having none.

With a tight deadline comes focus on productivity and little time to tinker. If the requirements restrict the use of third party controls (mostly because of the overhead on generated markup and resources) then the team is responsible of coming up with the needed components. If the requirements don't restrict the use of third party controls, then the logical decision would be to use some existing controls, as it will take longer to build new ones than customize what's already there.

Loose deadlines give some time to experiment and the decision can be made to build the controls instead of using existing ones. Experience can be gained from this and is beneficial to the team in the long run. Even so, third parties are chosen in most cases because there are so many things to consider when building custom controls and they might take longer to build than the entire application that is using them.

Note that third party controls are built with generality in mind and don't fit all the possible scenarios. Hence the multitude of configuration options available and the inherent (and apparent) complexity. And while they allow some degree of control over the generated markup it's not possible to get 100% due to the fact that some of that markup is vital to how they work.


答:
This is a case of premature over-design.

The pieces don't need a pointer to the board.  Just pass the board to the 'generateMoves' method.  You don't even need objects for the individual chessmen.  All pawns are alike, so you only need one Pawn instance.

Also, by the laws of chess, there is a game state that is also needed to correctly generate moves.  Pawns can capture e.p. but only after a previous two-square advance.  A king can castle with a rook but not if either has previously moved.

My suggestion is to forget all the class design stuff.  Start with a single ChessGame class with two methods: generateMoves and makeMove.  Write it test-first.  Start by only having two kings on the board.  Then add the different kinds of chessmen one at a time.  Extract classes as you find it convenient.


问:
Is there a programming pattern, design pattern, or naming convention for moving data between related schemas?
I'm working on a web application that is publicly accessible. (Really) Long story short, we have two sets of tables in the database with relatively the same names and relatively the same data. The first set of tables are used by our web site, which I will call Set A. The second set of tables are used by an Oracle Forms application, which I will call Set B.

The reasons for duplicated tables:

The data in Set B is the Holy Grail of information. Allowing the public to change this has legal repercussions.

The public can partially fill out all of the forms in our web application, and in one final button click, finalize their information. They then have to pay a fee before downstream processing begins. Users may start, stop and restart this process any number of times.

My current task is to copy data from Set B into Set A in one operation, so that form fields are pre-populated. If we don't do this, every page in our web application has to pull data from Set A first, and if it is missing fall back to Set B (which sometimes involves data conversions).

I have this built and functioning correctly, but I'm not real keen on the names I've used: *Converter

I'm really trying to avoid a "service" object. Having read I Shall Call It.. SomethingManager at Coding Horror, naming anything with the word "service" makes me want to write a sibling blog post titled "I Shall Call It.. SomethingService."

My lead developer didn't like the "Converter" naming convention. I've searched for programming and design patterns for moving data between similar tables and I haven't found anything.

I've thought about "Migration" but this implies changing the database schema iteratively over a period of time (ala Active Record Database Migrations).

Whatever the name or pattern is, I'd like it to clearly communicate:

Information is being pulled from one set of tables

Mapped to a common object model

And inserted into another schema

I also feel like I'm not the only person who has encountered this problem.

Is there a programming pattern, design pattern, or naming convention for moving data between related schemas?

Update: One of the biggest problems I have is that the web site tables (Set A) don't have primary or foreign keys! We have a bunch of meta data hidden in constants, whose values get mashed together sometimes into a single column.

@kevincline's answer to write a stored procedure is actually why I choose to handle this specific situation in code. We have a stored procedure to move data from Set A into Set B, and Oh. My. Goodness. The hoops the poor PL/SQL developer had to jump through to untangle our mess was nothing short of a miracle.

In this case, the code was much easier to write and maintain outside of the database because our web application ... well. Think of every database design best practice imaginable and then do exactly the opposite.

答:
A design pattern would probably be more applicable how you accomplished the goal in source code rather than describing the goal itself. It sounds like this could have been coded up using Adaptor or Strategy pattern, but again, that would depend on the code itself.

It sounds like you're looking for a name to describe the whole process, then want to apply that to the code to describe that "this is the part of the code that converts/translates data from B to A". Depends a lot on the codebase. But you might consider naming it based on the actual names. SetBConverter might not be so bad, depending on context. Or OracleToWebDataTranslator or whatever... (now just getting into total speculation).

In general, a lot of computer science can be boiled down to data transformations. Moving between related schemas is a little more specific, but I can't think of any specific terms to cover that off-hand.


问:
Comparing doubles
I need to compare to double variables like this

```<code>if (distance <= radius)
</code>```

both distance and radius are doubles and I remember in class how to use epsilon comparisons for checking equality but how would I do it for <= or >?

答: An epsilon is not relevant when you are checking which floating point value is bigger. It's only needed for equality, where (due to precision issues) your math may create two values which are supposed to be equal, but are slightly off.</p>

Title: Comparing doubles


答: I would just write a stored procedure to do this instead of getting application code involved.  It will be easier to develop and maintain and it will run faster.  You may need only a single MERGE statement for each destination table.</p>

Body:
I'm working on a web application that is publicly accessible. (Really) Long story short, we have two sets of tables in the database with relatively the same names and relatively the same data. The first set of tables are used by our web site, which I will call Set A. The second set of tables are used by an Oracle Forms application, which I will call Set B.

The reasons for duplicated tables:

The data in Set B is the Holy Grail of information. Allowing the public to change this has legal repercussions.

The public can partially fill out all of the forms in our web application, and in one final button click, finalize their information. They then have to pay a fee before downstream processing begins. Users may start, stop and restart this process any number of times.

My current task is to copy data from Set B into Set A in one operation, so that form fields are pre-populated. If we don't do this, every page in our web application has to pull data from Set A first, and if it is missing fall back to Set B (which sometimes involves data conversions).

I have this built and functioning correctly, but I'm not real keen on the names I've used: *Converter

I'm really trying to avoid a "service" object. Having read I Shall Call It.. SomethingManager at Coding Horror, naming anything with the word "service" makes me want to write a sibling blog post titled "I Shall Call It.. SomethingService."

My lead developer didn't like the "Converter" naming convention. I've searched for programming and design patterns for moving data between similar tables and I haven't found anything.

I've thought about "Migration" but this implies changing the database schema iteratively over a period of time (ala Active Record Database Migrations).

Whatever the name or pattern is, I'd like it to clearly communicate:

Information is being pulled from one set of tables

Mapped to a common object model

And inserted into another schema

I also feel like I'm not the only person who has encountered this problem.

Is there a programming pattern, design pattern, or naming convention for moving data between related schemas?

Update: One of the biggest problems I have is that the web site tables (Set A) don't have primary or foreign keys! We have a bunch of meta data hidden in constants, whose values get mashed together sometimes into a single column.

@kevincline's answer to write a stored procedure is actually why I choose to handle this specific situation in code. We have a stored procedure to move data from Set A into Set B, and Oh. My. Goodness. The hoops the poor PL/SQL developer had to jump through to untangle our mess was nothing short of a miracle.

In this case, the code was much easier to write and maintain outside of the database because our web application ... well. Think of every database design best practice imaginable and then do exactly the opposite.


答:
It depends on your definition of "<=".

If you want to declare them equal if they are within a certain distance of each other, then you would do:

```<code>if ((a < (b+epsilon)) do_whatever();
</code>```

This is counterintuitive, since it would accept a > b by less than epsilon, which is probably not what you want.  But it might be.

In general, talking about floating-point (which includes doubles) equality is meaningless.

Title: Comparing doubles

Body:
I need to compare to double variables like this

```<code>if (distance <= radius)
</code>```

both distance and radius are doubles and I remember in class how to use epsilon comparisons for checking equality but how would I do it for <= or >?

Body:
It depends on your definition of "<=".

If you want to declare them equal if they are within a certain distance of each other, then you would do:

if ((a < (b+epsilon)) do_whatever();

This is counterintuitive, since it would accept a > b by less than epsilon, which is probably not what you want.  But it might be.

In general, talking about floating-point (which includes doubles) equality is meaningless.


问:
Unit test private method in c++ using a friend class
I know that this is a debated practice, but let's suppose that this is the best option for me. I am wondering about what is the actual technique to do this. The approach that I see is this:

1) Make a friend class that of the class who's method I want to test.

2) In the friend class, create a public method(s) that call the private method(s) of the tested class.

3) Test the public methods of the friend class.

Here is a simple example to illustrate the above steps:

```<code>#include <iostream>

class MyClass
{
  friend class MyFriend; // Step 1

  private:
  int plus_two(int a)
  {
    return a + 2;
  }
};

class MyFriend
{
public:
  MyFriend(MyClass *mc_ptr_1)
  {
    MyClass *mc_ptr = mc_ptr_1;
  }

  int plus_two(int a) // Step 2
  {
    return mc_ptr->plus_two(a);
  }
private:
  MyClass *mc_ptr;
};

int main()
{
  MyClass mc;
  MyFriend mf(&mc);
  if (mf.plus_two(3) == 5) // Step 3
    {
      std::cout << "Passed" << std::endl;
    }
  else
    {
      std::cout << "Failed " << std::endl;
    }

  return 0;
}
</code>```

Edit:

I see that in the discussion following one of the answers people are wondering about my code base.

My class has methods that are called by other methods; none of these methods should be called outside the class, so they should be private. Of course they could be put into one method, but logically they are much better separate. These methods are complicated enough to warrant unit testing, and due to performance issues I will very likely have to re-factor these methods, hence it would be nice to have a test to make sure that my re-factoring didn't break anything. I am not the only one working on the team, though I am the only one who is working on this project including the tests.

Having said the above, my question was not about whether it is a good practice to write unit tests for private methods, though I appreciate the feedback.

答:
You shouldn't be testing private methods. Period. The classes using your class only care about the methods that it provides, not the ones it uses under the hood to work.

If you're worrying about your code coverage, you need to find configurations that allow you to test that private method from one of the public method calls. If you can't do that, what's the point of having the method in the first place? It's simply unreachable code.


问:
"Middle ground" architecture for client-server iOS apps?
I see two obvious approaches to the architecture for an iOS app which needs to talk to a server to do its job.

Pretend to be a web browser

Under this approach, the app fetches a chunk of data (typically JSON) from the server in response to a user action (navigating to a new view controller, tapping an "Update", whatever), puts up a spinner or some other progress indicator, then updates the view when the request completes. The "model" classes are mapped directly from the incoming JSON and possibly even immutable, and thrown away when the user moves off the screen they were fetched to populate.

Under the "pure" version of this approach you set the appropriate headers on the server and let NSURLSession and friends handle caching.

This works fine if you can assume the user has fast, low-latency network connectivity, and is mostly reading data from the server and not writing.

Sync

With the "sync" approach, the app maintains a local Core Data store of model objects to display to the user. It refreshes this either in response to user action or periodically, and updates the UI (via KVO or similar) when the model changes. When the user modifies the model, these changes are sent to the server asynchronously; there must be a mechanism for resolving conflicts.

This approach is more suitable when the app needs to function offline or in high latency/slow network contexts, or where the user is writing a lot of data and they need to see model changes without waiting for a server round-trip.

Is there a third in-between way? What if I have an app which is mostly but not always reads, but where there are writes the user should see those updates reflected in the UI immediately. The app should be usable in low/no network situations (showing any previously cached data until a request to the server has time to respond.)

Can I get the best of both worlds without going full Core-Data-with-sync (which feels heavyweight and is difficult to get right) but without also inadvertently implementing a buggy and incomplete clone of Core Data?

答:
Not from an effort perspective.  If you're implementing anything via a sync model, you need to build everything that entails.  You can optionally choose to allow - for some feeds - lazy loading on refresh if this is desirable from a performance standpoint (this is a common practice for small and obscure feeds that less than 50% of the userbase will ever navigate to).

But of course, while that's even better than going "one or the other" as above, it does have an issue that you essentially need to build both. It is in my opinion however the most efficient way to handle data loading into a mobile app.


问:
Feasible to keep work to a minimum for distribution purposes?
I'm faced with image manipulation requirements for a mobile app I wish to develop that I could quite easily (or 'easier', at least) implement in C# or javascript, as it's what I'm most familiar with.

I'm not one to shy away from learning new things, but would it not be easier to opt for this approach and get other platforms to 'call on' this functionality with a service oriented structure for the sake of addressing as many mobile platforms as possible without reinventing the wheel for each native platform?

My hesitation is that trips to a server to manipulate images would mean a transfer of byte streams to and from, a lot.

A second question, is this the kind of problem companies like PhoneGap aim to solve? Could I do all this in JS and compile and build it with PhoneGap? Or is, in people's experience, this not a feasible approach either?

Thanks very much. I appreciate this site isn't for subjective, opinion-based topics but I'm being specific in the fact that I want to handle potentially larger pieces of data and manipulate them, and so am asking for the advised way of structuring this in order to release it for as many platforms as possible.

答:
If it's going to happen frequently on the application itself then you want to use native code.  Yes, PhoneGap and Xamarin style products aim to allow you to write cross-platform mobile applications easily...but they are not 'lightweight' to add to an existing entirely native codebase. You can explore Xamarin - it would likely be a better fit than PhoneGap.

If that doesn't work for your project then I'd actually suggest you write your solution in C# or JavaScript and have one of the native developers assist you in porting that to Objective-C and Java.

If you're going to be making a lot of round-trips you should not do this server-side - because it will destroy you on data and battery usage from the mobile phone.  If it was something cache-able my opinion would change.


问:
How to minimize networking cost of distributed game database?
We've been working on a networked online game project which will run in near future and
looking for a satisfying solution for our distributed game database. We didn't take networking costs
into account so far.

We have following constraints:

1) We planned to use MySql but we can review alternatives if offered solution makes sense.

2) We planned to host multiple game servers on different geographical regions such as USA, Europe and Asia.

3) Every gamer usually connect to the nearest game server and distributed database node in order to reduce networking costs and lags.

We've been thinking to develop a logic in one of our server side layers that will check the user location he wants to connect from. Then, replicate user specific data from one database node to another if the check operation results that the gamer attempt to connect from a different region than he did before.

We wonder that is the correct way to do that?

Of course we have to think disaster cases.
For that purpose, what can we do if one of the distributed database node fails?

We don't think to replicate all data between database nodes because it causes high networking costs.

Thanks

答:
Sounds like a typical use for a service bus based solution.

I solved exactly this problem but for keeping running servers live and interconnected and in sync with each other in my MMO server framework.

The simple answer is "don't try and sync the data once its in the database use an event and handle it in multiple locations".

It's basically like taking the same approach as cloud computing does by having several clouds you either need a fat pipe on a scheduled basis or a means of seeing an incremental change as it happens.


问:
Why does java collections not supply a function for the index of max value?
I have been using Collections.max(list) for many projects, but I occasionally want to find the index of that maximum element. I feel silly writing a function to do this for myself in every program I write.

Why does the Collections Interface not supply a Collections.maxIndex(list)?

答:
Please take a look at Java 8 Streams API.

Link: http://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html

(Disclaimer: I haven't used it before.)

However, there's no out-of-the-box implementation of maxIndex. To enable that, someone will have to provide a high performance primitive pair or tuple stream implementation for Java 8 Streams.

The reason is this. Functionally speaking, maxIndex is:

Convert each value into a pair (tuple of 2) as: (value, position)

Reduce the stream as follows:

Compare the two items, (value1, position1) with (value2, position2),

Keep the item with the higher value, and copy along its position.

Namely, return (item1.value > item2.value) ? item1 : item2;

If a tie is possible, a tie-breaking mechanism is also needed, as pointed out in 9000's answer. It will no longer be a reduction over the tuple, but will become a "collection of (value, position) tuples all having the same maximum value".

As long as a tie-breaking mechanism is implemented, the approach outlined here will still be applicable.

At the end of operation, return item.value as the maximum value, and item.position as the maximum index.

As pointed out by 9000's answer, depending on the tie-breaking mechanism, there may be multiple results.

Unfortunately, as many Java advocates have pointed out, Java as a language is experiencing from an explosion of class-happiness, and this is due to the limitation of Java generics support. As a result, if you need anything not found in Java API, you have to roll your own, or find a library or toolbox that does.


问:
Is there something like Creative Commons licenses for privacy policies?
I've recently read Reading the Privacy Policies You Encounter in a Year Would Take 76 Work Days and was pretty shocked that it was that bad. So I thought how this could be improved.

Creative Commons licenses are nice, because they are modular:

CC: Indicates that it is a creative commons license

[-BY]: Attribution

[-NC]: Non Commercial

[-ND]: No Derivates

[-SA]: Share Alike

I think one could eventually make such modular privacy policies. Eventually a tabular policy would be better:

Received Information

Information you provide to us: Name, Content, Transactional information, Location, Friends

Collected information when you use the service: Site activity information, Access Device and Browser Information, Cookie Information

Third Parties: ...

Usage of Information

Manage Service

Sell to third parties

Contact you

...

Is there any attempt to create such a modular / structured (eventually machine-readable) privacy policy?

答:
The standard for handling privacy policies is called P3P. Part of P3P's aim is to have machine-discoverable and -readable privacy policies, so browsers can check whether they fall within the user's preferred bounds.

Other uses could include limiting web crawlers to only select data whose privacy policy allows this usage (eg. scraping blogs for a sociology experiment).