答:
You’re noticing the difference between parameters and arguments, and also the notion of scope.

A parameter is a name that refers to a value passed into a function. Consider a trivial function definition:

```<code>def f(x):
    return x
</code>```

Here, x is a parameter of f. An argument is the value assigned to a parameter during a function call.

```<code>print f(42)
</code>```

Here, 42 is an argument to f. In a function call, you can think of substituting all the instances of the parameter (name) with the argument (value). So when you write f(42), what the interpreter does is return 42.

Similarly, when you write buildConnectionString(myParams), it is exactly as though you had written:

```<code>";".join(["%s=%s" % (k, v) for k, v in {
    "server":"mpilgrim",
    "database":"master",
    "uid":"sa",
    "pwd":"secret" }.items()])
</code>```

params is replaced with the value of myParams, and the resulting statements are executed.

Title: Confusion regarding def function within Python

Body:
I've been learning Python for about 2 months now (Started with Learn Python The Hard Way, now reading Dive Into Python), and within both books, I still seem to be confused over this one bit of code.

Lets just take the default code that Dive Into Python uses as an example:

```<code>def buildConnectionString(params):
    """Build a connection string from a dictionary of parameters.

    Returns string."""
    return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

if __name__ == "__main__":
    myParams = {"server":"mpilgrim",
                "database":"master",
                "uid":"sa",
                "pwd":"secret"
               }

print buildConnectionString(myParams)
</code>```

How does the function buildConnectionString with the argument (params) know to get its data from the variable myParams?  Or params.items(), too within the return line?  Wouldn't the argument in buildConnectionString need to be set as buildConnectionString(myParams) in order for it to read properly?  How can you set the variable of your data to myParams, but have the argument of your function be params and have it read?  How does it know to read myParams as params?

And is there a reason behind not naming your variable params, or vice versa naming your argument in your function myParams?  It's just been extremely confusing seeing the argument set as one word, and then having the variable named something completely different, but having the function still be able to read your code, even when the argument name is different from your variable with the data you're printing from.

Body:
You’re noticing the difference between parameters and arguments, and also the notion of scope.

A parameter is a name that refers to a value passed into a function. Consider a trivial function definition:

def f(x):
    return x

Here, x is a parameter of f. An argument is the value assigned to a parameter during a function call.

print f(42)

Here, 42 is an argument to f. In a function call, you can think of substituting all the instances of the parameter (name) with the argument (value). So when you write f(42), what the interpreter does is return 42.

Similarly, when you write buildConnectionString(myParams), it is exactly as though you had written:

";".join(["%s=%s" % (k, v) for k, v in {
    "server":"mpilgrim",
    "database":"master",
    "uid":"sa",
    "pwd":"secret" }.items()])

params is replaced with the value of myParams, and the resulting statements are executed.


问:
How do you prioritize initial sprints to maximise the chance of catching architecture errors early?
I've worked on several projects that have used agile successfully as a means of providing continuous improvement on an already mature piece of software. But I've found it's much harder to be "agile" when pre-planning something. An element of waterfall is necessary to produce initial functional specifications and a sensible architecture, as per this question: How do you explain to an "agile" team that they still need to plan the software they write?

However, you still want to be as fast, as light and most of all as flexible as possible. One of the big dangers in traditional software design is misunderstandings, resulting in major architectural changes that are only caught late in the process.

I have recently joined a project which had woefully insufficient planning and is in the most horrendous mess. While salvaging what I can, I'm left wondering what previous developers could have done (besides some planning) to catch the huge architectural problems in the system at an early stage.

If we presume a moderate amount of pre-project planning, how can I best allocate work in initial sprints to catch the (probably inevitable) architectural issues in the solution as early as possible?

EDIT: After reading the answers, and some suggested articles, I feel I made need a bit of clarity in the question. I understand that Agile requires some upfront design, but that it ought to be kept to a minimum, and it needs to be done with an eye to flexibility.

What I'm trying to discover are whether there are any tricks, tips or techniques to ensure that we correctly identify the parts of the project that need the most rigidity, prototype and iterate them first, and catch problems there as early as possible?

答:
I have been working on a project from its early stages and what I have learnt is adopting mindset of agile and 'failing fast' can really help project moves forward.

Firstly you have to make sure that you can make things working by having proper POC and from their starting building your software but at same time you shouldn't spend lots of time and resources to design best architecture. code also can be kept simple and basically just workable and then you always can have refactoring PBIs in later iteration where you make it more complicated.

Beside that it is good to find out those critical things in your project and try to fail your architecture as fast as possible! so you can validate it fast and early instead of late phases. for instead if you have different components in your arch and when they are workable (not necessary complex enough) it is a good idea to start integration those components together and see if they can work together or something is missing

ContentLicense: CC BY-SA 3.0


问:
Implementing an anti-corruption layer with domain logic
I'm building an application that compiles a single PDF document from multiple source PDF documents as follows: it takes the first page of each source document, stamps certain information on top of each of those pages, and then combines all those "first pages" into an output PDF document.  Assume the source PDFs already exist.

I'm using a third-party class library to manipulate the PDFs, i.e. extract the first pages, apply the stamped information, and combine pages to output the resulting PDF.  My goal is to keep those PDF manipulation operations independent of my domain logic layer so it will be easier to swap out the third-party library if needed in the future.  For this, I'd like to make use of an anti-corruption layer.

I imagine my domain will consist of one class (at this point): PdfDocument.  The domain logic layer will load a collection of PdfDocument objects from file or another type of input stream and make use of services exposed by the anti-corruption layer to produce a single output document which has the characteristics I mentioned earlier.  I can envision two possible ways of architecting this:

expose the following distinct services on the anti-corruption layer: 1.) extract the first page of a PDF document, i.e. return a PdfDocument that is one page, 2.) stamp provided text at the top of a provided PdfDocument, i.e. return a new PdfDocument that contains the stamped text, and 3.) combine multiple PdfDocument objects into one PdfDocument, i.e. return a new PdfDocument that is all pages from the provided PdfDocuments combined.

expose a single service on the anti-corruption layer which takes a collection of PdfDocuments and returns a single PdfDocument with the aforementioned characteristics.

The first approach seems more in line with separation of concerns because the second approach would have to take on a lot of the domain logic considerations such as "how many pages do I extract?", "do I stamp every page?", and "which of the extracted pages to I include in the output?".  However, the first approach is much-less efficient because each service returns a PdfDocument.  The third-party library I'm using has a Document class and an intermediate class -- Page -- which represents a page belonging to a whole PDF Document.  If I use the first approach, the third-party library would have to bundle everything up into a Document and then output a PdfDocument for each service.  However, if I use the second approach, I can more-efficiently operate on each PDF because the input PDFs can be broken down into Page objects to which the stamps could then be directly applied, and those Page objects could then be combined into the resulting Document and only then returned as a PdfDocument.

I've considered adding a PdfDocumentPage class to my model as one solution to this, but then my model is taking on concerns that it shouldn't necessarily have.  I have no need for the notion of a "page" in my model other than to facilitate a more-efficient use of the third-party library, and that, to me, defeats the purpose of the anti-corruption layer.

Please help me work through this!

答:
I sounds like you're trying to create an adapter around a third party library to avoid it becoming coupled in your business logic. Out of the two approaches you mention, the first one seems the best idea, as it's the most flexible and you can separate your business logic from the adapter (i.e. the adapter will basically be a pass through to the third party library).

However, you'd like to take advantage of a possible intermediate state of processing offered by the library. One way of doing this might be to use the builder pattern.

```<code>Adapter.CreateBuilder() -> returns the builder object
Builder.AddFirstPageFromDocument(binary data) -> returns the page number
Builder.StampPage(page number, message)
Adapter.CreateDocument(builder)
</code>```

That's just a brief example, you could hide all the adapter inside the builder object or each method could live in the adapter and you would pass the builder to each method (in which case it becomes more of a state/context object rather than a builder object).

If you're still not comfortable with introducing additional objects into your domain, however, I would definitely sacrifice efficiency for a clean separation (i.e. stick with the first option and return the whole document each time), purely from a maintenance perspective.

Body:
I sounds like you're trying to create an adapter around a third party library to avoid it becoming coupled in your business logic. Out of the two approaches you mention, the first one seems the best idea, as it's the most flexible and you can separate your business logic from the adapter (i.e. the adapter will basically be a pass through to the third party library).

However, you'd like to take advantage of a possible intermediate state of processing offered by the library. One way of doing this might be to use the builder pattern.

Adapter.CreateBuilder() -> returns the builder object
Builder.AddFirstPageFromDocument(binary data) -> returns the page number
Builder.StampPage(page number, message)
Adapter.CreateDocument(builder)

That's just a brief example, you could hide all the adapter inside the builder object or each method could live in the adapter and you would pass the builder to each method (in which case it becomes more of a state/context object rather than a builder object).

If you're still not comfortable with introducing additional objects into your domain, however, I would definitely sacrifice efficiency for a clean separation (i.e. stick with the first option and return the whole document each time), purely from a maintenance perspective.


答:
tricks, tips or techniques to ensure that we correctly identify the
  parts of the project that need the most rigidity,

Guess and hope you get lucky.  Experience will help.

