问:
Close to knapsack problem?
I think that I am trying to solve a problem somewhat similar to a knapsack problem. I am not sure though.

Please see the input given below and my solution. There are three types of items and 4 buckets. The problem is to keep the items as uniformly as possible in the 4 buckets. i.e. the capacity of the buckets (or number of items in the bucket) should be equal (or close to equal). You can also keep the items from different types in the same bucket.

example input:

```<code>item-type   :   A   B   C
  #items    :   12  36  25
</code>```

One simple solution I am using currently is as follows:

Since there are 4 buckets, each bucket should get (sum of items)/4. For the above example input data, it is (12 + 36 + 25)/4, i.e. approximately 18 items. The capacity of each of the bucket should be "CLOSE" to 18.

Then start keeping the items of type A into the first bucket until the number of items become 18.  However, still we need 6 more items for the first bucket as the number of type A items are 12. Therefore keep 6 items of the type B into the first bucket so that the capacity of the first bucket will be 18. Like this fill the other three buckets also.

Finally the four buckets are as follows:

```<code>Bucket-1: (12 A items, 6 B items)
Bucket-2: (18 B items)
Bucket-3: (12 B items, 6 C items)
Bucket-4: (19 C items).
</code>```

I think that the time complexity of this problem is O(N^2), N is the number of buckets.

It would be great if someone helps me to improve the solution further.

Note-1: We can mix items of different types in the same bucket.

Note-2: We also need to somehow keep the information of type of the item in the bucket.

答:
It looks like all your items have the same size, in which case the solution is trivial. Count the total number of items, let's say that number is c. Say there are n buckets. Calculate x = floor (c / n) and y = c - n*x. Then y bins get filled with x+1 items, and n-y bins filled with x items. </p>

<p>To make this an interesting problem, assume that the different item types have different sizes, and assume this time the total of all weights is c. In that case, it is quite possible that you cannot distribute the items into bins with weights x and x+1. Or that it is hard to do so. If it is impossible, then you'd need to define what the "best" solution is. </p>

Title: Close to knapsack problem?

Body:
It looks like all your items have the same size, in which case the solution is trivial. Count the total number of items, let's say that number is c. Say there are n buckets. Calculate x = floor (c / n) and y = c - n*x. Then y bins get filled with x+1 items, and n-y bins filled with x items.

To make this an interesting problem, assume that the different item types have different sizes, and assume this time the total of all weights is c. In that case, it is quite possible that you cannot distribute the items into bins with weights x and x+1. Or that it is hard to do so. If it is impossible, then you'd need to define what the "best" solution is.


问:
Finding the first index in which the element and the index are the same
I am to build a python function that takes a sorted list of numbers and outputs the first index the is equal to the element in its place.

It should run on O(log n) which I know how it should be running, operationally, but I can't manage to implement it. I guess I should check if the first element fulfills the required. Then, check whether or not the middle index is bigger than its element or smaller, and then go to the middle index between the previous index and the first\last index(which is a recursive operation.).

My code for now(using @Stefan guidance ):

```<code>def Fyn(I,lo,hi):
    while lo < hi:
        if I[(lo+hi)/2]==(lo+hi)/2:
             if I[(lo+hi)/2-1]==(lo+hi)/2-1:
                    return Fyn(I,0, (lo+hi)/2)
             else:
                    return (lo+hi)/2
        if I[(lo+hi)/2]<(lo+hi)/2:
            return Fyn(I,(lo+hi)/2,hi)
        else:
            return Fyn(I,lo,(lo+hi)/2)
</code>```

What remains is actually finding the smallest index for which it happens. Right now it won't always do so. ()

答:
Since you're splitting up the lists, changing the indices, you need to reflect that back into your return calls as the function calls unravel. Something like:

```<code>def Fun(I):
    for i in range(0,len(I)-1):
        if i==[i]:
            return i
        elif I[len(I)/2-1]>len(I)/2-1:
            # no need to add if index is below
            return Fun(I[:len(I)/2])
        else:
            # if index is greater, add your 'pivot' index
            return ((len(I)/2) - 1) + Fun(I[len(I)/2:])
</code>```

(warning: code untested)

Edit: If you're willing to change your function definition, another way to get your indices to add up which still allows the return of a -1 (or whatever) when the value isn't found.

```<code>def Fun(I, base):
    for i in range(0,len(I)-1):
        if i==[i]:
            return i
        elif I[len(I)/2-1]>len(I)/2-1:
            # no need to add if index is below
            return Fun(I[:len(I)/2], base)
        else:
            # if index is greater, add your 'pivot' index
            return Fun(I[len(I)/2:], (base + len(I)/2 - 1))
</code>```

(warning again: code untested)