prototype and iterate them first, and catch problems there as early as possible?

Deliver something as soon as possible.  The sooner it fails the less painful it will be to toss it out.  Don't plan.  Do and learn.

Title: How do you prioritize initial sprints to maximise the chance of catching architecture errors early?

Body:
I've worked on several projects that have used agile successfully as a means of providing continuous improvement on an already mature piece of software. But I've found it's much harder to be "agile" when pre-planning something. An element of waterfall is necessary to produce initial functional specifications and a sensible architecture, as per this question: How do you explain to an "agile" team that they still need to plan the software they write?

However, you still want to be as fast, as light and most of all as flexible as possible. One of the big dangers in traditional software design is misunderstandings, resulting in major architectural changes that are only caught late in the process.

I have recently joined a project which had woefully insufficient planning and is in the most horrendous mess. While salvaging what I can, I'm left wondering what previous developers could have done (besides some planning) to catch the huge architectural problems in the system at an early stage.

If we presume a moderate amount of pre-project planning, how can I best allocate work in initial sprints to catch the (probably inevitable) architectural issues in the solution as early as possible?

EDIT: After reading the answers, and some suggested articles, I feel I made need a bit of clarity in the question. I understand that Agile requires some upfront design, but that it ought to be kept to a minimum, and it needs to be done with an eye to flexibility.

What I'm trying to discover are whether there are any tricks, tips or techniques to ensure that we correctly identify the parts of the project that need the most rigidity, prototype and iterate them first, and catch problems there as early as possible?


问:
Confusion regarding def function within Python
I've been learning Python for about 2 months now (Started with Learn Python The Hard Way, now reading Dive Into Python), and within both books, I still seem to be confused over this one bit of code.

Lets just take the default code that Dive Into Python uses as an example:

```<code>def buildConnectionString(params):
    """Build a connection string from a dictionary of parameters.

    Returns string."""
    return ";".join(["%s=%s" % (k, v) for k, v in params.items()])

if __name__ == "__main__":
    myParams = {"server":"mpilgrim",
                "database":"master",
                "uid":"sa",
                "pwd":"secret"
               }

print buildConnectionString(myParams)
</code>```

How does the function buildConnectionString with the argument (params) know to get its data from the variable myParams?  Or params.items(), too within the return line?  Wouldn't the argument in buildConnectionString need to be set as buildConnectionString(myParams) in order for it to read properly?  How can you set the variable of your data to myParams, but have the argument of your function be params and have it read?  How does it know to read myParams as params?

And is there a reason behind not naming your variable params, or vice versa naming your argument in your function myParams?  It's just been extremely confusing seeing the argument set as one word, and then having the variable named something completely different, but having the function still be able to read your code, even when the argument name is different from your variable with the data you're printing from.

答:
Okay, when I understood you correctly your problem is that you don't know why params inside the function is associated with the dictionary myParams you put into the function, right?

Okay, lets start at the beginning:

When you have the following python code, how does Python know that you can call the upper() method (which makes it all caps) on the variable?

```<code>a = "hello"
...
print a.upper()
</code>```

a could have been an integer if we wrote a = 1 instead of a = "hello". But as you might have learned already, python is a dynamic language and is able to handle this without defining what a variable should hold in the first place.

Now to your problem with the function. Let's say that we got the following function:

```<code>def divide(a,b)
    return a / b
</code>```

a and b are not only parameters, they are variables. When python sees the line result = divide(4,2) it technically does the following:

```<code>""" Create local variables and assign the input values to them """
a = 4
b = 2
result = a / b
""" Because the variables were local they do not exists after the function
    call ended """
</code>```

If we now try to call this function as divide("hello","world") the program crashes because you cannot use division on strings. So far so good.

So your question can be reduced on the following problem:

```<code>myParams = { "foo":"bar", "meow":"purr" }
someOtherVariable = myParams
print someOtherVariable["meow"]
</code>```

How does Python know that someOtherVariable can be treated as myParams? Because we told it to be the same. And that is exactly what happens when you call your function with myParams. It implicitly makes params = myParams until the end of the function call. This code works because the function assumes that the content of params has the methods you call on it (in this example items()). If it doesn't it crashes. You can try this by calling buildConnectionString(1). It will say that int has no attribute 'items'.

TLDR; Function parameters are like normal variables. Python tries to do with them what you wrote in your function body - if the you call functions on the objects which they don't have your program crashes like it would do when you did the same thing to a normal variable.

Body:
Okay, when I understood you correctly your problem is that you don't know why params inside the function is associated with the dictionary myParams you put into the function, right?

Okay, lets start at the beginning:

When you have the following python code, how does Python know that you can call the upper() method (which makes it all caps) on the variable?

a = "hello"
...
print a.upper()

a could have been an integer if we wrote a = 1 instead of a = "hello". But as you might have learned already, python is a dynamic language and is able to handle this without defining what a variable should hold in the first place.

Now to your problem with the function. Let's say that we got the following function:

def divide(a,b)
    return a / b

a and b are not only parameters, they are variables. When python sees the line result = divide(4,2) it technically does the following:

""" Create local variables and assign the input values to them """
a = 4
b = 2
result = a / b
""" Because the variables were local they do not exists after the function
    call ended """

If we now try to call this function as divide("hello","world") the program crashes because you cannot use division on strings. So far so good.

So your question can be reduced on the following problem:

myParams = { "foo":"bar", "meow":"purr" }
someOtherVariable = myParams
print someOtherVariable["meow"]

How does Python know that someOtherVariable can be treated as myParams? Because we told it to be the same. And that is exactly what happens when you call your function with myParams. It implicitly makes params = myParams until the end of the function call. This code works because the function assumes that the content of params has the methods you call on it (in this example items()). If it doesn't it crashes. You can try this by calling buildConnectionString(1). It will say that int has no attribute 'items'.

TLDR; Function parameters are like normal variables. Python tries to do with them what you wrote in your function body - if the you call functions on the objects which they don't have your program crashes like it would do when you did the same thing to a normal variable.


答:
Your first approach looks much cleaner than the second, but I do not think you have to sacrifice performance necessarily by choosing this design.

Assumed it turns out the approach is really not efficient enough, then you could use your PDFDocument as an abstraction over your preferred pdf representation "behind the scenes". What you call a PDFDocument, does not need to be exactly what your third party library calls a document, so it could alternatively be a certain page range within the latter. If you follow that route, extracting the first page from a PDFDocument can be implemented internally just by setting the page range from "page 1 to page 1", without creating a new original "3rd party document object". The stamp operation then internally has to make use of that page range, as well as the final merge.

So I guess it should be possible to have both: a simple representation for PDFDocuments in your adapter layer, and the usage of internal optimizations provided by your library vendor without exposing them to your domain layer.

Title: Implementing an anti-corruption layer with domain logic

Body:
I'm building an application that compiles a single PDF document from multiple source PDF documents as follows: it takes the first page of each source document, stamps certain information on top of each of those pages, and then combines all those "first pages" into an output PDF document.  Assume the source PDFs already exist.

I'm using a third-party class library to manipulate the PDFs, i.e. extract the first pages, apply the stamped information, and combine pages to output the resulting PDF.  My goal is to keep those PDF manipulation operations independent of my domain logic layer so it will be easier to swap out the third-party library if needed in the future.  For this, I'd like to make use of an anti-corruption layer.

I imagine my domain will consist of one class (at this point): PdfDocument.  The domain logic layer will load a collection of PdfDocument objects from file or another type of input stream and make use of services exposed by the anti-corruption layer to produce a single output document which has the characteristics I mentioned earlier.  I can envision two possible ways of architecting this:

expose the following distinct services on the anti-corruption layer: 1.) extract the first page of a PDF document, i.e. return a PdfDocument that is one page, 2.) stamp provided text at the top of a provided PdfDocument, i.e. return a new PdfDocument that contains the stamped text, and 3.) combine multiple PdfDocument objects into one PdfDocument, i.e. return a new PdfDocument that is all pages from the provided PdfDocuments combined.

expose a single service on the anti-corruption layer which takes a collection of PdfDocuments and returns a single PdfDocument with the aforementioned characteristics.

The first approach seems more in line with separation of concerns because the second approach would have to take on a lot of the domain logic considerations such as "how many pages do I extract?", "do I stamp every page?", and "which of the extracted pages to I include in the output?".  However, the first approach is much-less efficient because each service returns a PdfDocument.  The third-party library I'm using has a Document class and an intermediate class -- Page -- which represents a page belonging to a whole PDF Document.  If I use the first approach, the third-party library would have to bundle everything up into a Document and then output a PdfDocument for each service.  However, if I use the second approach, I can more-efficiently operate on each PDF because the input PDFs can be broken down into Page objects to which the stamps could then be directly applied, and those Page objects could then be combined into the resulting Document and only then returned as a PdfDocument.

I've considered adding a PdfDocumentPage class to my model as one solution to this, but then my model is taking on concerns that it shouldn't necessarily have.  I have no need for the notion of a "page" in my model other than to facilitate a more-efficient use of the third-party library, and that, to me, defeats the purpose of the anti-corruption layer.

Please help me work through this!


问:
Interview Question - Adding Method to interface that has been implemented by thousands of class
There is scenario where I have Interface X, which has been implemented with my thousands of classes. Now I want to add new method in that Interface X. So how to make the changes in minimal way to solve the problem of overridden of methods in all my classes.

Please don't add default methods of Java 8 in the answers.

答:
The comment is correct, if you really have thousands of classes and no common base class, that's a code smell that should be solved first. Classes that share a common interface but no code whatsoever should be rare.

Otherwise, use a tool. Resharper for C# for example will give you an option to actually implement that method in all classes that implement the interface. That's obviously only a part of the work to be done, but at least it still compiles. For literally thousands of classes, I guess writing your own tool would still come ahead of doing it manually.


问:
Can I use GPL libraries temporarily for prototyping and make the future code closed source?
I am working on a prototype for a software system, which (at least at the start) will be closed source.

In order to save time, I'm thinking of using (that is, statically linking) a library that is licensed under GPLv3, so I can test my design quickly. If I distributed the software at this stage, I'd have to distribute source code along with it.

What if I don't, but satisfy myself that my system works, and then replace the GPL library with my own code before distributing? Would the result be "contaminated" by the GPL?

I have a feeling that retaining the GPL library in my Git history or not may make a difference.

答:
As long as you don't release the software to anyone while you are linking to GPL'd libraries, you are safe. The viral aspect of GPL only kicks in if you distribute your software.

It would be better if you could find a library with a more permissive licence, of course, like LGPL or APL2 or MIT.


答:
If you provide access to the revisions using the GPL'd code, they will be completely GPL'd. But you don't want to, as that wouldn't be closed-source...

For any later state which no longer uses any GPL'd code, that you used GPL-code sometime earlier is simply irrelevant.

Title: Can I use GPL libraries temporarily for prototyping and make the future code closed source?

Body:
I am working on a prototype for a software system, which (at least at the start) will be closed source.

In order to save time, I'm thinking of using (that is, statically linking) a library that is licensed under GPLv3, so I can test my design quickly. If I distributed the software at this stage, I'd have to distribute source code along with it.

What if I don't, but satisfy myself that my system works, and then replace the GPL library with my own code before distributing? Would the result be "contaminated" by the GPL?

I have a feeling that retaining the GPL library in my Git history or not may make a difference.


答:
First thing I would try in this situation is to avoid an interface change at all. You could add an extended interface, derived from the original one, with the new method added, and make the code which uses that interface in combination with the new method expecting to get an object of type "ExtendedInterface".

If that is not possible, for example because the code in stake is outside of your control, you could add an abstract class with a default implementation for the new method in the inheritance hierarchy between the interface and all derivations. Even for thousands of classes, the necessary changes in the code base can probably be made in a few hours with some global searching/replacing, or by creating a small script or helper program, with a low risk of breaking something.

Which of this approaches is better depends on which part of the code base you are actually allowed to change, and what "minimal way" actually means.

Title: Interview Question - Adding Method to interface that has been implemented by thousands of class

Body:
There is scenario where I have Interface X, which has been implemented with my thousands of classes. Now I want to add new method in that Interface X. So how to make the changes in minimal way to solve the problem of overridden of methods in all my classes.

Please don't add default methods of Java 8 in the answers.


答:
I don't think your question is actually about the GPL. It's about the prototype and whether it will be used in the future as the basis for the deliverable software system.

If you're making a throwaway prototype and you are not going to reuse any of the code in your deliverable system, then go ahead and use a GPL library.

Three Approaches You Can Take

However, if you're going to evolve the prototype (something lots of managers push for!) you have three approaches you can take:

Move the non-core parts into separate applications that communicate with your core over JSON or a REST API or some other Inter-Process Communication language/library. Your non-core parts thus can be GPL as well and you can use any GPL libraries in them.

Design your code so that you can swap the libraries out. This means creating a facade that hides the implementation details. When you're ready to switch to a proprietary library or MIT/BSD library.

Don't use the GPL'd code at all.

I suggest you go with the first approach because then you have open source work that you can use in the future as part of your professional portfolio.

The second approach is also good because that's how you should be designing the system anyway, creating the exact functions/classes you need and stubbing them out until you have the library or custom code that fills in that functionality.


答:
This is a practice that I have seen in the industry.

They create a new interface with a number appended, for example Interface2 and make this contain methods in the old interface.

Make the old interface deprecated

When there is a major overhaul, a new package will most likely be added in (think about the overhaul when Java JDK introduces the new mechanism for file and IO in nio). This is the time to remove the number from the interface, having a new interface in a different package

This approach allows new methods in the interface, you can have very flexible solution for various way to implement the new interface.

It doesn't break existing users.

It provides a buffer period when the changes can consolidate and/or be experimented before the old interface is actually removed after deprecated.


问:
Scrum Daily meeting: Punctuality over Full team presence?
My understanding is that a Daily Scrum meeting should be very quick, hosted in a friendly way and that it requires all the team members present. Because it is objective is to have everyone up to date with what everybody else is doing.

I like Scrum Daily Meetings that are held like that.

In my latest project our Daily Scrums are more like a Status Update meeting. Although the position is that we are holding Scrums and practicing proper Agile.

We are a distributed team, in 2 different countries, and the people that is in the same Country are not in the same office. As consequence we have virtual Scrums.

The problem is that our meetings always start on time, many people calls before the actual start time, so they actually start at the very first second of the meeting. Without any tolerance for small delays.

For example the last time we were on the phone and the person coordinating the meeting checked if everyone was on, and we said one of our team members was not on yet but he was calling. And I was told to start sharing without waiting for my team member.

Also everyone has a lot of meetings, and sometimes they are back to back with the Scrum meeting, so it is understandable if they arrive during the first or second minute of the meeting.

Is that the normal for teams practicing Daily Scrums? It is the first time that happens to me.

I can not find any bibliography directly about it. Although the presence of all team members is stressed, it is stressed also that the meetings should always start at the same time. But I imagine there can be a small delay tolerance.

I even read on a blog someone suggesting that the Scrum Master can place penalties if someone arrives "5 seconds" late. I thought the Scrums were supposed to be friendly, and having a penalty like that seems counter productive.

What is the recommended approach in a situation like this?

答: People over process. That's one of the core tenants of Agile, if a process isn't working for your team, scrap it or modify it. Let the team modify it to fit their needs.


问:
How to stop / avoid Over Time on a Scrum Team?
Actually, I'm helping a small software shop on their Scrum Implementation. Recently the Scrum Master reported me that he has a problem because the Team is working Over Time to achieve the Scope (Committed Backlog). So they have an Unreal Velocity.

My formal question(s) is / are:

Apart from speaking about on the Retrospective Meeting; do you think that is a good idea to implement some hard-blocks to avoid Over Time?

If so, what techniques / tools do you suggest?

Revision Control system (SVN, GIT, HG, etc...), blocks by hours (8 to 5)

Work station blocks by hours (8 to 5) or cumulative hours (up to 8 hrs/day)?

Other(s)...

Or, maybe, do not hard-block this kind of things; but implement some "Penalty System" for Unjustified Extra Hours?

First: Tks all for your fast responses.

@Baqueta (and others with similar questions): No they are not been paid for Extra Hours. My first advise to them was to review their estimates because maybe they were underestimating.
This was my favorite advise:

If they have an interest in working overtime, remove it. Development isn't something you can do for 60 hours a week and stay productive, and there are numerous studies out there that prove this. If overtime pay is the issue, get rid of it and improve their base pay so they're getting what they're worth.

Also, I think that the root problem (for this team), is a combination of the following:

The developers are being told what they must achieve in a sprint/aren't being consulted on what's achievable/are being ignored when they say there's too much work.

The developers are consistently underestimating how much time tasks will take/how many units of work are involved in each task.

Summary: I'll talk to the Team to review their estimates, and with the P.O. because I feel that they are not being consulted about the scope, as you mentioned.

答:
To avoid overtime, you have to cut the scope of the project.

The following chart shows where uncertainty lies in a project:

If you notice, at the product definition and requirements phases, you have a huge variance in estimation of effort. You can't be sure if it will take a month or a day to implement the feature.

I'm betting that none of the tasks are done done because they're simply too large and unspecified and there's too many of them.

If your team can handle 10 tickets in 5 days, and they're assigned 20 tickets, cut that number down, kick it up to the product owner/project manager/manager/client and tell them to prioritize.

At this point that's the only way to save the team from overtime. You can't deliver everything, but whatever you do deliver will be less likely to have bugs.

I would also advise looking for a new job and helping your team mates to do the same and fix up their resumes and professional portfolios. A company that expects overtime is one no one should work for and the software produced will be buggy as hell.


答:
There are several issues to consider, before deciding how to make the code change.

Consider the case when third parties have written code that uses or implements this interface.  That would significantly increase the complexity of managing the code changes required, as well as adding a political element to the process - creating work (and cost) for other companies.

As this interface has already been implemented in many classes is a strong indicator against making changes to the current interface.  The consequence on all the implementations of this new interface method need to be considered.

The fact that all these implementations have been completed without needing this new method is a warning flag that perhaps this is not really core to this interface purpose, and that this should be implemented as a new separate interface on the basis that this is a separate (but related) use of the object, and requires its own interface.

That said, assuming that we control all code that uses this interface, I would implement the new method in all classes implementing the new method explicitly.