This function also needs code to return when the value is not present (size of list is 1, but the value is not the one you're looking for).

ContentLicense: CC BY-SA 3.0

Body:
Since you're splitting up the lists, changing the indices, you need to reflect that back into your return calls as the function calls unravel. Something like:

def Fun(I):
    for i in range(0,len(I)-1):
        if i==[i]:
            return i
        elif I[len(I)/2-1]>len(I)/2-1:
            # no need to add if index is below
            return Fun(I[:len(I)/2])
        else:
            # if index is greater, add your 'pivot' index
            return ((len(I)/2) - 1) + Fun(I[len(I)/2:])

(warning: code untested)

Edit: If you're willing to change your function definition, another way to get your indices to add up which still allows the return of a -1 (or whatever) when the value isn't found.

def Fun(I, base):
    for i in range(0,len(I)-1):
        if i==[i]:
            return i
        elif I[len(I)/2-1]>len(I)/2-1:
            # no need to add if index is below
            return Fun(I[:len(I)/2], base)
        else:
            # if index is greater, add your 'pivot' index
            return Fun(I[len(I)/2:], (base + len(I)/2 - 1))

(warning again: code untested)

This function also needs code to return when the value is not present (size of list is 1, but the value is not the one you're looking for).


问:
building feature dependent version software
I have a program that is used by customers to do some computational work. And how long it takes always depends on how much data customer wants to compute. Some customers have a little data, some have a lot (bigger amount of customers have smaller data, but once with bigger data are richer).
It's possible to make a scalable version of that software, but that of course will cost to implement, and price of software would rise.
Marketing of course would like to have different options, like for customers that have a lot of data and can pay, they would suggest more expansive version, that supports scaling. For others, they would like to suggeest cheaper version, that will take longer.

But from development view, these are kind of 2 different version of same think. And therefore if something is implemented (like new dialog window), it should be implemented in both versions. Some parts of course can be just reused, but some might need special work (because how data access is implemented).
So it looks like have one version would be much cheaper from development perspective. It would be easy to fulfill marketing demands by building 2 version, where 1 have unlimited scalling posibility, another don't have that (assuming that it's possible to have some variable for that). But than it feels like giving worst program to poorer customers, just because they don't really really need it.

Is there some practice how this kind of versions are done and what's a reasoning doing that? Like you have windows for desktop and windows for servers, desktop version will have limits how many users can connect etc.

答:
On you specific use case, why not implement a "limit" on datasets and charge customers on dataset size? After going over x records or x Gb the software locks up or shows some horrible popup or warning about performance or whatever until you upgrade.

It would be pretty easy to keep the same code base for the two versions and you can easily split into more versions if/when needed.

Pricing systems is another beast entirely, but as for how to best integrate scalability on your pricing system, I suggest you make your pricing system measure the scalability, instead of simply hiding it.


问:
How to open a desktop application through browser without a Java applet?
We run a cloud-based medical software, and a very important part of the program is bridging to an imaging software straight from our website, passing information through command line arguments.  We pass a patient's name and ID through a Java applet, and it will open the imaging program that is installed locally on the user's computer.  There are many different imaging software vendors that we bridge to, so it isn't possible to make our own imaging software in the browser.

I was wondering what the best way is to pass in these arguments and open the program, without using the Java applet that we have.  As you all may know, Google is dropping NPAPI support in Chrome, and has just recently pushed update 42 which disables Java applets by default.  It is still possible to use them for now, but support will be dropped completely by September.  So, what would be the best thing to replace our Java applet with?

答:
Things that come to mind, but none as cross platform and browser neutral as Java is supposed to be:

Create a Chrome extension.

Convince Oracle to support Java in Chrome.

Require users to use IE or Firefox.

Have your "cloud-based medical software" people also support your imaging needs.

I'm trying to think of a clever, simple solution, but you're in a tough spot.  I don't envy you trying to connect a browser-based app to a locally installed component.  You're working against the grain big time.


答:
Running local programs through the web browser is frowned up for most scenarios, so browsers don't really want to implement that support.

One idea I had that you could do, is create some obscure file extension, and register your client-side app to open them. Then, your web page serves up some file, in that file extension. The file would get opened by your client-side app and the file contents would tell your app what to do. Then, configure the browser to download and open those files without confirmation.

Title: How to open a desktop application through browser without a Java applet?

Body:
We run a cloud-based medical software, and a very important part of the program is bridging to an imaging software straight from our website, passing information through command line arguments.  We pass a patient's name and ID through a Java applet, and it will open the imaging program that is installed locally on the user's computer.  There are many different imaging software vendors that we bridge to, so it isn't possible to make our own imaging software in the browser.

I was wondering what the best way is to pass in these arguments and open the program, without using the Java applet that we have.  As you all may know, Google is dropping NPAPI support in Chrome, and has just recently pushed update 42 which disables Java applets by default.  It is still possible to use them for now, but support will be dropped completely by September.  So, what would be the best thing to replace our Java applet with?


答:
Forget my earlier answer. I actually implemented it now and it works. Not spoiling the whole thing but just answering your question, here's part of my code:

```<code>def Fun(I):
    lo, hi = 0, len(I)    # We'll search I[lo:hi], i.e., excluding index hi
    while lo < hi:
        check middle index
        adjust lo and hi appropriately
        handle the the result appropriately
</code>```

Edit: Since Meitar made his final one now, here's mine:

```<code>def Fun(I):
    lo, hi = 0, len(I)      # We'll search I[lo:hi], i.e., excluding index hi.
    good_index = None       # So far we haven't found a good index.
    while lo < hi:          # As long as we have a range to look into...
        i = (lo + hi) // 2  # Get an index in the middle.
        if I[i] < i:        # If too low here, then earlier ones are, too,
            lo = i + 1      #   so we only look at later ones (note the +1 !).
        elif I[i] > i:      # If too high here, then later ones are, too,
            hi = i          #   so we only look at earlier ones.
        else:               # If good here, then
            good_index = i  #   remember this but
            hi = i          #   keep looking for earlier ones.
    return good_index       # Return what we found (real index or None).
</code>```

Can be tested with this:

```<code>import random
try:
    for _ in range(100):
        I = sorted(random.sample(range(-50, 150), 100))
        if Fun(I) != next((i for i, e in enumerate(I) if i == e), None):
            print("wrong answer")
            break
    else:
        print("all correct")
except:
    print("crashed")
</code>```

Title: Finding the first index in which the element and the index are the same

Body:
I am to build a python function that takes a sorted list of numbers and outputs the first index the is equal to the element in its place.

It should run on O(log n) which I know how it should be running, operationally, but I can't manage to implement it. I guess I should check if the first element fulfills the required. Then, check whether or not the middle index is bigger than its element or smaller, and then go to the middle index between the previous index and the first\last index(which is a recursive operation.).

My code for now(using @Stefan guidance ):

```<code>def Fyn(I,lo,hi):
    while lo < hi:
        if I[(lo+hi)/2]==(lo+hi)/2:
             if I[(lo+hi)/2-1]==(lo+hi)/2-1:
                    return Fyn(I,0, (lo+hi)/2)
             else:
                    return (lo+hi)/2
        if I[(lo+hi)/2]<(lo+hi)/2:
            return Fyn(I,(lo+hi)/2,hi)
        else:
            return Fyn(I,lo,(lo+hi)/2)
</code>```

What remains is actually finding the smallest index for which it happens. Right now it won't always do so. ()

Body:
Forget my earlier answer. I actually implemented it now and it works. Not spoiling the whole thing but just answering your question, here's part of my code:

def Fun(I):
    lo, hi = 0, len(I)    # We'll search I[lo:hi], i.e., excluding index hi
    while lo < hi:
        check middle index
        adjust lo and hi appropriately
        handle the the result appropriately

Edit: Since Meitar made his final one now, here's mine:

def Fun(I):
    lo, hi = 0, len(I)      # We'll search I[lo:hi], i.e., excluding index hi.
    good_index = None       # So far we haven't found a good index.
    while lo < hi:          # As long as we have a range to look into...
        i = (lo + hi) // 2  # Get an index in the middle.
        if I[i] < i:        # If too low here, then earlier ones are, too,
            lo = i + 1      #   so we only look at later ones (note the +1 !).
        elif I[i] > i:      # If too high here, then later ones are, too,
            hi = i          #   so we only look at earlier ones.
        else:               # If good here, then
            good_index = i  #   remember this but
            hi = i          #   keep looking for earlier ones.
    return good_index       # Return what we found (real index or None).

Can be tested with this:

import random
try:
    for _ in range(100):
        I = sorted(random.sample(range(-50, 150), 100))
        if Fun(I) != next((i for i, e in enumerate(I) if i == e), None):
            print("wrong answer")
            break
    else:
        print("all correct")
except:
    print("crashed")


问:
Haskell types for functions
I don't understand the answer to this question:

Q: Can Haskell find a type for the function selfapply defined by: selfapply f = f f

A: The function selfapply is not typeable in the simple system of types: we need to associate to f two types which are not compatible: α → α and α.

So I know a -> a means alpha input and alpha return, but why is it a->a and a instead of a->a->a?

Also another question regarding this topic:

Find a polymorphic type for the functions quad, double

```<code>quad x = y*y where y = x*x
double x = x*2
</code>```

How can we determine a polymorphic type for these two functions?

答:
Hm, well for the first one this is because let's say f f was well typed. We're applying f so it has to be a function. Functions have the type f : A -> B for some A and B. Since f is also the argument, it must also be the case that f : A. This means that A = A -> B. Moreover since f = f f, the the type of f f is also the type of f. Since f f : B this means f : B. This means that A = B and so f : A -> A and A -> A = A as required.

For the second, what's the type of *? This is the key to understanding the type of these functions since we're applying * to the input. In Haskell * :: Num a => a -> a -> a, which must mean that our functions have the type Num a -> a -> B for some B. I'll let you figure it out from there :)

Title: Haskell types for functions


问:
Check distance between all elements in a list of numbers in O(n*lg(n))
I have an exercise for my algorithms and data structures class, where I basically have to implement a divide and conquer algorithm or function called check_distance to determine whether all numbers in a list X have distance greater or equal to k from each other, and I have to show that the worst case complexity of this algorithm is O(n*lg(n)).

When I think at algorithms that have to run in at most n*lg(n) time asymptotically, I think immediately about merge sort, which is exactly the divide and conquer algorithm that I used. Are my functions are correct or not?

Before this exercise, I had already one, where I had to create another divide and conquer function to check if there are duplicates in a list. This function should also run in O(n*lg(n)).

This is my function check_duplicates, which uses again the merge sort algorithm (I am not posting the code of the merge sort algorithm, because it's a typical merge sort. If you want me to post it, just ask!):

```<code>def check_duplicate(X):
    S = merge_sort(X)               # O(n*lg(n))
    for i in range(0, len(S) - 1):  # O(n)
        if S[i] == S[i + 1]:
            return True
    return False
</code>```

My first questions are: Is it correct, and does it run in O(n*lg(n)) time?

Now, I pass to the real problem, my second function, which (as I said) should check that the distance between each element in a list is greater or equal than a constant k. For this check_distance function, I used the check_duplicate function above, to ensure that are no duplicates, otherwise it returns immediately false.

Now, my main reasoning was again to sort the list. Once the list is sorted, the ai + 1 element will always be greater or equal than ai, therefore, for all ai in X, ai <= ai + 1 <= ai + 2, etc.

Now, again, for all ai in X, if I sum ai + k, and this is less or equal than ai + 1, then the distance between all elements should be >= k.

Am I correct?

```<code>def check_distance(X, k):
    if check_duplicate(X):        # n*lg(n)
        return False
    else:                         # no duplicate values
        A = merge_sort(X)
        for i in range(len(A) - 1):
            if A[i] + k > A[i + 1]:
                return False
        return True
</code>```

If I am not correct, is there a better approach?

答: The obvious solution is to sort the array in O (n log n), and then the elements can be checked sequentially in O (n). I wonder what is going on in the teachers mind when he asks for a "divide and conquer" algorithm. </p>


答:
I guess you don't need this anymore, but since I realized gnasher's bump only after thinking about this, I'll leave some imho nicer code here anyway:

```<code>def check_distance(X, k):
    A = merge_sort(X)
    return all(b-a >= k for a, b in zip(A, A[1:]))
</code>```

I'm interested in the teacher's solution. Did he just have this braindead sort and sweep in mind, or something more interesting?

Title: Check distance between all elements in a list of numbers in O(n*lg(n))

Body:
I have an exercise for my algorithms and data structures class, where I basically have to implement a divide and conquer algorithm or function called check_distance to determine whether all numbers in a list X have distance greater or equal to k from each other, and I have to show that the worst case complexity of this algorithm is O(n*lg(n)).

When I think at algorithms that have to run in at most n*lg(n) time asymptotically, I think immediately about merge sort, which is exactly the divide and conquer algorithm that I used. Are my functions are correct or not?

Before this exercise, I had already one, where I had to create another divide and conquer function to check if there are duplicates in a list. This function should also run in O(n*lg(n)).

This is my function check_duplicates, which uses again the merge sort algorithm (I am not posting the code of the merge sort algorithm, because it's a typical merge sort. If you want me to post it, just ask!):

```<code>def check_duplicate(X):
    S = merge_sort(X)               # O(n*lg(n))
    for i in range(0, len(S) - 1):  # O(n)
        if S[i] == S[i + 1]:
            return True
    return False
</code>```

My first questions are: Is it correct, and does it run in O(n*lg(n)) time?

Now, I pass to the real problem, my second function, which (as I said) should check that the distance between each element in a list is greater or equal than a constant k. For this check_distance function, I used the check_duplicate function above, to ensure that are no duplicates, otherwise it returns immediately false.

Now, my main reasoning was again to sort the list. Once the list is sorted, the ai + 1 element will always be greater or equal than ai, therefore, for all ai in X, ai <= ai + 1 <= ai + 2, etc.

Now, again, for all ai in X, if I sum ai + k, and this is less or equal than ai + 1, then the distance between all elements should be >= k.

Am I correct?

```<code>def check_distance(X, k):
    if check_duplicate(X):        # n*lg(n)
        return False
    else:                         # no duplicate values
        A = merge_sort(X)
        for i in range(len(A) - 1):
            if A[i] + k > A[i + 1]:
                return False
        return True
</code>```

If I am not correct, is there a better approach?

Body:
I guess you don't need this anymore, but since I realized gnasher's bump only after thinking about this, I'll leave some imho nicer code here anyway:

def check_distance(X, k):
    A = merge_sort(X)
    return all(b-a >= k for a, b in zip(A, A[1:]))

I'm interested in the teacher's solution. Did he just have this braindead sort and sweep in mind, or something more interesting?


问:
MaxHeap-like data structure supporting max AND min, also decrease-key (yes decrease-key)
For the purpose of implementing an optimization algorithm (finding the minimum of a multivariate function) I want to create a data structure that supports the following operations:

load from array

Peek at maximum element (but don't destroy it)

Peek at next-to-maximum element

Peek at minimum element

decrease the maximum element

Once initialized, the data structure always stores the same number of elements.

Currently I'm just using an unsorted array, and searching the array each time to find the max, next-to-max, and min elements, and updating the max element when necessary.

I considered using a heap / priority queue, but those don't seem ideal, as they support adding and removing elements, which I don't need to do. They also don't natively support "decrease the maximum element", just "increase an arbitrary element" so I'd have to extract-max and then re-add it.

I also considered a sorted array in a ring buffer, which seems like it would be better than just a sorted array, as I'd only have to move at most half of the list.

Wikipedia talks about some complicated data structures (Fibonacci heaps) that I vaguely remember from my sophomore algorithms class in college, but those seem like overkill (and they also support features I don't need and don't support features I need).

Well, now I search again and I find my question is sort of kind of a duplicate of https://cs.stackexchange.com/questions/10203/increase-key-and-decrease-key-in-a-binary-min-heap

答: For the max stuff I'd use a heap, for the min a simple variable (to be potentially updated when the decrease operation lets the previous maximum fall all the way to the bottom of the heap).</p>


问:
What languages should I know if I'm interested in building web applications?
I'm interested in developing for the web and I'm curious what languages should I know besides html, css, javascript, php/python/ruby. I don't know much about c# or java to make a decision whether to learn them or not, are they used much in the field I'm interested in?
What other technologies should I look into ?</p>

答: Definitely check out Django if you already know Python, it's a great web app framework, really easy to get started with (there are tutorials on the Django website) and very flexible.</p>

OwnerDisplayName: webguy

ContentLicense: CC BY-SA 2.5


答:
"Java Web Start (also known as JavaWS, javaws or JAWS) is a framework developed by Sun Microsystems (now Oracle) that allows users to start application software for the Java Platform directly from the Internet using a web browser."

source : "http://en.wikipedia.org/wiki/Java_Web_Start"

With Java WS you can start desktop java applications (not applets).

You can use a JNLP link from Chrome :
How to Configure Chrome to Open JNLP Files

And finally, this is how to pass parameters to your local desktop java application from the internet :
Passing dynamically parameters to a Java Web Start App (JNLP)

P.S. : If your desktop application is not in Java, your can still use a Java desktop application as a relay to launch it.


问:
Is studying algorithms important for game development?
I am fairly new in the programming world, I have a 1-year experience and I learned by watching online courses, and I made few iOS apps.

Now I am moving into game development and I already familiarized myself with Unity3D and started doing my own simple project.

Playing games like Monument Valley for example made me wonder: what if I want to implement the same movement technique in my own game, or lets say I have an automated turret that shoots at the nearest enemy, or a even a game like sudoku or tic tac toe?

I have no idea how to efficiently implement that. So is it absolutely necessary to learn the fundamentals of algorithms or is there some easier way to achieve what I want without the complexity of CS?

答:
The short answer is yes.

It depends on the complexity and innovation of the game being designed. Some games, say, Gravity Master, looks simple enough but actually requires a rigid body physics solver.

All games involve programming; software with increasing functionality requires more programming, which I hope is obvious to you.

The majority of games require geometry because most kinds of gameplay involves movements and distance effects in a 1D, 2D or 3D space.

Some kinds of gameplay require less knowledge areas:

Card games don't involve geometry, but may involve combinatorics and artificial intelligence (more specifically "game tree" and "heuristics", used for searching for a viable strategy by the computer player.)

Games where movement is constrained to a grid and only one step allowed at a time (without pathfinding) are also simpler.

Games which only involve a series of storyboards (of which the evolution of the story is based on answering multiple-choice questions by the user) is also simplier.

But games in general can involve many knowledge areas. Game developers must work really, really hard. It is not unheard of that they might work twice as long hours compared to other software programmers outside the game industry. They must be avid self-learners because they may not have all of the necessary knowledge when they graduate from school. Each game requires new knowledge (or else, it will not be innovative enough to impress the gamers.)

Games in general are also divided into many components. Sometimes, these components can be packaged into "game engines", so that other programmers can build on top of that without having reached the same level of knowledge as to implement the same.


答:
1. No.

You can do a LOT in game development with only the most shallow knowledge and understanding of Computer Science. You don't need CS knowledge to do graphic design, nor do you need it for most 3D design. You don't need CS to tell a story, which is essentially what most quest games do. You don't need CS to think about game-play and usability, and design the ways a user interacts with a game, and so on...

Also, today you have so many tools available (such as the Unity, etc) that allow you to create really cool things without going too deep into what happens in the background.

Also, most of the problems you face in day-to-day software development, even when they have some CS elements, are very trivial, and almost always have been solved before in a well known and documented way. You can always come here and ask :-)

2. Yes.

The way we, humans, understand and describe the world around us is with mathematics. The way computers work is solely founded on mathematics (and some fancy sand i.e. Silicon). When I say "the world around us, i don't only mean physics, and the "physical" world. Chess, checkers, soduku, most card games, and many more are just fancy math problems. To understand, manipulate, and be able to create, things like a Chess AI,  a visual 2D\3D engine, or anything beyond a MOD to a First Person Shooter, you must have a deep and profound understanding of the mathematical elements behind them.

3. Maybe?

So basically my answer is - Your mileage may vary. It depends on what do you want to do, where, and how much understanding do you want of what you are doing. Even if you want to do things that really require the Math, today you can learn most of the things you need yourself on the internet.
But, as someone who worked for about 7 years in the industry with only 6 months of professional training, I can say that the easier way is going to collage and learning it there...

Title: Is studying algorithms important for game development?

Body:
I am fairly new in the programming world, I have a 1-year experience and I learned by watching online courses, and I made few iOS apps.

Now I am moving into game development and I already familiarized myself with Unity3D and started doing my own simple project.

Playing games like Monument Valley for example made me wonder: what if I want to implement the same movement technique in my own game, or lets say I have an automated turret that shoots at the nearest enemy, or a even a game like sudoku or tic tac toe?

I have no idea how to efficiently implement that. So is it absolutely necessary to learn the fundamentals of algorithms or is there some easier way to achieve what I want without the complexity of CS?


问:
DDD - map or object
What is correct by DDD - should I create map of two objects eg Map or should i use more meaningfull object that will contain this pair MoreMeaningfullName{Obj1, Obj2} ?

If using first approach, I don't create unnecessary classes, but in 2nd approach I have meaningful object (to some extent).

答:
First of all I would like to object "correctness by DDD". Domain Driven Design is all about constructing model of domain and exposing it in your design using object-oriented programming. It is not a set of strict rules, rather list of guidelines and patterns.

I assume that both types (Obj1 and Obj2) stored in the map are meaningful to domain. Otherwise this map is out of DDD scope.

Existence of map of Obj1 to Obj2 suggest that there is one-to-many relationship between Obj1 and Obj2. So the first question that you should ask yourself is whether this relationship is meaningful for your domain. Or maybe this is just technical detail useful for some calculation.

In the former case DDD suggest that you should consider making this relationship explicit. Too many relationships in your model make it too complex. Therefore Evans in DDD book suggests:

imposing traversal direction

adding qualifier to reduce multiplicity

limiting associations to only those really essential

So if you decide to place the relationship in your model, there are different ways to make relationship explicit, as suggested by OOP principles. One-to-many relationship might be represented as attribute in Obj2 (for traversal direction Obj1 <-- Obj2 or collection of objects of Obj2 in Obj1 (for Obj1 --> Obj2). You can also introduce some class representing association, which is especially useful for many-to-many relationships.

Of course if the map has its own identity or lifecycle, i.e. fulfils requirements for Entity, than it is recommended to model it as a separate class. I can also imagine a map being modelled as Value object, but see my remark below.

Even if the relationship is not meaningful or not essential for your domain, basic design principles still apply to your design (according to priority):

Passes all the tests.

Express every idea we need to express.

Contains no duplication.

Minimized the number of classes, methods and other moving parts.

So if you are going to duplicate some operations on the map in multiple places - create a class. If the map has some deeper meaning - also use separate class. If not, then probably it is better to leave it as pure map to avoid having too many classes.

Title: DDD - map or object


问:
What is the usefulness of transactions in a batch (especially a Spring batch)?
I understand what a transaction is in a web application, where you have some groups of database interactions which have to fail or succeed together so the database is always in coherent state.

But why is a framework like Spring Batch built around transactions ? My group of committed records is not a logical group (the size of this group is set up using commit-interval property) : it's not a problem if one fails and the others succeed. And in the contrary, if my commit-interval is 100, what's the purpose of rolling back 100 independent operations when one fails ?

If my question is not clear enough, let's take an example : I have a job with a few steps, and each main step is about parsing some xml files and inserting fragments into DB. What will happen if all these steps run in no transaction, and any failing reading/processing/writing results in a caught exception and just produces some logs ? What am I losing doing so ?

Best answer I've found to this so far is : batch transactions are not logical transactions, they are about performance, you can't process item in chunks without transactions, is that true ?

I understand how to set up transactions and I've wrote a few jobs already, my question is not about "how" but about "why".

答:
First, transactional databases typically do not allow to write data "without transactions" - any kind of write access will be enclosed in a transactions. From the viewpoint of the database, a write operation is just a write operation for which data integrity has to be ensured. If it is caused by a batch process, an OLTP process or a mixture of both does not matter.

Furthermore, it is not too hard to imagine a batch process where you have to insert data in two tables, with a master-child relationship between them, and you want to make sure when a master record is inserted, also the related child records will be inserted completely, and when the insert of a child record fails, the master record shall not be inserted at all. So opposed to the case where you insert into data only into one table and each INSERT is an atomic operation, now you have to consider a group of INSERTs as one atomic operation.

For such a process, you can still insert 100 records into your master table, and all related child records within the same transaction. But you will definitely have to avoid to place the COMMIT somewhere at the wrong place between the INSERT of a master record and its related child records. So your COMMITs have to respect the logical relationship of your data in such a case.

Another scenario: if your batch process needs to make a detailed log about which of the INSERTs failed and which were successful, you may have to enclose each logical atomic group of inserts into a single transaction. That may also be true if you have just a single table to be filled. You can think of optimizing this by first trying to insert your data in chunks of 100, and if that fails, you try again to insert your data one-by-one, but at least for the second step, you need to cut your transactions logically correct.


答:
I don't remember i ever encountered a real life situation when a heap was the best solution.

It sounds to me that what you need is a self balancing Self-balancing binary search tree
. You should probably look into AVL trees, and Red-Black Trees.

Binary Search Trees have very similar performance characteristics to a Heap, but they are much more useful, and can help you solve a lot of problems quite trivially.

P.S.

Here is a useful way to find the K'th smallest element in a search tree.

Title: MaxHeap-like data structure supporting max AND min, also decrease-key (yes decrease-key)

Body:
For the purpose of implementing an optimization algorithm (finding the minimum of a multivariate function) I want to create a data structure that supports the following operations:

load from array

Peek at maximum element (but don't destroy it)

Peek at next-to-maximum element

Peek at minimum element

decrease the maximum element

Once initialized, the data structure always stores the same number of elements.

Currently I'm just using an unsorted array, and searching the array each time to find the max, next-to-max, and min elements, and updating the max element when necessary.

I considered using a heap / priority queue, but those don't seem ideal, as they support adding and removing elements, which I don't need to do. They also don't natively support "decrease the maximum element", just "increase an arbitrary element" so I'd have to extract-max and then re-add it.

I also considered a sorted array in a ring buffer, which seems like it would be better than just a sorted array, as I'd only have to move at most half of the list.

Wikipedia talks about some complicated data structures (Fibonacci heaps) that I vaguely remember from my sophomore algorithms class in college, but those seem like overkill (and they also support features I don't need and don't support features I need).

Well, now I search again and I find my question is sort of kind of a duplicate of https://cs.stackexchange.com/questions/10203/increase-key-and-decrease-key-in-a-binary-min-heap


问:
Does the LGPL allow me to do this?
I am planning to develop a commercial software using a LGPL software.

In the LGPL software that I am using some functions in a class are not fully implemented. I want to modify the LGPL code so that the class and not-implemented functions are made visible outside the dll by adding dllexport infront of class and by adding virtual keyword infront of function.

Then I plan to implement those functions in my proprietary software. I am ready to distribute the modified LGPL code but not proprietary software that implements functions in the way I want.

Does that violate LGPL terms and conditions?

答:
https://www.gnu.org/licenses/lgpl-java.html

If you distribute a Java application that imports LGPL libraries, it's
  easy to comply with the LGPL. Your application's license needs to
  allow users to modify the library, and reverse engineer your code to
  debug these modifications. This doesn't mean you need to provide
  source code or any details about the internals of your application. Of
  course, some changes the users may make to the library may break the
  interface, rendering the library unable to work with your application.
  You don't need to worry about that—people who modify the library are
  responsible for making it work.

In short, there is no problem with inheritance as long as you do not change the library code itself, but even if you change it, you are required to release only the library modified code, not your application code.

Title: Does the LGPL allow me to do this?

ContentLicense: CC BY-SA 4.0


问:
What's the right balance between code consistency and code improvement?
Recently I had a discussion with a colleague regarding code style. He was arguing that your usage of APIs and the general patterns you are using should be as similar as possible with the surrounding code, if not with the the codebase as a whole, just as you would with code appearance (brace positioning, capitalisation etc). For example if I were adding a method to a DAO class in C# I would try to use LINQ where appropriate to help make my code clean and easy to maintain, even if none of the other methods in that class were using it. However, my colleague would argue that I should not use it in that instance because it would be against the existing style of that class and thus harder to understand.

At first I found his position rather extreme, but after thinking it over for a while I am beginning to see his point. With the hypothetical LINQ example, perhaps this class doesn't contain it because my colleagues are unfamiliar with LINQ? If so, wouldn't my code be more maintainable for my fellow developers if I didn't use it? On the other hand, if I truly believe that using such a technique would result in cleaner code, then shouldn't I use it even if it differs drastically from the surrounding code?

I think that the crux of my colleague's argument is that if we all go about implementing similar functionality in a codebase in different ways, and we each think that our way is "best", then in the end the code as a whole just gets harder to understand. However at the moment I still think that if we blindly follow the existing code too much then the quality will just slowly rot over time.

So, to what extent are patterns part of code style, and where should we draw the line between staying consistent and making improvements?

答:
The answer to this is simple.

Consistency is of paramount importance.

but it comes with a caveat...

You and you coworker are likely obsessing over the wrong sort of consistency

Implementations are disposable. They can be completely overhauled with varying degrees of ease depending on the quality and comprehensiveness of the test suite. Worrying about things like "Should this be a property?", "Shouldn't thins code use LINQ instead of a lower level construct?" is of dubious value. Its vary hard to tie any measurements to the value of consistency at the implementation level. A much better question to ask at this level is "Does this code work as advertised?". TL;DR implementation consistency is where "little minds" get their hobgoblin on.

Why isn't consistency as important here? Implementations usually have a tiny number of contributors. Most methods are written and never touched again. Of the remaining code the number of methods that have two contributors almost certainly a majority. This pattern continues ad infinitum. In this context consistency just isn't that important. If the shelf life of the code is pretty small(a few years) the gains from aggressive consistency are likely a non-factor.

This is not to say that you should go crazy in your implementations. Rather its to say that a nice, clean, simple design will be orders of magnitude more valuable to your hypothetical future maintainer than silly boiler plate consistency method by method. This takes us to the real point...

APIs are not disposable.

This is all APIs code level, web services, SDKs etc. These must, must, MUST be consistent. The productivity gains from this variety of consistency are enormous for a number of reasons:

Integration Tests:

If you keep your API's consistent you can create suites of integration tests. These allow developers to freely swap the implementation details and achieve immediate validation. Wanna swap your co-works crap over to LINQ? Do the integration tests run? It also provides validation when preparing to go to production. Because computers are fast a single laptop can preform the work of a thousand testers executing mundane tasks. Its tantamount to increasing your organization's headcount considerably.

Productivity

When API's are consistent you can make guesses about how to use an API just by following what you've learned about using other parts of the API. This is because the API affords a natural, consistent "look and feel". It means your client's spend less time sifting through documentation. Onboarding is easier and cheaper. Less questions are asked to the people that developed the API.  Consistency makes everyone a winner

Why is consistency important in this scenario? Because API's have the exact opposite problem of implementations. The number of people using them is typically much greater than the number of people contributing to their implementations. Small gains from a little consistency are multiplied and costs of maintaining that consistency are amortized.

Conclusion

Consistency is expensive. On its face it lowers productivity. It constrains developers and makes their lives harder. It places limitations on the ways they can solve a problem sometimes forcing them to solve it in a non-optimal way. This is often for reasons they don't understand, are ill-conceived, or they are not privy to(contracts, larger organizational or inter-organizational policies).

Raymond Hettinger made some excellent points in his Pycon 2015 talk regarding using the PEP8 style guide for teams of python programmers. He showed that the obsession on stylistic consistency on a piece of code caused code reviewers to miss serious logic and design flaws. His hypothesis can be summarized as finding stylistic inconsistencies is easy; determining the real quality of a piece of code is hard

The point here is be critical. Identify where consistency is important and protect it aggressively. Where its not important don't waste your time. If you can't provide a objective way to measure the value of consistency(in the above cases "effective headcount", cost as a function of productivity) and you can't demonstrate the returns are substantial then your are likely doing a disservice to your organization.


问:
Write Once - Use Many for server return values?
Well, I was wondering how I could do this or how this is done.

Having a server that accepts HTTP Requests and maintains a database for a mobile app, it is supposed to provide data for Android and iOS - or let's say - for more than one client.

Now that I write the Android client in Java and the iOS client in Objective-C I cannot simply have a shared project between my clients and the server for them to know how the objects returned from the server as JSON are supposed to look like as runtime objects.

For example if my server returns a simple Java object that gets marshalled to JSON:

```<code>public class Person {
    public String name;
    public int age;
}

// ..

public Person[] getListOfPersons(int minAge, int maxAge) {
    // ..
    return personList[];
}
</code>```

How can I introduce this return value for all kind of clients without having to write every object over and over again?

答:
You might want to use Google Protocol Buffers.

You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages – Java, C++, or Python.


问:
Can GPL be implied to a derivative work?
There are three software projects: A, B and C.

A is published to anyone and is licensed under GPL.

B extends A, is published too, but has no license information or is mistakenly licensed under LGPL. Basically it violates the license of A by not being GPL. Source code of B is still available.

C extends B. Can C be published under GPL? Motivation would be "A is GPL, any derivative must be GPL too, so B is GPL and C can be GPL too".

答:
First off, B is in violation of the GPL on A. But that's not exactly your concern and is irrelevant to the question here (who knows, maybe B got a LGPL license from A on their code so that it may be released under LGPL?).

The question is "Can you build a GPL piece of software based on LGPL code?"  The answer to this is simply "yes".

The LGPL is less restrictive than the GPL (thus why B is in violation of the license on A unless other provisions were made), but also allows it to be brought back into a GPL project fairly easily.

From the LGPL license:

Object Code Incorporating Material from Library Header Files.
  The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following:

a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License.

  b) Accompany the object code with a copy of the GNU GPL and this license document.

Its part of the license. You can easily build a GPL software based on LGPL code.

There are some version differences that you'll have to pay attention to to make sure that the code is licensed in the correct way, under the correct version of the GPL.

In the event that there is no license information presented, you do not have the right to extend upon it. B should not have been distributed, but its contributions are not licensed under an open source license. This may have been an internal project that got published or some other event.

It is not presented under a license that is compatible with extending with the GPL.  Consider the situation that a company, using GPL software internally (acceptable - not a violation), mistakingly made their repo public.

In this case, it is quite possible that the project C is in violation of copyright infringement itself (the material that B added that is not licensed under the GPL as it should not have been distributed in the first place).

One cannot force a license on someone else's source. It is either in compliance with the license, or in violation of it.  If it is in violation of it, then as spelled out in the license:

You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11).

A violation of the GPL does not mean that the material is under GPL, but rather that it can't be distributed.


答:
Technically, it is possible to extend a GPL library with code that is itself not covered by the GPL license. The snag is that when you distribute the derived work that you created, you must observe all the requirements that the GPL places on you.

In your situation, this means that it is possible to have library A under the GPL and the new code in library B under the LGPL. The combined work (library B) is effectively distributed under the GPL license, and can be distributed as such because the LGPL license is compatible with the GPL license (you can use LGPL licenses code in a GPL licensed project).

In that situation, it is perfectly fine to have the new code in library C under the GPL, with the resulting work under the GPL as well.

Title: Can GPL be implied to a derivative work?

Body:
There are three software projects: A, B and C.

A is published to anyone and is licensed under GPL.

B extends A, is published too, but has no license information or is mistakenly licensed under LGPL. Basically it violates the license of A by not being GPL. Source code of B is still available.

C extends B. Can C be published under GPL? Motivation would be "A is GPL, any derivative must be GPL too, so B is GPL and C can be GPL too".


答:
There are copyright holders: There is copyright on the works created by A, there is copyright on the additions by B, and there is copyright on any changes that C made. C must check whether he has permission to use the software on which A and B hold copyrights.

A was licensed under the GPL. I am quite sure that the GPL gives you permission to use A's work under the GPL terms, even if you received them from B who licensed them incorrectly. There may be practical problems: For example, you must be able to provide the source code. If you received the software without source code, then you have no way to publish it under the terms of GPL.

B was licensed under some other license. B should have been licensed under the GPL, but wasn't. If B's license give you more rights than the GPL, you don't actually have any of those rights for A's code - B can't give you additional rights to A's code. You can use A's code under GPL terms because A allowed it, and B's additional code under B's license.

If B released their code under a stricter license than GPL, then B is most likely commiting copyright infringement. You can't use B's code under the GPL license. That's often confused: GPL cannot force B to do anything. It only gives B the choice: Publish this way, and it is legally fine, or publish another way, and it is illegal. B has the right to do something illegal and suffer the consequences (being sued for copyright infringement). You don't have any rights to B's code that B didn' give you.


问:
How many threads should I use in my NIO server?
I've built a Java NIO TCP server, it currently uses four threads.
One ServerRunnable thread that uses a selector and three worker threads.

I've been looking around for some information about this, as I've read in the past that you should only have one thread per processor core. So that's that.

But that got me wondering recently, and after a little more research I came across this thread.

Where, in the comments on the accepted answer user Donal Fellows points out the following:

Have at most one CPU-bound thread per processor allocated to the application. IO-bound threads aren't a big problem (other than the memory they consume) and it's important to remember that apps can be restricted to only use a subset of the system's CPUs; after all, it's (usually) the user's/admin's computer and not the programmer's.

With that in mind, am I correct in thinking I can safely increase the number of selector threads and worker threads in my thread pool.

My server thread reads input, processes the data into JSONObjects and then pushes them to a queue. The worker threads then take the JSONObjects from the queue, checks what type of objects they are and then pushes them to the database.
So there is very little computational work going on there. Is it safe enough for me to increase the number of threads here, as in use more ServerRunnable threads and more worker threads?
Say to double the amount of each for example?

What do I need to think about when considering something like this?

答:
Processing power is the most scarce resource in a computer. As I write this, the most advanced CPU I am aware of has 18 cores and costs around 6 grands. That limits your number of threads to 18 if you want to have true parallelism. Anything more than that is overkill unless you are writing GUIs or other latency-insensitive applications.

A single-thread is capable of handling at least ten thousand connections. Now imagine if you wanted to have 10 thousand threads, one for each connection?

Take a look on this article about high-availability servers with CoralReactor to understand how a single thread can handle thousands of connections through a demultiplexer and multiplexer.

Disclaimer: I am one of the developers of CoralReactor.


问:
Why is negative zero important?
I'm confused about why we care about different representations for positive and negative zero.

I vaguely recall reading claims that having a negative zero representation is extremely important in programming that involves complex numbers. I've never had the opportunity to write code involving complex numbers, so I'm a little baffled about why this would be the case.

Wikipedia's article on the concept isn't especially helpful; it only makes vague claims about signed zero making certain mathematical operations simpler in floating point, if I understand correctly. This answer lists a couple of functions that behave differently, and perhaps something could be inferred from the examples if you're familiar with how they might be used. (Although, the particular example of the complex square roots looks flat out wrong, since the two numbers are mathematically equivalent, unless I have a misunderstanding.) But I have been unable to find a clear statement of the kind of trouble you would get into if it wasn't there. The more mathematical resources I've been able to find state that there is no distinguishing between the two from a mathematical perspective, and the Wikipedia article seems to suggest that this is rarely seen outside of computing aside from describing limits.

So why is a negative zero valuable in computing? I'm sure I'm just missing something.

答:
First, how do you create a -0? There are two ways: (1) do a floating-point operation where the mathematical result is negative, but so close to zero that it gets rounded to zero and not to a non-zero number. That calculation will give a -0. (b) Certain operations involving zeroes: Multiply a positive zero by a negative number, or divide a positive zero by a negative number, or negate a positive zero.

Having a negative zero simplifies multiplication and division a little bit, the sign of x*y or x/y is always the sign of x, exclusive or the sign of y. Without negative zero, there would have to be some extra check to replace -0 with +0.

There are some very rare situations where it useful. You can check whether the result of a multiplication or division is mathematically greater than or less than zero, even if there is an underflow (as long as you know the result is not a mathematical zero). I cannot remember ever having written code where it makes a difference.

Optimising compilers hate -0. For example, you cannot replace x + 0.0 with x, because the result shouldn't be x if x is -0.0. You can't replace x * 0.0 with 0.0, because the result should be -0.0 if x < 0 or x is -0.0.

Title: Why is negative zero important?


问:
What is difference between publisher-subscriber and reactor patterns?
Publish-subscribe and Reactor patterns looking very similar to me. How they are different?

In both patterns a message is getting passed to subscribers indirectly (listeners in reactor pattern).

I feel observer pattern is very similar to two other patterns too.

What are key differences between those patterns?

答:
PubSub is more related to Messaging Queues (MQs). It has to do with how nodes receive asynchronous messages in a distributed system.

Reactor pattern has more to do with asynchronous events. For exemple, non-blocking sockets use the reactor pattern to deliver network events: READ, WRITE, CONNECT, ACCEPT

You can check CoralReactor to have a better understanding of the reactor pattern.

Disclaimer: I am one of the developers of CoralReactor.


答:
One of the things that's critical in designing a multithreaded system is figuring out how to split the work up in a way that keeps as many cores as busy as possible.  Your proposed design uses two types of threads which are mostly I/O bound and puts some of the computational work on each.

I'd suggest that you make the I/O-bound threads separate and put the compute-intensive stuff in the middle using three kinds of threads:

Input - Reads the input, puts it on an input queue and goes back to waiting for more input.  I'm going on the assumption that the input is a single stream where it isn't practical to have multiple readers.  If multiples work, it's safe to add more of these threads, up to the number of channels your input environment provides.  The important point here is that offloading the input onto a queue as quickly as possible gets the thread back to reading more input or being I/O bound without adding any delay while it's processed, maximizing the ingestion rate.

Processing - Grabs items from the input queue, converts them to JSON objects, decides what type they are, cooks up the correct database action and puts that on an output queue.  In other words, this is all of the parallelizable, CPU-intensive work.

Output - Takes items off the output queue and does your database writes.  These threads do almost no processing and, like the input threads, spend most of their time waiting for I/Os to complete.

The benefit in this model is that you can use the state of the queues to make decisions about how to tune the system:

Continued growth in the average input queue length means there aren't enough processing threads to handle the input load.  The solution is to either add more processing threads or, if you're out of physical cores, get a machine with more.  (Better might be another machine to pick up some of the load, but that's another discussion.)

Growth in the output queue means you have a bottleneck in getting database writes done.  Usually you'll want as many output threads as the database can handle in parallel.  Any more and you're just offloading the overqueueing problem to the database.  (Some databases are better than others at dealing with that, so whether you go for more output threads is a decision only you can make.)

Title: How many threads should I use in my NIO server?

Body:
I've built a Java NIO TCP server, it currently uses four threads.
One ServerRunnable thread that uses a selector and three worker threads.

I've been looking around for some information about this, as I've read in the past that you should only have one thread per processor core. So that's that.

But that got me wondering recently, and after a little more research I came across this thread.

Where, in the comments on the accepted answer user Donal Fellows points out the following:

Have at most one CPU-bound thread per processor allocated to the application. IO-bound threads aren't a big problem (other than the memory they consume) and it's important to remember that apps can be restricted to only use a subset of the system's CPUs; after all, it's (usually) the user's/admin's computer and not the programmer's.

With that in mind, am I correct in thinking I can safely increase the number of selector threads and worker threads in my thread pool.

My server thread reads input, processes the data into JSONObjects and then pushes them to a queue. The worker threads then take the JSONObjects from the queue, checks what type of objects they are and then pushes them to the database.
So there is very little computational work going on there. Is it safe enough for me to increase the number of threads here, as in use more ServerRunnable threads and more worker threads?
Say to double the amount of each for example?

What do I need to think about when considering something like this?


问:
Is it necessary anymore to extract logic from API controllers?
I've been working in MVC web frameworks since its they started getting popular with RoR and ASP.NET MVC. I have always been careful to never put "business logic" on my controllers since that couples the framework with the logic. These days, like many of you, I'm not really using the MVC part of my framework, since I'm not returning "views" and framework artifacts. Instead, I'm just using routes to controller actions to build API's that return xml or json.

In the past couple years, I've been trying to move closer to CQRS, so my business logic ends up being packaged in commands and handlers with a dispatcher to connect the two. The "real" business logic is actually in my entities, but my command handlers drive the operations. I have also started allowing multiple services to expose different bounded contexts (micro-services). Then I started thinking "outside the box" (outside for me, at least).

Why do I bother with dispatcher, commands, and command handlers? Now that my framework is only a networking layer over my bounded context, why not let my controllers be my command handlers? Why not let my dispatcher be the routing system in my framework? Why not let the content of the HTTP request be my command?

答:
Short Answer

The primary benefit of decoupling application logic from any presentation/external interfacing layers is to allow consumers to vary independently without duplicating logic.  Therefore, the necessity of decoupling is dependent upon how many consumers your application will have.

Long Answer

Using Domain-Driven Design nomenclature, your question could be recast as "Why include an 'Application Layer' within your solution architecture?".

The Application Layer is intended to serve as the interface to the domain and infrastructure needs of your application, translating request and response messages into interactions with the underlying components.  By 'translating' here, we mean the conversation of a logical message in some standard format into zero or more operations upon the underlying components.  Ideally, a request to a "Fund Transfer Application Service", which verifies the input, instructs the domain to perform a transfer, persists the domain state, logs the operation, and notifies the world by calling a "Notify World Infrastructure Service", could be called by either a component or subcutaneous-level test, a Web Application, a console application, or be exposed as a Web service without modification. That said, the  degree any given solution benefits from such separation of concern strategies depends upon the context.

There are, however, other factors which may lead you to want some degree of decoupling from the consuming interface aside from a need to service multiple consumers.  For example, the ASP.Net MVC architecture tends to steer developers into grouping operations together for a given view/Web page.  For operations that go beyond simple CRUD operations on a single aggregate root, Microsoft's design has a tendency to lead to controllers which lack cohesion with respect to the adapter role-stereotype they are meant to serve.

To explain further, while you might have a CustomerController who's actions are all about customers and nothing but customers, each action may require different collaborators to accomplish their goal, not all of which are needed for every operation.  One action might need to save something to a database, another may need to send an email, and another may need to cache data or place something on a message queue.  Just because all these actions center around a single aggregate root doesn't mean the role the controller is meant to play (i.e. adapter) is cohesive with respect to its own responsibilities.  Ideally, a Web framework would take an inbound HTTP message and map it onto a command handler within the Application Service layer without requiring the Application Service Layer to take a dependency upon the Web framework.

Architecture theory and Feng shui motivations aside, it really all boils down to your need to reuse the application logic that you are going to either place in your Web page/code behind/controller/command handler.  Typically, the first client that should consume your application logic is your executable specifications and the second is the production interface.  Depending upon your approach to testing (none, user acceptance, isolation, etc.) along with the ease in which any framework dependencies you take on as part of the application logic implementation effort allow you to implement the specification's observations, this will often determine the degree of decoupling you want to include within your application.


答: You will need to learn SQL at some point and it's probably better to learn it sooner rather than later. You'll need to know a thing or two about databases no matter what framework or language you work in so the effort spent on learning SQL won't be wasted. Most frameworks and languages try their best to abstract the database access layer but it varies from language to language and you won't see the unity unless you know SQL. Lately there's a push away from relational databases but it's still a good idea to learn the basics of SQL simply because many of the terms and concepts have analogs in non-relational settings as well.</p>

Title: What languages should I know if I'm interested in building web applications?

Body:
I'm interested in developing for the web and I'm curious what languages should I know besides html, css, javascript, php/python/ruby. I don't know much about c# or java to make a decision whether to learn them or not, are they used much in the field I'm interested in?
What other technologies should I look into ?</p>


问:
What is the (craziest, stupidest, silliest) thing a client/boss asked you to do?
See title, but I am asking from a technical perspective, not

Take my 40 year old virgin niece on a date or you're fired.

答: Well, this one time I bid on a freelance reverse engineering job, only to discover that they quite literally wanted me to be able to change the past.</p>

OwnerDisplayName: Torvaun


问:
Does Silverlight have a future?
Recently I have read some articles/blogs/comments about the development and history of WPF and Silverlight. In some forums many developers and users criticize the performance of WPF applications (for example Visual Studio 2010). Actually the market share of Silverlight in comparison to Flash is not very high. At PDC 2010 Bob Muglia said something like "our Silverlight strategy and focus going forward has shifted...." and Microsoft wants to push HTML5 in the future.

Additionally, Microsoft has announced HTML5 being a core part of the Windows 8 and Windows Phone 8 ("Mango") platforms.

Recently I have started learning Silverlight and now I must ask myself, if I should continue investing time in learning these (in my opinions) very nice and powerful technologies!? Does they have a future? Does (Windows) desktop (client) applications have a future? Does so called "Rich Internet Applications" have a future? Or will HTML5 become the "absolute truth" in software development?

What is your opinion and what do you think?

答:
I think Silverlight is pretty much game over now (market share wise) since both Flash and Silverlight will be giving way to HTML5 in the next few years.

WPF on the other hand is likely to stick around (even though the performance concerns are valid) Windows Vista / Windows 7 are both heavily invested in WPF and it will likely be the desktop strategy for Microsoft for the next few years (at least), especially considering that VS & Expression are written using WPF.

But, of course that's the Desktop strategy, and it's growing clear that most applications that people use day to day are going to migrate from the Desktop to the Web (if they haven't already) as HTML5 browser support becomes ubiquitous. WPF is still (arguably) the best choice for applications which require the Windows Desktop and .Net but these are likely to be niche versus web based apps which will be the mainstream.

Other than HTML5, mobile platforms (read: Android and iOS) are likely to be the growth areas for development for the next few years.

Title: Does Silverlight have a future?


答:
I'd say that HTML5 is valid for as long as you want to produce applications that are targeting as many possible customers as possible.

Should your application require internet access? Should it use the native cababilities of the computer? (files, monitoring, etc). Does it require sharing of information?
All of these questions and more to it guides wether or not you can or should produce your applications as a Rich Web App, or if it should be developed as a client-based application.

There is definitly a place for WPF applications in the future, especially in the near term. Silverlight seems to be the target for sandboxed development such as phones, but we'll see how that train goes. But at the start of any development you should look at the requirements of the application, what you want to achieve and select your technology accordingly.

Now however I'd like to point out that there is no reason not to learn Silverlight or WPF, even if it is not what will be the major player in 6 or 7 years. If there is one thing I can tell you for sure, then it is that technology changes. There will be a HTML6, there will be a next WPF, and you will have to learn more than one technology if you truly wish to understand the first one.

Just start to learn one of them, and you can always switch and take what you've learned with you to the next technology.

Title: Does Silverlight have a future?

Body:
Recently I have read some articles/blogs/comments about the development and history of WPF and Silverlight. In some forums many developers and users criticize the performance of WPF applications (for example Visual Studio 2010). Actually the market share of Silverlight in comparison to Flash is not very high. At PDC 2010 Bob Muglia said something like "our Silverlight strategy and focus going forward has shifted...." and Microsoft wants to push HTML5 in the future.

Additionally, Microsoft has announced HTML5 being a core part of the Windows 8 and Windows Phone 8 ("Mango") platforms.

Recently I have started learning Silverlight and now I must ask myself, if I should continue investing time in learning these (in my opinions) very nice and powerful technologies!? Does they have a future? Does (Windows) desktop (client) applications have a future? Does so called "Rich Internet Applications" have a future? Or will HTML5 become the "absolute truth" in software development?

What is your opinion and what do you think?


问:
Do people in non-English-speaking countries code in English?
I've heard it said (by coworkers) that everyone "codes in English" regardless of where they're from. I find that difficult to believe, however I wouldn't be surprised if, for most programming languages, the supported character set is relatively narrow.

Have you ever worked in a country where English is not the primary language?

If so, what did their code look like?

答:
I'm Hungarian, working in my home country with a team consisting mostly of fellow Hungarians. We always write our code and comments in English, since that is the official language of the company anyways. In addition to that, some of our projects are open source, which really mandates that everything is in English.

This has a funny side effect, by the way: sometimes my mind stays in "English mode" after work and I keep thinking in English on the way home.


答:
Silverlight + Flash vs HTML5.  Oh boy.  There's been a TON of discussion around this one.

Let's focus on Silverlight (though many of the same arguments can be made for Flash).  Is it dead in Microsoft's eyes?  NO.  Just watch the recent Firestart event, specifically Scott Guthrie's keynote (Plenty of new features coming):

http://www.silverlight.net/news/events/firestarter/

What it gives you:

The ability to write Internet apps (and desktop if you use Out-Of-Browser) in your favorite dotNET language, today.

Give your users highly interactive and rich interfaces across all major browsers and platforms in a consistent manner, today.

Access to advanced APIs on the client (this is a fairly weak argument as JavaScript always has new libraries being added and it is pretty awesome).

Windows 7 Phone programmability - Silverlight is one of the two primary "native APIs" to the WP7.  That's one device at least that you can build apps for natively.

The downside:

Mobile - There are a ton of mobile devices that Silverlight will NEVER be on.  Not gonna happen.

Microsoft - Let's face it.  Lots of people will refuse to use it just because it's Microsoft.  Some of your users will refuse to install the runtime because it's Microsoft.  It's dumb, yes, but it's a fact.

Oh there are others.  Do I really need to iterate all the down-sides?

HTML5 will answer many (if not all) of the downsides we can think of for Silverlight.  But what are the downsides to HTML5:

It's not a finalized spec.  Yes, many browsers implement a lot of features of HTML5, but many browsers don't, or many do it in different ways.  And even if they do implement it today, there's no guarantee the spec won't change over the next few months/years.

It's not 100% ready today.  Again, there is lots of talk about what HTML5 will bring, someday.  But for a lot of stuff, it's just that.  Talk.  While some CORE stuff has been done (animation, graphics, etc), there are still a lot of pieces that are WAY up in the air and nowhere near being standardized on every implementation yet (hardware API access for devices like accelerometers for example).  You can start using some of these pieces today, but you will be locked into certain browsers, and again there is no guarantee you won't have to change your code as the spec approaches finalization.

Browser consistency - If you think HTML5 is going to be exactly the same across all browsers/devices then you are delusional.  Every browser will implement it slightly differently and you will need to have code to detect the browser and insert the appropriate "interpreter".  It will be easier to detect the browser I'm sure, and I'm sure libraries will help (like JQuery does today), but it will still be an issue.

App Stores - The fact is that no one is going to buy your HTML5 app like they do with Apple apps today.  If you want user's to buy your app through an App Store then you are going to need to write to the device's native library.  Again, there's been a ton of debate around this issue, but the fact is that all modern mobile devices provide browser access and browser-based apps just don't have the appeal of a native app.  Apps built today using HTML/CSS just don't have the appeal that their native counterparts do.

The way I see it, Silverlight gives you the "rich client" ability today.  You don't get access to every device (especially mobile), but for certain classes of apps it's a great choice and will remain so.  HTML5 will be a serious contender very soon and I strongly encourage everyone to learn it.  You WILL need it.

Title: Does Silverlight have a future?


问:
What's your favourite quote about programming?
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!

答:
```<code>to understand recursion you must first understand recursion
</code>```

LastEditorDisplayName: Roger Pate


答:
To get a quick start, you might want to look at frameworks like Ruby on Rails, Django or Grails. To use them, you need to learn Ruby, Python resp. Groovy.
Those languages are relatively easy to learn, so if you are new to web application programming, you might want to start with one of them.

JavaScript, HTML, CSS are necessary in any case. You will probably need some SQL, too.


问:
What are solutions and tradeoffs to maintain search result consistency in a web application
Consider a web application with a custom search function that must display the results in a paged manner (twenty per page with up to hundreds of thousands of total results) and the ability to drill down to individual results that maintain next/previous links to navigate through the results.

Re-executing the search on each page request to get the appropriate results for that page of data can be too expensive (up to 15s per search).  Also, since the underlying data can change frequently (e.g. addition of new results), re-executing could cause the next/previous functionality to result in inconsistent behavior (e.g. the same results reappearing on a later page after having been viewed on an earlier page).

What options exist to ensure the search results can be viewed across multiple pages in a consistent manner, and what tradeoffs does each option have in terms of network, CPU, memory, and storage requirements?

EDIT: I thought caching the query search results was an obvious necessity.  The question is really asking about where to cache the result set and what tradeoffs might exist to each.  For example, storing the ids of the entities in the result set on the client, or storing the IDs of the entities themselves in the users session on the web server, or in a temporary table in the database.  I'm not looking specifically for a single solution as different scenarios may result in different approaches (and such a question would be more suited for stackoverflow.com rather than here), but more of a design comparison between the possible approaches.

答:
Make your searches immutable

Most of the potential problems you cite can be rendered immaterial by simply caching the results of a particular search.  In other words, do not re-run the search each time you display the next results page.

In a typical web application, a search function takes the form of a query result, where each page is delivered as it is needed, using some helper functions.  When you perform the search, you need to cache the results of the search somewhere, and deliver each page of the search as it is requested.

In the Microsoft .NET world, this would be done using Skip() and Take() functions on a Linq query.  The code might look something like this:

```<code>var searchResults = from tableToSearch
                    where myConditions
                    select someFieldsToDisplay;

var pageResults = searchResults.Skip((requestedPageNumber- 1) * resultsPerPage)
                               .Take(resultsPerPage)
</code>```

So searchResults becomes the record set containing the results of your search, and pageResults contains the requested records from that search results for that particular page.

In most applications, the freshness of the search results is a non-issue, provided you make it clear to the user that, if they want results that are newer than two or three minutes old, they can simply perform a brand new search.

Body:
Make your searches immutable

Most of the potential problems you cite can be rendered immaterial by simply caching the results of a particular search.  In other words, do not re-run the search each time you display the next results page.

In a typical web application, a search function takes the form of a query result, where each page is delivered as it is needed, using some helper functions.  When you perform the search, you need to cache the results of the search somewhere, and deliver each page of the search as it is requested.

In the Microsoft .NET world, this would be done using Skip() and Take() functions on a Linq query.  The code might look something like this:

var searchResults = from tableToSearch
                    where myConditions
                    select someFieldsToDisplay;

var pageResults = searchResults.Skip((requestedPageNumber- 1) * resultsPerPage)
                               .Take(resultsPerPage)

So searchResults becomes the record set containing the results of your search, and pageResults contains the requested records from that search results for that particular page.

In most applications, the freshness of the search results is a non-issue, provided you make it clear to the user that, if they want results that are newer than two or three minutes old, they can simply perform a brand new search.


问:
How do you maintain productivity outside of work? (Programming Schedule)
I enjoy programming, but programming at work is just that, work. I would like to further develop my own personal interests in programming. Throughout the week I imagine myself completing a small project on the weekend or finishing up a programming related book. However, in reality I often fall short of my expectations. I often will get just one or two chapters of reading done and even less coding. In reality I will spend time surfing the net, watching television, or visiting friends and slacking off... because it is the weekend. But when Sunday evening rolls around I often reflect on my weekend and I am sorely disappointed with my use of time.

So my question is how do you maintain your productivity outside of work? I am sure some programmers could care less about programming on their free time. Although, I think the majority of programmers, especially on stackexchange, are passionate about programming.

Should I spend the weekend programming, or will I burn out and resent programming if I dedicate that much time to it?

How should I go about programming on my free time? Should I set a schedule? How much time should I dedicate to it? Most importantly how do I follow that schedule? Its only human nature to procrastinate.

I know there is a lot of questions here. Feel free to answer the ones that relate to how you remained focused outside of work. I am passionate about programming but after 40 hours of programming it can be difficult to maintain that enthusiasm.

答:
I find that my home programming is reasonably proportional to the amount of joy I feel going to work. When the office is a terrible drudge that makes me want to gouge my eyes out with a spork, then no programming gets done at home (and frequently I won't even turn on the computer/console to play games. When I'm in the mood/place of "woo hoo! it is 6am! time to get up and rush to work!" then I'm doing a lot of coding at home as well.

Spending too much time doing work, or work-like ventures is a path to burn out. Go with Walter's advice above.

When I am learning a new language or framework for the office, I try to devote about 4 hours on the weekend for it. Usually it ends up being on Sunday morning-afternoon, because that's where the largest single block of time I haven't promised anyone else is located (it is also the time when some of the folks in my life are in church, so they aren't going to be calling me on the phone).


问:
Why does it matter that HTML and CSS are not programming languages?
Example here:

What languages should I know if I'm interested in building web applications?

Yes, I understand that HTML and CSS are not Turing-complete.  Yes, I understand that they are declarative, not imperative languages.  But why are people always clubbed over the head with this pedantic (and arguably obvious) fact when they ask a question about these languages?

答:
It doesn't matter. And it's also a matter of definition. What is a programming language? Some mean that it has to be Turing-complete. Others have other definitions, that make HTML a programming language. (And in your example, they weren't even called programming languages, just languages, which they obviously are).

My recommendation: Try to ignore people who point out these kinds of pointless and in many senses even incorrect claims. It's just a variation of grammar nazi-ism. Calling HTML a programming language isn't incorrect in any meaningful sense.


答:
Tell a Civil or Mechanical Engineer that you studied "Software Engineering" and they'll tell you that "Software Engineering" isn't real engineering.

Tell an F-16 pilot that you fly Cessnas for fun and he'll tell you you're not a real pilot.

Tell a doctor that you're a chiropractor and he'll tell you... well, let's not go there :-)

I think it's mostly that people don't like the idea of their profession being infiltrated by pretenders or people who aren't really "worthy".

Now, to be fair, it's quite clear that HTML and CSS are not programming languages. They're no more programming languages that the .docx format is a programming language, and to claim that you're a programmer if all you know is HTML and CSS is certainly inaccurate. But I think some of the vehemence in the reply can be attributed to what I said above.

Also, in the question you linked, the questioner called HTML and CSS a "language", not a "programming language". HTML is a markup language and CSS is a language too (I don't know what "kind" of language you'd call CSS, though?), so I think it was a bit unfair to call him out for calling them "languages"...

Title: Why does it matter that HTML and CSS are not programming languages?

Body:
Example here:

What languages should I know if I'm interested in building web applications?

Yes, I understand that HTML and CSS are not Turing-complete.  Yes, I understand that they are declarative, not imperative languages.  But why are people always clubbed over the head with this pedantic (and arguably obvious) fact when they ask a question about these languages?


答:
It doesn't really matter to me so much.

But I presume that to those for whom it does, the distinction between HTML, CSS, XML, etc. and Real Programming Languages™ is kind of like the distinction between wood and paint as building materials. You can't build things with paint like you can with wood, and likewise you can't program with HTML like you can with an RPL.

I grant you though, for some conversations, making such a distinction can be irrelevant, and therefore pedantic and annoying.


答:
HTML and CSS are not programming languages. Get Over it.

However:
JavaScript is a programming language. The machine is the browser.
PHP is a programming language. The machine is a virtual one in the server.

So if you are doing only using HTML and CSS, you are not doing any programming (although you might be doing some engineering).

But if you are using JavaScript, PHP, or another scripting language. You ARE doing programming.

As for REAL programming languages. If you are operating on a machine (real one, or virtual). And are using YOUR OWN algorithms to tell the machine to do things. Then you are using a REAL programming language.


问:
Will high reputation in Stack Overflow help to get a good job?
In a post, Joel Spolsky mentioned that 5 digit Stack Overflow reputation can help you to earn a job paying $100k+. How much of that is real?

Would anyone like to share their success in getting a high paid job by virtue of their reputations on Stack Exchange sites?

I read somewhere that, a person got an interview offer from Google because a recruiter found his Stack Overflow reputation to be impressive. Anyone else with similar stories?

答:
Probably not. Look at it from a different perspective:

How many 5-digit SO users are looking/willing to accept another job for "only" 100K?

What percentage of people looking to fill 100K jobs have ever heard of SO and if so would use it as a criteria for hiring?

Some day they may be able to make the connection between SO scores and their job & CV posting site.

Maybe another question would be, would you consider SO scores for hiring?


问:
Best books on the theory and practice of software architecture?
I have a couple of developers at my company who wish to move from programming into architecture. What are the best books out there on the theory and practice of software architecture? Include a cover picture if you can.

Feel free to include general books, and also books that relate to a specific technology.

答:
Documenting Software Architecture: Views and Beyond by Clements et al. from the Software Engineering Institute.

Cover of Documenting Software Architecture http://ecx.images-amazon.com/images/I/512Fz-vNz5L._SL160_.jpg


答:
Just Enough Software Architecture by George Fairbanks.

Cover of 'Just Enough Software Architecture' http://ecx.images-amazon.com/images/I/61%2BhzVm5IoL._SL160_.jpg

Title: Best books on the theory and practice of software architecture?

Body:
I have a couple of developers at my company who wish to move from programming into architecture. What are the best books out there on the theory and practice of software architecture? Include a cover picture if you can.

Feel free to include general books, and also books that relate to a specific technology.


答:
Simplicity is prerequisite for reliability.

-- Edsger W. Dijkstra

Body:
What's your favourite quote about programming?

One quote per answer, and please check for duplicates before posting!


问:
Is outsourcing code more expensive in the long term? Does it harm code quality?
I am aware of a company that owns the intellectual property of a decent software product and makes an excellent income from licensing per annum. However, the director (non technical) complains about the cost of maintaining the development team, as it eats significantly into the profit margins, and is considering outsourcing development of specific modules to other countries that charge at a lower rate.

Personally, I don't think this will be a more cost effective solution in the long term. This can lead to communication breakdowns when there are problems, additionally the specifications will need to be water tight which can end up taking taking more time anyway. In my opinion, when working in teams communication is key - or is there an effective way of making this work?

答:
My only experience of outsourcing to a company in another country will be my last. The company that was hired, failed to complete their work on time or even remotely meet the specifications, and resulted in us having to redo the whole lot again in-house.

However, if you can find a reliable company you can trust (i.e. you've seen/heard good things about them from other people) then maybe it's worthwhile.


答:
Yes - you get what you pay for.

In my experience, unless your market and development needs are so dead simple they can easily be explained via email to any developer with a possible language barrier, and so dead simple that even a developer who isn't really invested in the company can still succeed at creating a quality product, then yes your product will suffer.

I worked at a company where we had a large local development team, and our product suffered simply because the management team poured more money and effort into sales.  Because so much effort was poured into sales, it appeared we were doing "fine" - but it meant to earn revenue we were bound to keep pouring money and resources into the sales process.

We had a remote team but we integrated them fully into the company and they participated at the same level as our local teams. That's the only way it can work. I was the local team leader for them and we flew out to work on site with them regularly.  We gave them company shirts and jackets just like the local teams.  After all things considered, it maybe saved us 20-30%.  If you put together a system that attempts to cut costs by more than that, your product will suffer accordingly.

Title: Is outsourcing code more expensive in the long term? Does it harm code quality?

Body:
I am aware of a company that owns the intellectual property of a decent software product and makes an excellent income from licensing per annum. However, the director (non technical) complains about the cost of maintaining the development team, as it eats significantly into the profit margins, and is considering outsourcing development of specific modules to other countries that charge at a lower rate.

Personally, I don't think this will be a more cost effective solution in the long term. This can lead to communication breakdowns when there are problems, additionally the specifications will need to be water tight which can end up taking taking more time anyway. In my opinion, when working in teams communication is key - or is there an effective way of making this work?


答:
I'm sure that someone has an example of this working, but I haven't seen it.

I've worked in a Fortune 500 company for many years where they outsourced alot of development.  I don't have a single example in those years of an outsourced project costing less than if we had done it ourselves (in-house).

While their programming rates were less than ours, we spent 3 times the amount of time managing the outsourced team than we do for in-house teams.  That's on top of the added time needed to have the requirements more detailed than our in-house team needs and the added time needed in QA because the code was never close to being correct.


答: You can have quickly, you can have it cheaply, or you can have it done well. You can't have all three, and I would argue that even two out of three can be a stretch.</p>