e.g.

```<code>public class MyObject : ITheInterface
{
    public void ITheInterface.NewMethod(int age)
    {
        throw new NotImplemented("NewMethod needs to be implemented on MyObject");
    }
}
</code>```

By implementing the method explicitly like this, code only calls the new implementation when it is using a reference typed as ITheInterface for the object.

Body:
There are several issues to consider, before deciding how to make the code change.

Consider the case when third parties have written code that uses or implements this interface.  That would significantly increase the complexity of managing the code changes required, as well as adding a political element to the process - creating work (and cost) for other companies.

As this interface has already been implemented in many classes is a strong indicator against making changes to the current interface.  The consequence on all the implementations of this new interface method need to be considered.

The fact that all these implementations have been completed without needing this new method is a warning flag that perhaps this is not really core to this interface purpose, and that this should be implemented as a new separate interface on the basis that this is a separate (but related) use of the object, and requires its own interface.

That said, assuming that we control all code that uses this interface, I would implement the new method in all classes implementing the new method explicitly.

e.g.

public class MyObject : ITheInterface
{
    public void ITheInterface.NewMethod(int age)
    {
        throw new NotImplemented("NewMethod needs to be implemented on MyObject");
    }
}

By implementing the method explicitly like this, code only calls the new implementation when it is using a reference typed as ITheInterface for the object.


问:
Does Separation of Concerns applies to GUI components?
In an application I developed with C#, I use a webbrowser control, it should navigate to some websites, then I would like to extract some contents from the webpages. I do it by manipulation of DOM and removing some nodes. It can be done automatically or manually with the help of user.

Then I have two modes, surfing mode and extraction mode. I think switching between modes and updating related controls and menus and responding to events... has made my program complicated. What is your advice to make it less complicated?

Does Separation of Concerns applies to GUI components too?

答:
Separation of concerns is just as important in UI as anywhere else, if not more so.  Anything that doesn't directly involve user interaction does not belong in the UI.  It belongs somewhere else.

Consider what happens when you create a UI having the usual event hooks:

```<code>private void Form1_Load(object sender, EventArgs e)
{
    listView1.Items.Add(new ListViewItem("this is a test"));
}
</code>```

What happens if you put all of your business logic in your form?  You wind up with a big ball of mud, that's what.  That's why we put business logic in another module, class or DLL.

Whether this is what's happening with your application is an open question.  As I see it, there's two possible approaches.  You can have a single UI with two modes, or two different UI's.  If the modes are dramatically different, I usually prefer two different UI's, as you can avoid all of the if statements that way, and your design is generally cleaner.  You can refactor common functionality between the two UI's into a separate module, class or DLL.

Body:
Separation of concerns is just as important in UI as anywhere else, if not more so.  Anything that doesn't directly involve user interaction does not belong in the UI.  It belongs somewhere else.

Consider what happens when you create a UI having the usual event hooks:

private void Form1_Load(object sender, EventArgs e)
{
    listView1.Items.Add(new ListViewItem("this is a test"));
}

What happens if you put all of your business logic in your form?  You wind up with a big ball of mud, that's what.  That's why we put business logic in another module, class or DLL.

Whether this is what's happening with your application is an open question.  As I see it, there's two possible approaches.  You can have a single UI with two modes, or two different UI's.  If the modes are dramatically different, I usually prefer two different UI's, as you can avoid all of the if statements that way, and your design is generally cleaner.  You can refactor common functionality between the two UI's into a separate module, class or DLL.


答:
I can think of two aspects to consider with your approach. The first is straightforward, by not distributing your project or (or as it's GPLv3, making it available for public use) whilst you are using code that is released under the GPL, it is hard to see how you would be required to distribute your code under the GPL license too under the redistribution terms.

The second aspect is possibly more significant to you. When you create your own implementation to replace the GPL library, you need to be careful not to create an derivative work. Whilst I am sure you have good intentions, on not directly copying source code - you are more likely than not going to copy significant portions of the library API.

If this is a commercial product, this risk needs to be considered and assessed by reading through the GPLv3 license carefully, and where there is doubt, asking for a professional legal opinion.


答:
Think of it like this, what is the point of the daily stand up?

It is your opportunity to raise impediments with the rest of the team, to flag up that you may need assistance, and to highlight changes that will affect others.  It is important that you as a developer are there.

With a team of 4 -8 developers, they need to be quick and snappy - 30 seconds each most of the time. If  was performing the role of scrum master, I would be concerned about late starting of the meetings as it would increase the meeting cost.  Likewise, variable meeting times create a distraction for everyone - are we about to...  I would also be very aware of balancing this with the needs to ensure the team is able to support each other, so may delay the meeting if needed because someone who was likely to be impeded was on the telephone / toilet.

Where teams are distributed geographically like you are describing, I would be flagging this up as a team impediment at EVERY retrospective. It is blatantly an impediment to the scrums performance and communication that they are not all sat together and able to communicate freely and easily.

I would be arguing that this should be organised as two separate scrum teams, and work organised so that scrum of scrums should handle the international communication.

Title: Scrum Daily meeting: Punctuality over Full team presence?

Body:
My understanding is that a Daily Scrum meeting should be very quick, hosted in a friendly way and that it requires all the team members present. Because it is objective is to have everyone up to date with what everybody else is doing.

I like Scrum Daily Meetings that are held like that.

In my latest project our Daily Scrums are more like a Status Update meeting. Although the position is that we are holding Scrums and practicing proper Agile.

We are a distributed team, in 2 different countries, and the people that is in the same Country are not in the same office. As consequence we have virtual Scrums.

The problem is that our meetings always start on time, many people calls before the actual start time, so they actually start at the very first second of the meeting. Without any tolerance for small delays.

For example the last time we were on the phone and the person coordinating the meeting checked if everyone was on, and we said one of our team members was not on yet but he was calling. And I was told to start sharing without waiting for my team member.

Also everyone has a lot of meetings, and sometimes they are back to back with the Scrum meeting, so it is understandable if they arrive during the first or second minute of the meeting.

Is that the normal for teams practicing Daily Scrums? It is the first time that happens to me.

I can not find any bibliography directly about it. Although the presence of all team members is stressed, it is stressed also that the meetings should always start at the same time. But I imagine there can be a small delay tolerance.

I even read on a blog someone suggesting that the Scrum Master can place penalties if someone arrives "5 seconds" late. I thought the Scrums were supposed to be friendly, and having a penalty like that seems counter productive.

What is the recommended approach in a situation like this?


答:
The GPL writes:

You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions:

So this condition only applies if your work is "based on" the library, which the licence defines as follows:

To “modify” a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a “modified version” of the earlier work or a work “based on” the earlier work.

That is, your program is "based on" the library if and only if it is a derivative work according to copyright law. The legal definition of that term varies somewhat among jurisdictions, and usually does not directly address software. For instance, the US Copyright Act writes:

A “derivative work” is a work based upon one or more preexisting works, such as a translation, musical arrangement, dramatization, fictionalization, motion picture version, sound recording, art reproduction, abridgment, condensation, or any other form in which a work may be recast, transformed, or adapted. A work consisting of editorial revisions, annotations, elaborations, or other modifications which, as a whole, represent an original work of authorship, is a “derivative work”.

What this means for software must be interpreted by the courts, based on earlier similar rulings. I am not sufficiently familiar with the relevant case law in your jurisdiction to say with certainty how a court would decide your case. One could argue that "replacing the GPL library with own code" is an act of translation, particularly if your code is strongly inspired by the GPL implementation. Even reusing the API of the GPL library could land you in hot water (see Oracle vs. Google).

If the answer matters to you, I recommend seeking competent legal advice rather than asking strangers on the internet.


问:
Advice on new git / deployment workflow
I work with a small team that until recently didn't use source control. I'm working on the layout of our development/deployment workflow with git. I would appreciate and advice or insight you might have.

I'll spare you the details but we are basically using the git flow branching model and deploying with a remote pointed to a bare repo on the production server with a post-recieve hook. My question is with a larger project we have been developing. This is an application that will have many instances that will need to be able to update from the master branch of the applications repo but also have it's own set of unique files (front end project specific files).

I'm a little lost and I think it may be because I have the deployment scheme a little off. I've heard many people say "git isn't for deployment" and an equal number saying the opposite. The system works great for us currently pushing to the remote that deploys it based on that server's post-receive hook.

One deployment idea we have is to have a list of branches from the App's master that will have it's own 'projectA-master' and 'projectA-develop' branches that will follow our current git workflow. This leads us to having MANY branches on the original App repo and that feels wrong. Not to mention it doesn't scale well. We only have four servers slated for deployment but this method is awful when it gets to be 20 or more. That's a deal breaker.

```<code>master---A---B---C
   \\ \
    \\ develop--A--B--C
     \\
      \projectA-master--C--D--E
       projectA-develop--C--D--E
</code>```

Yuck.

Another idea was to have the App repo for development and updates and another repo (maybe App-frontend) that would be specific to each project and have a similar branching model above only not in the original App repo preserving it's code and branches to only core app specific development. Then having both deploy into the remote server.

```<code>master(App)---A---B---C---E---F----G
    \                            /  \___
     develop---A---B---C---E----F    ___ Live Instance
                                    /
master(App-frontend)---A---B---C---E
    \                             /
     develop---A---B---C----E----F
</code>```

This too feels wrong.

I used .gitignore to ignore all of the directories that are project specific but the problem I had there was that my FE files were not being source controlled on the remote server, they remained un-tracked.

I don't know how to push updates from the app master repo and not override the custom files on the project specific (remote server repo) level.

So how do you manage a situation like this? You've a product that will have many instances but each instance has client specific front end files. And how is this managed on a large scale of hundreds to thousands of instances and you still need to push out updates/fixes?

I've been all over these and other forums and I've gotten pretty far from not really utilizing git at all. If you have the time I would appreciate some input from those of you more experienced that can tell me what I'm doing wrong and what I'm doing right.

Thank you very much.

答:
Welcome to the world of change management and deployment.

Git - with gitflow is one of the best source control tools out there at the moment for managing the software development side of creating a product.  But the key part of that sentence is source control tools.

There are several other aspects to the solution you are looking for.

Build Automation - Jenkins, Team City, CruiseControl.NET are examples in this category.  These products take code from your source control and compile it into programs, run unit tests, do code analysis and publish artefacts from this build process.

Artefact Respository - Artifactory, Archivia, Nexus are examples of this type of product.  These act as versioning stores for the build artifacts.  You can request the latest of this build, or specify version 1.35 and get compiled official outputs

Deployment - Chef, Puppet, Salt, CF-Engine are examples that manage the deployment. These tools handle the configuration and installation of the software (and many OS aspects too)

There is a lot of work involved in setting up this kind of environment, but when you are deploying software to large numbers of servers, this is import to do, and to do it with care and precision.

Title: Advice on new git / deployment workflow


问:
Can you "stop" a C program from being reverse engineered?
I'm sure that many of the middle to high level languages can be reverse engineered. But if a C program can be reverse-engineered, and turned back into editable source code, how do I discourage such a thing?</p>

答:
Any program can be reverse engineered, because of the very simple principle that anything that a computer can execute has to be in a format where a person that understands machine code can read. (With the proper tools of course.)

The real question is, how easy is it to reverse engineer?  C is trivial to decompile; I've seen some surprisingly clean C code generated from decompilation tools.  But because C doesn't have the same rich metadata as managed languages, you lose a lot of useful information, such as names of variables and data types, that help out with the task of reverse engineering.  (Then again, most managed code systems have an "obfuscator" tool available that mangles the metadata to make such tasks more difficult on the reverse engineer.  So the difference may not necessarily be all that big.)


答:
It is impossible to prevent reverse engineering for any program that runs on your computer. But you can make steps that make it harder...

Program languages like Java and .NET are trivial to recreate human source code for, as they are byte code 'compiled'. Meaning the programming language is compiled into a set of tokens that are interpreted by a run time engine or 'virtual machine'. This makes the reverse compilation an achievable task.

Because of this ease of obtaining C# source code for any .NET library, there are several tricks often done to make it harder. One approach is to rewrite the code so that all the class and method names are not meaningful and similar. This makes the C# source code 100% available, but usually unintelligible to a human to understand what is going on in the code.

The next step is to make this harder is to create an encrypted version of the library, with wrapper code that decrypts the byte code library in memory. This makes it harder, but there is nothing stopping a determined person using an assembler debugger to step through the decryption process until the .NET byte code was decompiled and then doing a memory dump to get to the byte codes.

C has a huge advantage in protecting the source code, in that the source is compiled into machine code. This is not fool proof though. To allow developers to step through their code, the compiler will have options that prevent optimisations reorganising the code, and worse still, often add additional data to the executable to provide context to the code that would be useable for decompilation.

Where C code is non-trivial, compiled with optimisations turned on and stripped of all debugging data, trying to recreate understandable source code is beyond the effort/reward for most people.

That said, I learned how to program in assembler as a child by single stepping through the assembler tape loader code on ZX Spectrums designed to make it harder for people to copy, and/or alter the program to give you infinite lives.

Spending three days in a long summer holiday stepping through the code that was transcoding the set of bytes stored on the tape into the modified tape loading code that actually loaded the game seemed like a good use of my time back then, and started me out on a long career as a software developer as an adult.

Title: Can you "stop" a C program from being reverse engineered?

Body: I'm sure that many of the middle to high level languages can be reverse engineered. But if a C program can be reverse-engineered, and turned back into editable source code, how do I discourage such a thing?</p>


问:
Convert x and y velocity to x and y velocity relative to another point
The question I asked probably isn't very clear, so I'll explain. If I have an x and y velocity, where the y goes towards the bottom of the screen, and the x goes towards the right of the screen, how would I convert the x and y velocity so that the y goes from the point to the particle at hand, and the x goes at a 90 degree angle from the y? If that explanation wasn't clear, then the reason I need to do this is so that I can minus a velocity as a particle tries to go away from a gravity source, but that source isn't just at the bottom of the screen.

What I have:

What I want:

Examples would be appreciated

答:
This is simpler than you think.  Suppose you have a particle at position P with velocity V, and there is a gravitational attractor at G.  The acceleration will act in the direction (G - P), call it A.  Of course P, G, V, and A are all two-dimensional quantities.

You have to update position and velocity with each increment of time dt.  You already know the new position is P + V dt.  The new velocity will be V + A dt.  There is no need to transform any vectors.  You just have to calculate A = k(G - P).


问:
Should I request the backend for every small piece of dynamic data?
Let's suppose there's a page implemented with AngularJS.
Ideally the frontend (Angular app) and backend (Web services/API/ call it whatever you like) should be 100% separated from each other which means that frontend project doesn't have access to database at all. And that's what I want to achieve.

Let's say we're rendering product list. The workflow is:

request and render HTML template (including JS code)

Angular app runs

Angular loads dynamic data (products data to show the list) and put it into the template.

We've made 2 requests so far (excluding js/css/images etc.) which is fine. Simple, effective, just great.
And that's what more or less is shown in tutorials/guides.  But that's not the reality. What I'm wondering is what about small pieces of data that are rendered across whole app layout but have to be retrieved from database.

Exmaples of such data are:

usename of logged in user in top right corner

menu with categories on the side bar

even <select> options in forms are often loaded from database (categories again for example)

For me it doesn't make sense to make a request to backend for each of these pieces of data because it makes a lot of http requests to make on every page refresh/init

How to deal with it?

答:
At a super-high level, there's exactly two ways to mitigate this problem:

1) Allow "batch" server requests, so you can get all these random bits of data in one round-trip. This seems appropriate for all the little lists of categories you need to put in side bars and form fields.

2) Cache information on the client so you don't have to re-request it for every page. In particular, the username could easily be part of whatever session id/token/cookie/thingy you use to keep the user "logged in", and categories for the side bar are probably going to be the same on most pages.

As James said, there is some risk of premature optimization, but reducing the total number of server hops is almost always a performance win (when the server isn't doing anything besides fetching bits of pre-computed data for you).


答:
If I understand your needs correctly you want three things:

Your FE (front end I think) / config files to be tracked in source control (so, git).

You want different configuration files for different installations.

You don't want those configuration files shared.

One possible solution that occurs to me is to have different git repositories.

There would be one for the main source code, branches, etc as you have already described.

The other repository (which would need to be in a different directory outside of the main project, though presumably accessible by it) would be a repository that is only for the config files.  It is a git repository so has all of the advantages of source control but is not tied to the other repository.

Actually managing this still requires some choices.  You might have a default 'template' repo (read only) which is initially cloned and acts as a template, and then have branches for each install within it might be one option.

btw One thing that you may see suggested by others is git submodules.  I would advise you avoid them.  They certainly seem like a good answer 'in theory' but in practice, at every workplace where I've seen them, they've not worked well at all.  The workflow is too different and manual when compared to the main git & branch workflow that is the default at many places.

Title: Advice on new git / deployment workflow

Body:
I work with a small team that until recently didn't use source control. I'm working on the layout of our development/deployment workflow with git. I would appreciate and advice or insight you might have.

I'll spare you the details but we are basically using the git flow branching model and deploying with a remote pointed to a bare repo on the production server with a post-recieve hook. My question is with a larger project we have been developing. This is an application that will have many instances that will need to be able to update from the master branch of the applications repo but also have it's own set of unique files (front end project specific files).

I'm a little lost and I think it may be because I have the deployment scheme a little off. I've heard many people say "git isn't for deployment" and an equal number saying the opposite. The system works great for us currently pushing to the remote that deploys it based on that server's post-receive hook.

One deployment idea we have is to have a list of branches from the App's master that will have it's own 'projectA-master' and 'projectA-develop' branches that will follow our current git workflow. This leads us to having MANY branches on the original App repo and that feels wrong. Not to mention it doesn't scale well. We only have four servers slated for deployment but this method is awful when it gets to be 20 or more. That's a deal breaker.

```<code>master---A---B---C
   \\ \
    \\ develop--A--B--C
     \\
      \projectA-master--C--D--E
       projectA-develop--C--D--E
</code>```

Yuck.

Another idea was to have the App repo for development and updates and another repo (maybe App-frontend) that would be specific to each project and have a similar branching model above only not in the original App repo preserving it's code and branches to only core app specific development. Then having both deploy into the remote server.

```<code>master(App)---A---B---C---E---F----G
    \                            /  \___
     develop---A---B---C---E----F    ___ Live Instance
                                    /
master(App-frontend)---A---B---C---E
    \                             /
     develop---A---B---C----E----F
</code>```

This too feels wrong.

I used .gitignore to ignore all of the directories that are project specific but the problem I had there was that my FE files were not being source controlled on the remote server, they remained un-tracked.

I don't know how to push updates from the app master repo and not override the custom files on the project specific (remote server repo) level.

So how do you manage a situation like this? You've a product that will have many instances but each instance has client specific front end files. And how is this managed on a large scale of hundreds to thousands of instances and you still need to push out updates/fixes?

I've been all over these and other forums and I've gotten pretty far from not really utilizing git at all. If you have the time I would appreciate some input from those of you more experienced that can tell me what I'm doing wrong and what I'm doing right.

Thank you very much.


问:
Function that would output all distinct values in an array
I want to create a function that outputs the distinct values in a given array. For example, in the following sequence 2 2 1 1 5 2 , the distinct digits are 2 1 5. What I've done till now is:

```<code>void Distinct(int a[], int b[], int n){

    int i;                    //n is the number of elements for a and b
    int k=0;                  //a is the original array
    int ac;

b[0] = a[0];
    for (i = 0; i <= n; ++i){
       if (a[i] != b[k])
                   {
                  k+=1;
                  ac = a[i];
                  b[k] =ac; //b is where I want to put distinct digits
                      }

    }

    for ( i = 0; i < k; ++i)
    {
        printf("%d ", b[i]);
    }
}
</code>```

But this is not enough, because what I've done is for the case when the numbers repeat one after another, I mean: 111122221 , I will get 121, and 1 at the end again.Can you please help me write a function that would consider this case, with repeating numbers scattered in the array ? Thank you.

答:
There are many, many ways of doing this, and you haven't really specified whether you're after something that's simple to code or optimally performant or if you have an upper bound on the possible numbers or any other restriction that might help us tell which answer you need.

But your sample code implies you want the solution in a "low-level" language where we're dealing with arrays made up of bytes rather than some higher-level construct like a list/tuple/vector that makes it trivial to do things like remove elements from the middle. Therefore, I would suggest you run a sort algorithm on the input array (if you're in C++, that would be std::sort), then run your Distinct() function on that sorted array to create a correctly unique-ified array.


答: You can reverse engineer any program, the result will not be the original source code with comments, descriptive variable names, structure etc. but its functionality will be the same. You cannot prevent this, you can make it more difficult but you cannot not prevent it because at  the end of day it will be instructions that the CPU will understand and thus you can interpret. The best way IMHO to prevent reverse engineering/pirate copy is to update your program frequently by adding more functionality, you will then reach a point when the effort to reverse engineer is too much of a hassle compared to buying/writing it yourself.</p>


答:
The lesser of two evils, if you are not allowed to refactor the implementing classes, is to not add the method to the interface. There is no reasonable situation where you should break compatibility with the existing interface. The new method belongs in a new interface, and any class that needs to use it will have to implement the new interface. Chances are, not all 1,000 classes that implement the existing interface will need the new method, and if you force them to you will end up with tons of empty implementations, which will be a waste of time and screen space for anyone involved in maintaining the code.

Regardless of the answer you end up giving for this question, I would seriously question whether or not you want to work for this company. If this is a common concern for them, then they clearly don't know what they're doing. If they don't actually have these types of issues, then they're wasting your time with a pointless interview question. Nothing good can come of this.


答: If you are planning to write your own code to replace the GPL code you will have a potential problem because you are not writing the code in a clean room environment. You would really want to have someone who has never looked at the GPL code write any replacement library.  On the other hand if you want to simply swap out a GPL library for an already published library that is under another license then this is not a problem, the other library was presumably already written in a clean room environment.</p>


答: If someone can observe the program in operation, they can reverse-engineer it.  Even if you could somehow prevent the user from accessing the internals of the program, they can perform black-box reverse engineering to build up a model of how the program reacts to various inputs.</p>


答:
Many anti-debugging techniques can be used to make reverse-engineering a hell of a task, but it's not impossible.

Malware authors use them regularly, and many are applicable to any native machine code, including that compiled from C.

A simple example that was really popular in the early years was inserting thousands of breakpoints to make running to a particular code point tedious, as you have to remove all those breakpoints first.

Other methods are polymorphism, self-modifying code and run-time decryption/encryption or cache-based hacks to conceal the execution paths taken as long as possible.

Additionally, you can use traditional obfuscation techniques such as creating decoy code, opaque value construction, extra jumps and pseudo-conditions to make understanding code harder.

This works for any language, not just managed .NET, Java or PHP where reverse-engineering is normally trivial, but also for C/C++.

Malware authors provide the best examples, e.g. Rombertik as analyzed by Cisco.

Hardening against rev-engineering is usually an economic problem:

how easy is it to add protections

how much does it hinder maintenance

how does it affect resource use and performance (e.g. memory, CPU use),

how compatible is it (does it work anytime, anywhere, may it trigger an anti-virus),

how hard is it to break them

This ends in the question: Is it worth it?

Are the savings higher than the expenses?

Are the costs for breaking higher than the potential gains from rev-engineering?

There are obfuscators available for popular languages to automate adding protection measures to your programs, but their quality varies.


答:
We have a name for a data structure that can only contain an element once: a set.

I have done this and tasks like it many times. Here is some pseudocode:

```<code>Array input = { ... };
Set output = ...;
for (int i : input) {
  output.add(i);
}
print output;
</code>```

Initialize the array and a set that will contain the array's contents. Then iterate the array, adding each element to the set. If the set already contains an element with the same value, it will do nothing. Once this is done, print the set. It will contain each value stored in the array a maximum of once.

Title: Function that would output all distinct values in an array

Body:
I want to create a function that outputs the distinct values in a given array. For example, in the following sequence 2 2 1 1 5 2 , the distinct digits are 2 1 5. What I've done till now is:

```<code>void Distinct(int a[], int b[], int n){

    int i;                    //n is the number of elements for a and b
    int k=0;                  //a is the original array
    int ac;

b[0] = a[0];
    for (i = 0; i <= n; ++i){
       if (a[i] != b[k])
                   {
                  k+=1;
                  ac = a[i];
                  b[k] =ac; //b is where I want to put distinct digits
                      }

    }

    for ( i = 0; i < k; ++i)
    {
        printf("%d ", b[i]);
    }
}
</code>```

But this is not enough, because what I've done is for the case when the numbers repeat one after another, I mean: 111122221 , I will get 121, and 1 at the end again.Can you please help me write a function that would consider this case, with repeating numbers scattered in the array ? Thank you.

Body:
We have a name for a data structure that can only contain an element once: a set.

I have done this and tasks like it many times. Here is some pseudocode:

Array input = { ... };
Set output = ...;
for (int i : input) {
  output.add(i);
}
print output;

Initialize the array and a set that will contain the array's contents. Then iterate the array, adding each element to the set. If the set already contains an element with the same value, it will do nothing. Once this is done, print the set. It will contain each value stored in the array a maximum of once.


答:
I think most of your problems will resolve themselves once you distinguish development from deployment.

git flow is a great workflow for development; but the cases in which I would push code to prod straight from source control are extremely limited. Probably only for personal projects or a very alpha-stage startup with no customers.

Once you've got a viable product, it's important to ensure that your codebase runs through some sort of sanity checks before it hits a prod box. As other answers have mentioned, Jenkins, Teamcity, or another CI server is a bare minimum. A continuous inspection tool like SonarQube or Coverity would be even better.

The git push-to-prod workflow also breaks badly when your new release requires dependency upgrades. That's where a config management tool really comes in handy.

To get back to your answer, I would probably maintain the core code – the stuff that doesn't change across vendors – in one repo. Each vendor gets its own vendor-specific repo. Use your CI build to overlay both repos into a common project, and then store the result as its own build artifact.

Let's say you're developing a Salesforce plugin. Store the general code in salesforce-plugin-core. Store the vendor extensions in vendor-a-extensions, vendor-b-extensions, and so on.

Create a CI job for salesforce-vendor-core. Use your CI tool's downstream job trigger mechanism to kick off the vendor-a-extension and vendor-b-extension jobs whenever the core job succeeds. Each vendor job should produce a final, vendor-specific package: something like vendor-a-plugin.jar and vendor-b-plugin.jar.

If you ever decide to become a SaaS provider (and it sounds like you might be), this workflow allows you to quickly push the vendor-specific packages to vendor-specific environments.

Title: Advice on new git / deployment workflow


问:
Building CMS from components
I have a design decision problem and would like to have some thoughts on it.

I'm building a CMS to use for my projects and want to incorporate existing components in it, like Doctrine, Monolog and any other i find suitable.

The question is, should I allow in code to access this each component directly, or should I have a buffer (proxy) class that acts as an API to underlying component?

In terms of performance/ease and access to full functionality i think it is better to allow this access, but in this case I lose control when component behavior changes (major version upgrade etc.). If I had a buffer class, i don't lock myself to particular component, and even can replace it with another, while not breaking backwards compatibility, but in this case I have to almost duplicate code from the component (I mean, function from my buffer class calls functions from component)

The CMS is written in PHP, if that matters.

答:
You need to weigh up each component and think about whether it really makes sense:

You need to think about how likely it is that you will need to substitute one library with another. In the case of an ORM, you may want to substitute one RDBMS for another, but an ORM typically already provides that abstraction so it's unlikely you'd also want to change your ORM.

You need to think about how universal the API of your proxy would be. There's no point crafting an intricate proxy API if you won't be able to maintain that API in the event you switch a component. For example, you probably wouldn't be able to maintain the same API if it is your intention to switch from an SQL to a no-SQL DBMS. On the other hand, it might be reasonable to drop in a different crypto library because most of those have similar functions and APIs.

Would the effort of writing a new proxy layer actually be lower than just updating the main codebase? If a library deprecates a function or two every few years which are only used in a few places it would be hard to justify writing a proxy for the whole library in case a small number of those functions happen to change which would only take minimal effort to update in each instance any way.

As general examples:

I probably wouldn't proxy an ORM because an ORM is already an abstraction, it would add significant complexity to transform the data structures returned by an ORM into something generic, and I'm probably not going to have a compelling reason to switch.

I probably would proxy something like a cloud object storage API, because it's likely that I might want to use a different storage provider in future and they often have a similar or identical API.

Perhaps more important than their API is your API.

If:

Your API is well defined, particularly in terms of what APIs are public and not

Your API does a good job of encapsulating the libraries within (ie. it avoids exposing implementation/library specific constructs to external consumers)

Your API is well covered by an automated test suite

Then even if you have to do significant re-plumbing of your application to replace a library or upgrade to a version with an incompatible API, you can at least be confident that your system still functions the same as it did before from an external perspective, and that you're not passing these problems onto your users.

Title: Building CMS from components


答: Simple, at least in the U.S. You just put an anti-reverse-engineering clause in the program's EULA, and threaten to sue the pants off of anyone who cracks it (this is no joke; the DMCA actually lets you do so).</p>


问:
Program to look at the first say 5 characters of a word and return a string if that string is actually the first 5 characters of a word?
For example, say I have a string and it has the letters:

RDNAL

This is not an actual English word or it doesn't start an actual english word, so the program would skip this string and would avoid it.

But say the string was:

MICRO

This is the first 5 letters of an actual word, like microwave or microprocessor, etc. And it actually is a word

I want to write a program in Java that will be able to see if a given string contains any block of strings that belong to a potential word.

I'm playing a game where I have to decypher a secret language, so I set numbers equal to each "character", and now I want to run each number and put an English letter to each number and see if it possibly spells out a word.

Is this possible or is this just way too massive to do? I'm asking here because I'm not sure if it's impossible or possible based on the number of combinations or some kind of program to reference to check words against.

I think I can write the program to add a letter to each number then rotate through and spit out a string, but I am not sure about comparing the string to an English word.

答:
Possible? Yes.

You should be able to download a word list (example) and compare each word's first five letters with your string, however it isn't going to be very efficient. IMHO.

If you need to check more than a few words, then it may be useful to look into optimizations. For example, you could precompute a giant HashMap which contains all valid 5 letter combinations and easily check against that.


问:
what are the limits of the client server architecture
i have developed a POS app as a stand alone app with its own database.
A customer needs 10 of the app in different PCs, but it should use one database.
This quickly brings a solution to mind. A Client/Server solution, in which the client apps talks to the server app. The server app will now be the one with the database

for each sale, the clients will be pulling current stock data/customer data/etc and also sending sale data to the server (at least every 20sec)

I need to know the realistic limits of data size that can be sent per second in a lan
Is my solution a good one

Are there any other solution that would be faster and better.

Please take note that each clients needs to login before performing anything on the client or server

An the clients activity needs to be monitored by the server

EDIT

The app would work in an office with four computer, the space between each client and the server is less that 100m

For now, there are only 10 client and one server

The lan speed is about 100 MB/s

答:
Answering this question with hard numbers would require knowing the number of clients, the quality of their network connections, the distances between them, each other and the server, how quickly the server responds to every possible request (at peak times!), and all sorts of other details. I would guess that the quality of their connections is probably where the hard upper limit lies.

The only reliable way to find out the concrete limits of an architecture is to build a prototype and test it. This is why "agile" methodologies are all the rage these days. Since you're talking about a LAN, it should be pretty simple to grab a dozen machines, hook them up in a similar fashion to your clients, and put simple programs on them that bombard each other with fake stock information.

P.S. To answer the more general question your title appears to be asking, the architectural limits of client-to-server are all about what the server(s) can do. When you add a lot more clients, you'll eventually need to add more servers (and load balancing), no matter what the app is; some apps may scale better with peer-to-peer. And of course, all network architectures are limited by speed and bandwidth of the network connection.


答:
The limitations of Client / Server implementations are well known.  Moving from a stand alone application to a client/server approach introduces some new issues for you to manage.

The Server will have multiple connections simultaneously. Handling this efficiently enough without having different clients causing contention on the database should be straight forward to solve with only 10 clients talking to the server.

Adding a network and a server adds latency.  as its on the same LAN, this is will not be huge per request, but keep an eye on how chatty your client needs to be with the server.

You have to decide the protocol that the client and server use to communicate and understand each other. A RESTful web service may well be a suitable approach for your needs

Change management.  When its one block of hardware, updates happen in isolation of other systems.  Now, when you need to roll out an upgrade, you have multiple clients talking to a server, rolling out upgrades needs a little more thought.

As you are interested on what kind of performance you can expect over a LAN, here is my view...

The typical network in an office is 1GBit Ethernet, that's capable of transferring to the server a maximum of around 50 MByte of real data a second.  If you are reaching this limit you have a serious design problem in your client server protocol.

If you have performance problems, the solution will be to make the client/server protocol more efficient, and that may mean more changes to the way the client side works than you are currently expecting.

This kind of project is interesting work, and may take you some time to deliver it right.  Make sure you have the spare time (and budget) for coping with the new learning you will be doing.

Title: what are the limits of the client server architecture

Body:
i have developed a POS app as a stand alone app with its own database.
A customer needs 10 of the app in different PCs, but it should use one database.
This quickly brings a solution to mind. A Client/Server solution, in which the client apps talks to the server app. The server app will now be the one with the database

for each sale, the clients will be pulling current stock data/customer data/etc and also sending sale data to the server (at least every 20sec)

I need to know the realistic limits of data size that can be sent per second in a lan
Is my solution a good one

Are there any other solution that would be faster and better.

Please take note that each clients needs to login before performing anything on the client or server

An the clients activity needs to be monitored by the server

EDIT

The app would work in an office with four computer, the space between each client and the server is less that 100m

For now, there are only 10 client and one server

The lan speed is about 100 MB/s


答:
The first thing you're going to want to do is figure out the requirements. If the customer says they currently need 10 clients, how many clients will they need in 5 years time when they shift to a larger premises? Will they want to have to completely redesign their POS system if/when that happens? Will they want to add other functionality later on (like stock management, or generating reports)?

The second thing you're going to want to do is figure out how you're going to approach fault tolerance. If the server goes down for any reason, do you want 10+ clients that are unusable and 10 checkout operators getting abused by impatient shoppers? Can you cache information at the client until the server comes back online? Do you need fall-over? How will you be doing backups (will you need to take the server offline to do the backup)?

The third thing you're going to want to do is decide on the protocol that clients will use to communicate with the server. Can it be raw SQL (with nothing more than a database running on the server)? Do you need additional layers in the server?

The fourth thing you're going to want to do is create a simulation/model of it. The idea here is to determine if the plan is viable (where are the bottlenecks, will the server's LAN connection need to be faster than the client's to keep up, how many clients could it handle, etc). You do not want to have one team of developers working for 6 months building the client software, and another team of developers working for 6 months building the server software; and then find out that it can't handle the load after its too late.


问:
Getting strokes and fill to align to pixel boundaries
While investigating ways to get the Cairo graphics API to draw a single-pixel line, I found this explanation in the FAQ.  It explains why often a single-pixel line gets drawn as a half-intensity line two pixels wide.

The reason that cairo does it this way is so that fills align nicely, at the cost that some strokes do not. It is not possible to set up sample locations in a way so that both fills and strokes with integer coordinates work nicely, so one had to be preferred over the other. One argument in favor of preferring fills is that all fills with integer coordinates align nicely this way. The best that can be done with strokes is to make all even-integer-width strokes align nicely (as they do in cairo) or to make odd-integer-width strokes align (which would then break the fill alignment).

After reading this explanation, I still don't understand why this is a problem with graphics generally.  What do they mean by odd-integer-width strokes breaking the fill alignment?  Why is it such a problem to have both fill and stroke aligned to whole pixels?

I guess I don't really understand why or how the stroke width affects the fill at all.

答:
Why is it such a problem to have both fill and stroke aligned to whole
  pixels?

It's not a problem at all. But you have to understand the used coordinate system and specify your coordinates accordingly.

Here, use integer coordinates for fills and even-width lines, but pixel-midpoint coordinates (i.e. floating point numbers ending with .5) for odd-width lines.

I don't really understand why or how the stroke width affects the fill at all.

It's not the stroke width, it's the choice of coordinate system. By choosing a coordinate grid aligned with pixel boundaries, fills bounded by integer coordinates align with pixel boundaries, while a line centered at an integer coordinate will extend to the pixels on both sides of the grid line. For lines with a width of 1, this means the line will only cover half of the pixel. Obviously, it is not possible to fill only half of a pixel, so the line will be drawn anti-aliased instead, i.e. The entire pixel will be filled with half intensity.


问:
Functional dependencies diagram
I'm searching for the correct type of diagram in which I can see all dependencies between the functions, classes and files of my Python program (multiple files). It's for cleaning purposes.

So my question is: Which diagram should I use? I though about Class Diagram, but there are no dependencies between functions (which function uses which function, which class or file uses functions from which class or file, etc.).

答:
I once participated in a Python project in which we had to employ some pretty long and confusing data processing steps. In order to maintain the minimal modularity, we developed a system in which data would flow from one class to another through a very long chain. Each chain link would only need to know the calling interface of the the "next" step of the chain. This way we could test the overall process by testing interactions between those adjacent links (classes e/or modules) and at each "link" only the necessary, specific, processing logic. Note that the "long flow" was actually a domain logic/requirement.

In no time this structure led to a very, very unmaintainable code. The problem was that the flow chain was too long, rendering the processing logic impossible to grasp from a higher perspective (i.e. the big picture). Although we could clearly understand the adjacency steps, we could not see how data was being processed/modeled throughout the chain.

We decided then to use an activity diagram, in which we tried mapping the different program flows, decisions, method calls, etcettera. We chose an activity diagram for the fact that it allows you to go from in-procedure detail level to class level or communication/interaction levels. We could abstract when we needed to and we could dive deep into algorithm logic when necessary.

We used swim lanes to represent classes/modules, and within them we depicted as much details as necessary of what that class would actually do. The lines flowing from one swim lane to another would allow us to understand how classes actually communicated, and the lines inside the swim lane itself, how that specific class would do it's own job.

In the end it wasn't the most formal Activity Diagram, but it was actually good enough to ensure we could grasp the process from a higher perspective. This allowed us to comprehend better how our system interacted and to improve it, specially reducing the chain length.

After refactoring code and cleaning up the chain structure, we actually had to throw away the Diagram, since it was completely different and maintaining it would cause much work without many benefits. We would rather build up a new one whenever we felt the need for it, we used diagrams as a communication tool rather than documentation.

Whether or not that original chain-like design was adequate would be another matter. Anyway, after this experience I think Activity Diagrams are a good place to start if you wan't to have a better view of your system/code for "cleanup" purposes. The main disadvantage is that it is hard to actually have a program structure (hierarchies, relations, etcettera) of your code.

Title: Functional dependencies diagram


问:
Why do many PHP Devs hate using isset() and/or any of PHP's similarly defensive functions like empty()?
Over on stackoverflow, I see this issue crop up all the time:

E_NOTICE ?== E_DEBUG, avoiding isset() and @ with more sophisticated error_handler

How to set PHP not to check undefind index for $_GET when E_NOTICE is on?

How to stop PHP from logging PHP Notice errors

How do I turn off such PHP 5.3 Notices ?

Even Pekka (who offers a lot of solid PHP advice) has bumped against the dreaded E_NOTICE monster and hoped for a better solution than using isset(): isset() and empty() make code ugly

Personally, I use isset() and empty() in many places to manage the flow of my applications.  For example:

```<code>public function do_something($optional_parameter = NULL) {
    if (!empty($optional_parameter)) {
        // do optional stuff with the contents of $optional_parameter
    }
    // do mandatory stuff
}
</code>```

Even a simple snippet like this:

```<code>if (!isset($_REQUEST['form_var'])) {
    // something's missing, do something about it.
}
</code>```

seems very logical to me.  It doesn't look like bloat, it looks like stable code.  But a lot of developers fire up their applications with E_NOTICE's enabled, discover a lot of frustrating "uninitialized array index" notices, and then grimace at the prospect of checking for defined variables and "littering" their code with isset().

I assume other languages handle things differently.  Speaking from experience, JavaScript isn't as polite as PHP.  An undefined variable will typically halt the execution of the script.  Also, (speaking from inexperience) I'm sure languages like C/C++ would simply refuse to compile.

So, are PHP devs just lazy?  (not talking about you, Pekka, I know you were refactoring an old application.)  Or do other languages handle undefined variables more gracefully than requiring the programmer to first check if they are defined?

(I know there are other E_NOTICE messages besides undefined variables, but those seem to be the ones that cause the most chagrin)

Addendum

From the answers so far, I'm not the only one who thinks isset() is not code bloat.  So, I'm wondering now, are there issues with programmers in other languages that echo this one?  Or is this solely a PHP culture issue?

答:
I think the notices on unknown elements are a design mistake in PHP. I'm not sure it's possible to fix the mistake now, but it produces a lot of boilerplate code like if(isset($foo['abc']) && $foo['abc'] == '123') - this code should not have isset, since the intent is to check if there's '123' in certain place of $foo and if there's nothing there it's definitely not '123'. The only reason you have to write twice as much code there is because of this unfortunate design mistake in PHP. And notices are very expensive in PHP, unfortunately, so just disabling them is not an option for the code where performance is a concern.

So yes, it does make the code ugly IMHO and it does annoy me. And it's not because of lack of experience - I use PHP since 1998 and I remember when there was .php3 extension and it meant "it's not PHP 2". Maybe I am lazy :) But laziness - at least certain type of it - is a virtue for a programmer.

On the other hand, valid use of isset and empty - just like ones in the original post - are fine. I just think PHP is over-zealous about warnings in places where isset/empty are not really needed.

ContentLicense: CC BY-SA 2.5


问:
Mutation operator for genetic algorithms for solving traveling salesman problem
I need help help for defining mutation operator for traveling salesman problem.

I'm currently using this now (pseudocode):

```<code>mutate ( strand ):
    for n in random_interval ( min_gene_index, max_gene_index ):
        i := random_interval ( min_gene_index, max_gene_index );
        j := random_interval ( min_gene_index, max_gene_index );
        swap ( strand[i], strand[j] );
</code>```

So when swapping is executed two cities in the route is swapped.
The goal is that it needs to be fast and effective. I don't want it to be a performance hit in the main loop. Can I improve my implementation or is there any other alternative that is better?

答:
Many different mutation (and crossover) operators have been devised for the TSP and each give different results.

You could use domain specific information (heuristic mutation).

E.g. the 2-opt mutation is an often used algorithm.

It usually improves solutions compared to a crossover-only approach (in (2) the 2-opt mutation operator was tested even without crossover with good results).

```<code>      ..                   ..
     /  \                 /  \
    /    \               /    \
  (a)    (c)           (a)    (c)
     \  /               |      |
      \/         =>     |      |
      /\                |      |
     /  \               |      |
  (d)    (b)           (d)    (b)
    \    /               \    /
     \  /                 \  /
      ..                   ..
</code>```

The operator randomly select two edges e.g. (a,b) and (c,d) from the tour and check if:

```<code>distance(a, b) + distance (c, d) > distance(a, d) + distance(c, b)
</code>```

if this is the case the tour is changed by removing (a,b) and (c,d) and replacing them with the edges (a,d) and (c,b).

This is quite lightweight and simple to implement.

References

Parallel Genetic Algorithms Applied to the Traveling Salesman Problem

Schema analysis of the traveling salesman problem using genetic algorithms

Body:
Many different mutation (and crossover) operators have been devised for the TSP and each give different results.

You could use domain specific information (heuristic mutation).

E.g. the 2-opt mutation is an often used algorithm.

It usually improves solutions compared to a crossover-only approach (in (2) the 2-opt mutation operator was tested even without crossover with good results).

      ..                   ..
     /  \                 /  \
    /    \               /    \
  (a)    (c)           (a)    (c)
     \  /               |      |
      \/         =>     |      |
      /\                |      |
     /  \               |      |
  (d)    (b)           (d)    (b)
    \    /               \    /
     \  /                 \  /
      ..                   ..

The operator randomly select two edges e.g. (a,b) and (c,d) from the tour and check if:

distance(a, b) + distance (c, d) > distance(a, d) + distance(c, b)

if this is the case the tour is changed by removing (a,b) and (c,d) and replacing them with the edges (a,d) and (c,b).

This is quite lightweight and simple to implement.

References

Parallel Genetic Algorithms Applied to the Traveling Salesman Problem

Schema analysis of the traveling salesman problem using genetic algorithms


问:
Can one deny specific parties the right to use and modify otherwise open source software?
I have an open source project that has the attention of some peers, and several of them are eager to contribute. There is one amongst them, however, who I wish (largely for comedic purposes; it's a long story) to keep from contributing.

Is it valid to put in the license a clause to the effect of "Anyone is free to modify this software, except for Andrew?"

答:
Not if you want to call it open source. Most definitions of open source include some variant of (OSI wording here):

The license must not discriminate against any person or group of persons.

Consider whether your little in joke can be honored without legal headaches for all users, for example by stating you won't merge your peer's contributions into the "official" repository.