答:
As you mentioned, there is no one rating for Developers' skills. What comes near to that are certifications - I' a Java-Guy and there are some certifactions available at different levels. However, all good Companies and Developer now, that such certificates does not mean much, because even bad developers pass the tests.

But that led me to a good point: programmer vs. developer. While the first rather cares about the doing and making code work, the latter more care about how to create working software.

Once you've learned the basics of the language and got a confident feeling with the syntax and libraries, you should learn how to code clean, write unit tests, use tools like issue tracker, wikis, source code management (e.g. git). Not for the sake of the tool, but this is how to work professionally. And it is fun, too, to mark an issue resolved or a feature implemented.

However, if you are not that confident with your programming skills, you could do dojos or katas or how they are named (small exercises with a defined goal you could repeat several times, throw the output away, and try a different approach next time).

Title: Evaluate one's skill and improve it?


问:
Describe the best deployment environment you've worked with
The Joel Test includes the question:

Can you make a build in one step?

Which is important, but I'm wondering, how streamlined have some of the deployment processes been?

All software from shrink-wrap to web applies: what's the best deployment environment you've worked with, and what steps were involved?

答:
It's the environment I have set up in my company, and am working with right now.

Description of the environment

We are a team of 4 developpers, working on a Java desktop project. The source code is under Mercurial, with the main repo hosted on our development server. We mostly use TortoiseHg to work with Mercurial. The projects that we open sourced are on BitBucket. The project is built with Maven. The IDE we use is Netbeans, which works impressively well with Maven (it works ok with Mercurial, too).

Our dev server runs Archiva, which is a proxy Maven repository. We use maven to build the project, but we use it also to execute it (mvn exec), to deploy the generated artifacts to Archiva (mvn release), and to generate an assembly from the artifacts hosted by Archiva (mvn assembly).

We have a Redmine bugtracker too, and it is aware of the Mercurial repos. We use a RSS client to be informed of the project activity (from Redmine and Mercurial). We also have a Jabber server to send messages and files to each other.

We set up an Hudson server (continuous integration) and a Sonar server (code metrics). But in practice we don't really use it.

We have the choice of using Windows or Linux

Steps to make a release

Example to release a version 1.1.3

```<code># tags the VCS, updates all the version numbers in the maven config file
mvn --batch-mode release:prepare -DreleaseVersion=1.1.3 -DdevelopmentVersion=1.1.4-SNAPSHOT
# performs a clean build, runs all tests, deploys to the server
mvn release:perform
# creates a unique jar (the final product) from the previously deployed artifacts (no recomilation involved)
<update the version number in a config file to 1.1.3>
mvn assembly:assembly
</code>```

ContentLicense: CC BY-SA 2.5

Body:
It's the environment I have set up in my company, and am working with right now.

Description of the environment

We are a team of 4 developpers, working on a Java desktop project. The source code is under Mercurial, with the main repo hosted on our development server. We mostly use TortoiseHg to work with Mercurial. The projects that we open sourced are on BitBucket. The project is built with Maven. The IDE we use is Netbeans, which works impressively well with Maven (it works ok with Mercurial, too).

Our dev server runs Archiva, which is a proxy Maven repository. We use maven to build the project, but we use it also to execute it (mvn exec), to deploy the generated artifacts to Archiva (mvn release), and to generate an assembly from the artifacts hosted by Archiva (mvn assembly).

We have a Redmine bugtracker too, and it is aware of the Mercurial repos. We use a RSS client to be informed of the project activity (from Redmine and Mercurial). We also have a Jabber server to send messages and files to each other.

We set up an Hudson server (continuous integration) and a Sonar server (code metrics). But in practice we don't really use it.

We have the choice of using Windows or Linux

Steps to make a release

Example to release a version 1.1.3

# tags the VCS, updates all the version numbers in the maven config file
mvn --batch-mode release:prepare -DreleaseVersion=1.1.3 -DdevelopmentVersion=1.1.4-SNAPSHOT
# performs a clean build, runs all tests, deploys to the server
mvn release:perform
# creates a unique jar (the final product) from the previously deployed artifacts (no recomilation involved)
<update the version number in a config file to 1.1.3>
mvn assembly:assembly


问:
Char and unsigned char
Where is unsigned char used in C ( please tell about some real-world examples )? Why would we need both char and unsigned char?

Char ranges from -127 to 128 ( 8-bit integer )
Unsigned Char ranges from 0 to 255 ( 8-bit integer )

If the purpose is to store ASCII, why would we need both?

Another question.
Consider this:

```<code>char a = 127;
unsigned char b = 255;
</code>```

When I print it using std::cout. It gives me different characters. Can you explain why?
( I'm using Microsoft vs11 compiler )

答: unsigned char stores a number. You can use it when you need to represent numbers in the range 0 to 255 and want to conserve memory.

ContentLicense: CC BY-SA 3.0

Title: Char and unsigned char


问:
Property proper naming to represent string starting with number
Looking at some camera metadata on Windows File Properties there are (along with a few more) two Properties named Focal length and 35mm focal length.

I'm developing software that will make use of these two Properties. So far I have created a Property named FocalLength for the first, but I cannot seem to find a proper name for the other one.

I have thought of _35MmFocalLength or ThirtyFiveMmFocalLength, but I think there might be a better suggestion.

Any ideas?

答:
Well, (in my opinion) you're tripping over two basic programming naming conventions:

You shouldn't start variable names with numbers, and my opinion on this is that variable names shouldn't have numbers at all.

The _variable name should be reserved for private variables.

There are many many, MANY standards. If you're using Visual Studio you should consider using the StyleCop Addon.  It will keep you straight for code quality and conventions.

As for the name of your variable, I suggest FocalLengthThirtyFiveMillimeter

I don't like using abberviations in my variable names but that's personal.


答:
Following two suggestions:

Swap names and use FocalLength35Millimeter (Note of not using the
abbreviation, to allow better readability)

Be more techy and use
EquivalentTo35MmFocalLength

Title: Property proper naming to represent string starting with number

Body:
Looking at some camera metadata on Windows File Properties there are (along with a few more) two Properties named Focal length and 35mm focal length.

I'm developing software that will make use of these two Properties. So far I have created a Property named FocalLength for the first, but I cannot seem to find a proper name for the other one.

I have thought of _35MmFocalLength or ThirtyFiveMmFocalLength, but I think there might be a better suggestion.

Any ideas?


问:
Passing an object between different handlers or a Superclass that contains most of the logic
I'm going to try to make this as concise and concrete as possible, but apologies since I can think of multiple ways to make it work.  This question might also relate to handling production workflows or manufacturing, but I have no experience in these areas.

I have a problem where I need to move an Object, O, from different states to other states (like a Nondeterministic finite automata). The problem is the Object can be in different states at the same time, and the interaction sometimes matters.

For example say there are 10 states, O can be in up to 3 of those states at the same time. I'm a bit lost as to what type of code design I should use to model this.  The two ideas I am thinking about are

Pass O from handler to handler, and manage the transitions between states, and keep some sort of info in O saying which states they are in, so that each state can figure out what to do based on what other states O is in.

Have a larger Superclass that handles which states O is in, and handles the interactions.

I'd normally say 1. but handling all the interactions between handlers in each handler sounds messy.

What would be the better option between these 2? Or is there another method that is preferred?

** Update and Clarification **

As a concrete example. The Object can be in one of many physical locations, while it can also be in one of several stages of processing (The object might move back and forth between locations, or back and forth between the stages of processing). As additional complexity each physical location might have sublocations, but I think I can ignore that for now.  So if it's clearer, it can be considered to be two independent automata, but choosing the edge to move to the next state in either automata depends on it's state from both automata.

答:
What I understand from your example is that your object can be represented by two parallel state-machines (location and stage), and you need to synchronize those automata.

You could take inspiration from Statecharts, for example, which allow hierarchical state-machines with communication across states, among other things, but this is likely to be overkill for your usage.

Personally, I would try to use something like Petri-nets. Basically, you can model fork/join ("rendez-vous") transitions easily between separate subgraphs. Read for example The application of petri-nets to workflow management or this paper (which is about another topic but has nice explanations).

Then, your would fork your initial state into different parallel paths (location, stage, ..) where each "token" would represent the current state of the object for the different variables. Some or all of those tokens will then be used jointly to trigger specific transitions.


答:
You forgot to mention signed char, which also exists and is a distinct from char.

char has the same range as either signed char or unsigned char and its intended use if for character data (although you can only use narrow encodings, like ASCII, if you want the correspondence of 1 char == 1 character).

Despite the use of char in their names, both signed char and unsigned char are not targeted for character data, but rather to hold small numbers. unsigned char in particular is often used to store raw byte data.

Title: Char and unsigned char

Body:
Where is unsigned char used in C ( please tell about some real-world examples )? Why would we need both char and unsigned char?

Char ranges from -127 to 128 ( 8-bit integer )
Unsigned Char ranges from 0 to 255 ( 8-bit integer )

If the purpose is to store ASCII, why would we need both?

Another question.
Consider this:

```<code>char a = 127;
unsigned char b = 255;
</code>```

When I print it using std::cout. It gives me different characters. Can you explain why?
( I'm using Microsoft vs11 compiler )


问:
Is it still worth learning desktop gui development?
For the last couple of years, all of the serious projects I have worked on have been either web based, or had a non graphical user interface (services, command line scripts etc...).  I can throw together a WinForms app or do some simple WPF when needed, but I've never really delved into some of the lower level API's like MFC or QT.

I understand that this depends on the situation but in general is it still worth taking the time to learn desktop development well or are applications moving to the web and mobile devices at a pace which makes this knowledge less relevant?  Also, do you expect developers you work with to have desktop gui expertise?

答:
Hmm, besides GMail, Stack-Exchange and my bank's home banking, I use all the day non-web software. Now with the advent of smartphones and tablets, web application are even less attractive to me (I use my smartphone Facebook client). That's user-side.

Developer-side: in my last 10 years, I worked almost only on non-web software (and my career spanned many very different domains as I worked as a software consultant) and I don't see any future web trend in my job.

So yes, it is still a must learning desktop GUI environments.


问:
Why is Feature Driven Development considered an Agile methodology?
In several places Feature Driven Development (FDD) is called an Agile methodogoly - e.g. the Wikipedia entry on FDD.

Yet in general, to be considered FDD it seems the following requirements have to be satisfied:

Coloured UML has to be used (but documentation isn't necessary);

Instead of pair programming  the team is divided by software features;

refactoring is discouraged or, at least, isn't a task with explicit scope;

unit testing is discretionary, the team leaders can decide;

the work flow has to pass through the five FDD phases;

On the flip side it seems to me that Agile is

UML is an optional tool

Tests are documentation

Tests are obligatory

refactoring is a consequence of the change requests of the customer and it isn't discouraged.

Am I wrong with my understanding of either concept?

答:
It's your definition of Agile that's wrong. Agile is valuing

Individuals and interactions over processes and tools

Working software over comprehensive documentation

Customer collaboration over contract negotiation

Responding to change over following a plan

That is, while there is value in the items on the right, we value the items on the left more.

To take your specific points ...

UML is an optional tool

Yes. Most things are when being Agile. Task boards are mandatory in Scrum, which is an Agile methodology, but they're not mandatory to BE Agile.

test is documentation
test is obligatory

This is more a TDD policy. TDD is another Agile methodology, but it is not a mandatory part of being Agile.

refactoring is a consequence of the changes of the customer and it isn't discouraged.

I don't think it's discouraged in FDD either. Nor is it explicitly stated. The Agile Manifesto also doesn't explicitly mention refactoring.

Agile is a set of principles, not a set of methodologies. Agile methodologies are methodologies that encourage those principles.

I don't see any way in which FDD isn't Agile.


问:
Shouldn't Location be a Value Object?
Eric Evan's DDD book, Cargo Shipping Example, pg. 168:

Location

Two places with the same name are not the same. Latitude and longitude
  could provide a unique key, but probably not a very practical one,
  since those measurements are not of interest to most purposes of this
  system and they would be fairly complicated. More likely, the Location
  will be part of a geographical model of some kind that will relate
  places according to shipping lanes and other domain-specific concerns.
  So an arbitrary, internal, automatically generated identifier will
  suffice.

Reason why author made Location an entity is because two different places could have the same name. But since it appears that Location is immutable and thus won't change over time, wouldn't it be better if it was instead a Value Object? Thus:

a) Why couldn't we ( instead of automatically generated identifier ) introduce an additional attribute describing an actual charasteristic of a location, which would help distinguish between the two places with the same name? Then we could make Location a VO.

b) Even if we don't introduce an additional attribute describing an actual characteristic of a location, but instead we use an automatically generated identifier, couldn't we still consider Location as a VO, since the fact still remains that it is immutable and that application would work the same even if it tracked several instances representing the same Location?

c) From the quote it seems that  author would designate Location as an entity even if instead of automatically generated identifier we'd use latitude and longitude to help distinguish between different locations. Why?

Thanks

答:
I believe your fundamental premise regarding location being immutable is wrong and that's what is hanging up your analysis.

Location is anything but immutable except for fixed, historical points in time.  Good design encapsulates the areas that can change, so I can see where location should be its own entity instead of a simple value.

Sticking with the cargo container domain, let's look at some examples to show how location is very much mutable.

Shipper The shipping company will generally have a fixed location over a period of time, but businesses can and do move their location.  The relative size of what they ship presents the largest hurdle here for moving the business.  But a company that deals in small goods with a low inventory can easily hop from one warehouse to the next.

Shipping container By definition of the domain, the shipping container is going to be moving from one location to another.  From the source facility to transit to the receiving company, the container's location is volatile.

Shipped goods present a similar challenge to the container, but the container will likely contain N amount of shipped goods.  While you could assign the container's location to the goods, it makes more sense to indicate the goods are located within a container.  Using a value based mechanism only here will create convoluted code for tracking the location of the goods.

Receiver has similar challenges as the shipping company.  Another consideration is what about tracking goods on a large property?  Large goods stored on tremendously large lots are frequently moved around in order to support incoming and outgoing requests. Likewise, with small goods you may have several categories of small goods located on one shelf.  Using a fixed value, how do you differentiate what goods are on the top shelf versus the bottom shelf?  GPS + altitude are insufficiently precise to specify this sort of a location.  Also note that I've created a de facto entity with my "solution" of combining GPS & altitude.

To summarize:

The chosen location value may be insufficiently precise to identify and isolate two objects in proximity to each other.

Location is mutable, it is going to change over time.

So let's contrast location with an address.

An address is immutable as it belongs to a fixed geographic space and has an implied degree of precision (which may or may not be sufficient).  Address is a property of a section of real estate.  In the extreme and somewhat absurd example of moving a building (think big crane and heavy duty flatbed trailers) to another location, the addresses involved have not changed.  The building does not carry its old address with it to a new real estate site, rather the building is given the address of the new real estate site. Whatever is built at the old real estate site receives the old address for its identification.

Part of the challenge here is the linguistic connotations of address and location.  Many times they can be used synonymously, but in some cases they absolutely cannot.

A house has an address which is also a location that is for most intents and purposes fixed.  You could say "the house's location" and most would infer you meant the address.

An mp3 player has a location which may correspond to an address but there is no implication of being fixed or immutable.  You can pick up an mp3 player and walk next door thereby change the location and therefore address.  You cannot say "the mp3 player's address" as it's just nonsensical due to the implied connotations of the term.

When to use address versus location depends upon the stability of the object you're referring to.  A business generally is described as having an address but in reality it's a location since it can and does change.  Goods and containers have locations as they are prone to moving around.

Title: Shouldn't Location be a Value Object?


问:
Converting an empty string to a number
If you are designing a function which should conver a string to an integer, how would you convert an empty string? The question is only about this one particular input value (empty string).

Between throwing an ExcStringIsEmpty exception and converting to 0 options I prefer the first. It seems more logical to me. Because when you perform an opposite conversion from integer 0 you will hardly convert it to an empty sting but to a string 0 instead.

答:
An empty string doesn't represent any integer, so at face value your question has a trivial answer - do not convert an empty string to a valid integer.

The question behind the question seems to be "how to design a robust non-surprising string-to-int conversion utility".  This is tricky - consider the following additional cases:

What string number representations will you accept?  There is more than decimal - the following strings are also integer number representations in common use: 0x0A, 2x10^2, 10E5, 08,...

Will you consider converting strings representing floating point numbers to integer numbers?

If you answer yes to the previous question, what rounding or truncation will you use?

What about rational numbers?

You can probably come up with a few more if you tried.

So all in all the actual answer to your question should be to use the string-to-number conversion library functions supplied with your current language and framework, if they have any.  If there are no implementations for your situation, then look at other languages or libraries for inspiration of how to handle those cases in your own implementation.
If you document what your conversion function does, then it will not (or at least should not) surprise the clients of your function.

Title: Converting an empty string to a number


答:
If you're converting string to int similar to JavaScript's parseInt function, then you would probably want to have '' return NaN or throw an exception, as you said.

JavaScript returns NaN, but if your language doesn't have that convention or feature you should throw an exception or return a null value.

Title: Converting an empty string to a number

Body:
If you are designing a function which should conver a string to an integer, how would you convert an empty string? The question is only about this one particular input value (empty string).

Between throwing an ExcStringIsEmpty exception and converting to 0 options I prefer the first. It seems more logical to me. Because when you perform an opposite conversion from integer 0 you will hardly convert it to an empty sting but to a string 0 instead.


答:
I'd say yes, it is.  There's sort of a pendulum effect in program development.  First everything ran directly on the computer.  Then when the computer became powerful enough to run multiple programs, they got mainframes with dumb terminals.  But dumb terminals really suck in terms of usability, so as soon as computers got powerful enough to put reasonable amounts of hardware inside a terminal-sized system, we got personal computers, and everything ran directly on the computer.

Then they invented the World Wide Web, and we're back to a mainframe (server) and a dumb terminal (browser.)  But dumb terminals still really suck in terms of usability, and people are starting to relearn the lessons of 30 years ago, and we're trending away from that again.  A lot of the really hot development these days is for desktop (or mobile) apps that run locally, but are able to connect to the Internet for specific purposes to enhance their functionality.

Title: Is it still worth learning desktop gui development?

Body:
For the last couple of years, all of the serious projects I have worked on have been either web based, or had a non graphical user interface (services, command line scripts etc...).  I can throw together a WinForms app or do some simple WPF when needed, but I've never really delved into some of the lower level API's like MFC or QT.

I understand that this depends on the situation but in general is it still worth taking the time to learn desktop development well or are applications moving to the web and mobile devices at a pace which makes this knowledge less relevant?  Also, do you expect developers you work with to have desktop gui expertise?


答:
Maybe this link will explain more of the details. FDD came before the Agile Manifesto, so don't always think you have to practice XP or Scrum to be agile or no one considered the benefits long before.

From your wikipedia link:

"Its main purpose is to deliver tangible, working software repeatedly
  in a timely manner."

Isn't that the whole point of being agile?  Like BDD, FDD isn't appropriate for all projects. You may be the biggest UML hater on the planet, but there could be a project that will be eaiser to manage if you have a few.

Look at the reasons/problems solved by certain methodolgies. What aids you in being agile in one type of project could hold you back in another especially if you think the way to not rely on documentation, contracts, etc. is to exclude them completely.

Title: Why is Feature Driven Development considered an Agile methodology?

Body:
In several places Feature Driven Development (FDD) is called an Agile methodogoly - e.g. the Wikipedia entry on FDD.

Yet in general, to be considered FDD it seems the following requirements have to be satisfied:

Coloured UML has to be used (but documentation isn't necessary);

Instead of pair programming  the team is divided by software features;

refactoring is discouraged or, at least, isn't a task with explicit scope;

unit testing is discretionary, the team leaders can decide;

the work flow has to pass through the five FDD phases;

On the flip side it seems to me that Agile is

UML is an optional tool

Tests are documentation

Tests are obligatory

refactoring is a consequence of the change requests of the customer and it isn't discouraged.

Am I wrong with my understanding of either concept?


问:
Is there some software to manage a XP Project?
I was wondering if there's some software to manage a XP project. I'm starting a school project and I want to follow this methodology, but, we don't have a place to work. Each one works at home (in pairs), therefore I can't follow XP ambient patterns.

So, anyone knows of any software to manage this?

答:
I would recommend https://www.flying-donut.com. It is inspired by scrum and could easily host an XP project. In Flying Donut you are working on iterations and items. Items are then broken down into tasks. A task can be assigned to several people in case of pair programming.

Disclaimer: I have been using it for many months, since I helped building it, and I think it is a great tool.


答:
Considering that 0 has been invented to fill a void in positional representation of numbers,

Considering that most spreadsheet applications interpret an empty cell as a 0 value and that this behaviour is expected by users,

It is not far fetched to convert an empty string to an integer of value 0.

The reverse conversion doesn't need to be symetrical (unless otherwise specified on your project).

Title: Converting an empty string to a number


答:
Well, I am not an FDD expert, but here are my thoughts about the Wikipedia article:

Coloured UML has to be used (but documentation isn't necessary);

The article says you should develop a domain model. That does not mean that UML is required. I guess your team can decide which kind of modeling language is appropriate for the task.

Instead of pair programming the team is divided by software features

Some agile processes require pair programming (XP), others do not, so this does not proof that FDD is not agile.

refactoring is discouraged or, at least, isn't a task with explicit scope;

I don't see it is really discouraged. But I guess you are correct, the part of evolving a software (by applying changes to an existing product) instead of piling new feature over new feature seems to be disregarded in the whole process. That is of course a sign of a non-agile process!

unit testing is discretionary, the team leaders can decide

Sounds like a process which is adapted to the needs of the current project - which is definitely agile.

the work flow has to pass through the five FDD phases

This could be a sign of beeing non-agile.

In summary, I am under the impression that FDD tries to combine some agile things (like iterative development of small features) with some non-agile things (formal process with phases).  Call it semi-agile if you like. Also, note that the same  Wikipedia article calling FDD beeing Agile starts with the disclaimer "This article does not cite any references or sources...".


问:
What are some well known applications written in F#?
As part of a continuing quest for knowledge, I'm spending some time this week learning the basics of F# as an introduction to functional programming. I think I am understanding the construction of software under this model and some of the proposed benefits, but am still a little fuzzy on the real-world use cases.

I was hoping that a F# success stories, or at least a few applications that I'd be familiar with might make it a little clearer about when F# (or any functional programming language) would be appropriate for a project.

So back to the question, what are some well known applications that use F# or a similar functional programming language?

BTW: I am also open to hearing about some lesser-known apps, but if you mention one, please give the basics of what the app is about and why the language used was the appropriate choice.

答: I looked at F# briefly when I wanted to write a SQL parser, which I ended up implementing in Haskell. That said, you could use F# anywhere you would use C#, but would it be worth it? If you'll be doing a lot of functional programming, using F# will be worthwhile, as the syntax for functional constructs is friendlier. If you're doing mostly OO, it's probably better to stick with C#.</p>


答:
Why do you only need one string-to-int method?  Why not three:

```<code>/** Throws exception if string is unparsable */
int strToInt(String s) throws NumberFormatException

/** Returns null if string is unparsable */
Integer strToIntOrNull(String s)

/** zero if string is unparsable */
int strToIntOrZero(String s)
</code>```

Now the client of your code can choose and know what to expect if a corner-case is hit.

Title: Converting an empty string to a number

Body:
Why do you only need one string-to-int method?  Why not three:

/** Throws exception if string is unparsable */
int strToInt(String s) throws NumberFormatException

/** Returns null if string is unparsable */
Integer strToIntOrNull(String s)

/** zero if string is unparsable */
int strToIntOrZero(String s)

Now the client of your code can choose and know what to expect if a corner-case is hit.


答:
Where is unsigned char used in C ( please tell about some real-world examples )?
Why would we need both char and unsigned char?

signed or unsigned are properties of the different C data types (char, short, int, etc...). So it's not a question of whether we need both, both come automatically as part of how C is defined.

Char ranges from -127 to 128 ( 8-bit integer ) Unsigned Char ranges from 0 to 255 ( 8-bit integer )

While that's true for most of the platforms out there, there's nothing garanting that char will be signed. In fact on ARM platforms, it's unsigned. See this fix: http://www.spinics.net/lists/linux-btrfs/msg20653.html as an example of real-world bug introduced by assuming that char is signed.

If the purpose is to store ASCII, why would we need both?

The thing is, the purpose is not to store ASCII. It happens to be used to store ASCII but it's a not a necessity.

char a = 127;

unsigned char b = 255;

When I print it using std::cout. It gives me different characters. Can you explain why? ( I'm using Microsoft vs11 compiler

I think what you're looking for is the following:

```<code>#include <iostream>

int main(void)
{
        char a = -1;
        unsigned char b = 255;
        std::cout << a << std::endl << b << std::endl;
        return 0;
}
</code>```

That is '-1' signed will be equal to '255' unsigned. Please note that this is heavily implementation dependent, and there's nothing that guarantees it will work accross all platforms and compilers.

Title: Char and unsigned char

Body:
Where is unsigned char used in C ( please tell about some real-world examples )?
Why would we need both char and unsigned char?

signed or unsigned are properties of the different C data types (char, short, int, etc...). So it's not a question of whether we need both, both come automatically as part of how C is defined.

Char ranges from -127 to 128 ( 8-bit integer ) Unsigned Char ranges from 0 to 255 ( 8-bit integer )

While that's true for most of the platforms out there, there's nothing garanting that char will be signed. In fact on ARM platforms, it's unsigned. See this fix: http://www.spinics.net/lists/linux-btrfs/msg20653.html as an example of real-world bug introduced by assuming that char is signed.

If the purpose is to store ASCII, why would we need both?

The thing is, the purpose is not to store ASCII. It happens to be used to store ASCII but it's a not a necessity.

char a = 127;

unsigned char b = 255;

When I print it using std::cout. It gives me different characters. Can you explain why? ( I'm using Microsoft vs11 compiler

I think what you're looking for is the following:

#include <iostream>

int main(void)
{
        char a = -1;
        unsigned char b = 255;
        std::cout << a << std::endl << b << std::endl;
        return 0;
}

That is '-1' signed will be equal to '255' unsigned. Please note that this is heavily implementation dependent, and there's nothing that guarantees it will work accross all platforms and compilers.


答:
It's really going to depend on your situation.  I recently worked for a Fortune 500 company who had several projects to convert web applications back into desktop applications (SmartClient/Click-Once).  In their particular circumstances it made a lot of sense and eliminated several usability issues their existing apps suffered from.

If you're a full-time employee and your company doesn't generally design desktop apps then it probably doesn't make any sense to be fully up to speed on Winforms or WPF.  If, however, you're a consultant and you'd like to be able to offer another service to your clients, then it can't possiblly hurt.


问:
Violating the Interface Segregation Principle?
I currently have an interface named InternalEntityIdTransformer, which has a getInternalId method, that given an external id returns the corresponding internal one.

Now I am working on functionality that will need to do the opposite transformation, and go from internal id to external id. Is adding an getExternalId method to this InternalEntityIdTransformer a bad violation of the ISP? (All places that currently are using this interface only need the getInternalId and are not going to care about getExternalId at any point.)

And if it is, then is is particularly harmful? Should I rather have two dedicated interfaces here?

The language used is Java, PHP or C#.

答:
ISP basically says that it's not good to require from a class to implement unrelated things, and/or make a client require unrelated things. Methods in an interface are related — a client may need all of them to complete some reasonable task.

I think getInternalID and getExternalID belong to separate interfaces, since clients wanting one of these don't need the other, per your words.

The class that currently implements InternalEntityIdTransformer could happily implement one more interface, say, ExternalEntityIdTransformer, if sharing of implementation details saves you some work. If at some moment you would need to split the implementations (e.g. external to internal is trivial, but the reverse requires heavy lifting), it will be painless, as it should be.


答:
ISP is an interesting principle because the benefits (or rather the costs of ignoring it) are generally small, but the cost of implementation is also small.

The kind of problem that might occur is if, at some point, you want multiple strategies for getting an internal interface, but only one for getting an external interface (or vice versa).

And you're immediately going to think "no, that's not going to happen," but I'll warn you that I did exactly that very recently and got bitten by it.

I was getting two pieces of data from a web service and thought "well if they change the service, I'm going to have to change both clients. So why worry? An obvious truism, you might imagine.

And then they gave me a CSV file for one half of the data, which was faster and contained more data. I wanted, for a time, to be able to switch between the two, while we made sure the CSV file filled all our needs. But I still wanted to get the other half of the data from the same place.

So, now I really want to break that down into three classes, but to do that was a pain because I only had one interface. The solution is simple enough, but it caused me pain in my unit tests.

I wished I'd followed ISP in that case, even though the cost was fairly low, and kicked myself cause you have to ask ... why didn't I? There is zero cost to having two interfaces to one service class for two different client classes.

Title: Violating the Interface Segregation Principle?

Body:
I currently have an interface named InternalEntityIdTransformer, which has a getInternalId method, that given an external id returns the corresponding internal one.

Now I am working on functionality that will need to do the opposite transformation, and go from internal id to external id. Is adding an getExternalId method to this InternalEntityIdTransformer a bad violation of the ISP? (All places that currently are using this interface only need the getInternalId and are not going to care about getExternalId at any point.)

And if it is, then is is particularly harmful? Should I rather have two dedicated interfaces here?

The language used is Java, PHP or C#.


答:
There's another potential answer here, and I think akalenuk hinted at it. Use a maybe monad or some other similar, option type.

For example C#/.NET has Nullable<T>, which isn't the same but is pretty close, but restricted to Nullable<int> it should be enough.

```<code>public static Nullable<int> toInt(string s)
{
    int i = 0;
    if (int.TryParse(s, out I))
        return new Nullable<int>(i);

    return new Nullable<int>();
}
</code>```

Also remember, that the transformation toInt is not 1 to 1 and invertible. You are transforming from a large set, the set of all possible strings, to the set of all possible integers (bounded by your types... which is relevant, but not that much). So it's not necessary, or even sensible to assume that toString is the inverse of toInt. The case where toInt(s).HasValue == false covers the case (set of all strings) - (set of all number strings)

However, we're not done.

Is this actually the general case? If so then what about number strings for which the value is too large to fit into an integer? Clearly, it's still a number. If it's not the general case then does your use case bound the set of output values within the range of an integer? If so, then you're done.

... if not, then we have to consider whether we need another type (Double? BigInteger?) BigInteger seems like it might fit the general case, still yet bounded by memory (OutOfMemoryException is possible).

In the end, if we're trying to shoot for something as general as possible, I'd go with:

```<code>public static Nullable<BigInteger> toInt(string s)
{
    BigInteger bi = new BigInteger();
    if (BigInteger.TryParse(s, out bi))
        return new Nullable<BigInteger>(bi);

    return new Nullable<BigInteger>();
}
</code>```

Now, for the big sex... let's do it functionally (F# + options):

```<code>let toInt s =
    match BigInteger.TryParse s with
    | (true, parsed) -> Some parsed
    | (false, _) -> None
</code>```

Title: Converting an empty string to a number

Body:
There's another potential answer here, and I think akalenuk hinted at it. Use a maybe monad or some other similar, option type.

For example C#/.NET has Nullable<T>, which isn't the same but is pretty close, but restricted to Nullable<int> it should be enough.

public static Nullable<int> toInt(string s)
{
    int i = 0;
    if (int.TryParse(s, out I))
        return new Nullable<int>(i);

    return new Nullable<int>();
}

Also remember, that the transformation toInt is not 1 to 1 and invertible. You are transforming from a large set, the set of all possible strings, to the set of all possible integers (bounded by your types... which is relevant, but not that much). So it's not necessary, or even sensible to assume that toString is the inverse of toInt. The case where toInt(s).HasValue == false covers the case (set of all strings) - (set of all number strings)

However, we're not done.

Is this actually the general case? If so then what about number strings for which the value is too large to fit into an integer? Clearly, it's still a number. If it's not the general case then does your use case bound the set of output values within the range of an integer? If so, then you're done.

... if not, then we have to consider whether we need another type (Double? BigInteger?) BigInteger seems like it might fit the general case, still yet bounded by memory (OutOfMemoryException is possible).

In the end, if we're trying to shoot for something as general as possible, I'd go with:

public static Nullable<BigInteger> toInt(string s)
{
    BigInteger bi = new BigInteger();
    if (BigInteger.TryParse(s, out bi))
        return new Nullable<BigInteger>(bi);

    return new Nullable<BigInteger>();
}

Now, for the big sex... let's do it functionally (F# + options):

let toInt s =
    match BigInteger.TryParse s with
    | (true, parsed) -> Some parsed
    | (false, _) -> None


问:
New C++11 analogous to python 2 ->3?

I'm a Python2 developer and I just ordered The C++ programming language, 4th edition, from Bjarne Stroustrup's, to learn C++11. But right after I ordered it, I started to wonder if I made a mistake. Are the changes made to C++ in C++11 analogous to how Python moved from 2 to 3 insofar as code significantly breaking and not being backwards compatible? Or is learning C++11 safe to do?

If I coded C++11 in XCode, the latest version being whatever it is, would it work on say a Windows machine? Or does that depend more on what will compile the code, fairly certain that XCode uses LLVM.

答:
There are certain features from C++98/03 that are deprecated, such as auto_ptr, the 'register' keyword, etc. But for the most part if your code compiled under C++98 it will be fine for C++11. The only breaking changes are the new keywords (and the re-using of the auto keyword.) So, unless you wrote C++98 code that used statements like

```<code>auto int x = 5; // auto means "on the stack"
</code>```

or used the keywords 'decltype' or 'nullptr', etc. as variable names, your code should be fine under C++11.

EDIT: As mentioned there are more breaking changes, but they won't trip up the average C++98 code base. I remember hearing a story about how they chose the keyword 'auto' for type deduction (can't vouch for it being true): they did a count of every time the keyword appeared in many large code bases and determined that the C 'auto' keyword went basically unused. Case in point: they take backwards compatibility very seriously.

Title: New C++11 analogous to python 2 ->3?

Body:
There are certain features from C++98/03 that are deprecated, such as auto_ptr, the 'register' keyword, etc. But for the most part if your code compiled under C++98 it will be fine for C++11. The only breaking changes are the new keywords (and the re-using of the auto keyword.) So, unless you wrote C++98 code that used statements like

auto int x = 5; // auto means "on the stack"

or used the keywords 'decltype' or 'nullptr', etc. as variable names, your code should be fine under C++11.

EDIT: As mentioned there are more breaking changes, but they won't trip up the average C++98 code base. I remember hearing a story about how they chose the keyword 'auto' for type deduction (can't vouch for it being true): they did a count of every time the keyword appeared in many large code bases and determined that the C 'auto' keyword went basically unused. Case in point: they take backwards compatibility very seriously.


问:
"Open-source" licenses that explicitly prohibit military applications
I am a researcher, and in my research I do a lot of programming. I am a big fan of the open-source concept - especially in research, where transparency and reproducibility is already a big part of the culture. I gladly contribute as much as I can to the community, and releasing my code for anyone to use is part of that.

However, in research there is always a certain measure of uncertainty about what the stuff you produce will be used for. I fully understand that I can't copyright any results or conclusions - but I can protect how others use my code, and I would like to make sure that there is no (legal) way to incorporate software I produce in military applications.

I've read through a few of the shorter ones of the common OSS licenses, and summaries of some more, but they all seem to focus solely on the questions "do you earn money on my code?" and "do you make my code available with your program?" - nothing about what the program actually does with the code.

Are there any good open-source licenses that explicitly prohibit all kinds of military applications?

Update:

After reading up some more on how OSS works, I've realized that a license that meets my needs by definition will not be open-source, since open-source licenses cannot discriminate against fields. Thus, I'm rather looking for a license that is like an open-source license, except that it prohibits military use. I want this license to be already existing, authored or at least reviewed by someone who actually knows licensing, since I don't.

Also, in response to a couple of remarks that this will be difficult to enforce: yes, I realize that. But this is more for myself than for the legal implications; if I use a license like this, and a military organization uses my code anyway, they are breaking the law and they are doing it despite my explicit instructions not to. Thus, the potentially gruesome things that they do with applications that include software I've written are no longer "on my conciousness", since they stole the software from me. (And somewhere I have a naïve hope that if they need something I've done, and my license prohibits them from using it legally, they'll get someone elses program that does the same thing and allows them to use it. Not that governments always do, but they always should abide by the law...)

It's a moral safeguard, so to speak, rather than something I actually expect to bring up in court (if my mediocre code is ever used by CIA...)

答:
I can't think of an example that has been tested in any court. The JSON license does state something that may be close to what you're looking for. Note that it's not considered open source because of that:

The Software shall be used for Good, not Evil.

There's nothing preventing you from adding your own statement to and MIT license, for example.


问:
How to outsource the UI of a dynamic Web application?
I have a web application developed using Spring and Hibernate, which uses a REST API and Javascript to display and update content. The project is nearly completed, but I want to enhance the look and feel. This will include better graphics and some extra behaviour.

I want to outsource this task to a freelancer over the Internet. I don't have experience with outsourcing and don't know how to incorporate an outsider to the project. I mean I'd like to avoid other people to access the back-end source if I can. The only code that i want to be changed runs on the client side.

Is this doable? I thought I can just give the URL to the designer and require them to use "Augmented Browsing" tools, like Greasemonkey or Tampermonkey to work on the UI. Is this something Web designers are accustomed to or willing to do? Or are there any better options to accomplish this?

EDIT:

A basic requirement: There are items on a list which are generated on-the-fly according to JSON data, using handlebars templates. I want these items to be removable, like when the mouse is over these items a button should appear. I also want those items to look better. This will require some Javascript, HTML and CSS integrated into existing code.

答: I'm a freelance graphic designer! I have experience creating UI designs for mobile and web applications. Often, clients give me a mockup of the UI they want or refer me to some other app UI that is similar to their app. Then describes his apps functionality(how the app works!). After providing a screenshot of UI by the designers, client gives feedback! In all cases clients prefer designs in PSD format. There are many famous marketplaces does this kinda outsourcing! I found 99designs.com best for design related works, besides other marketplace like freelancer.com, odesk.com etc are good.</p>


答:
How would one enforce such a license?

Would you prohibit any military use?  If the software checks air pressure in tires, and someone decides to use it on a military Hummer, is that a prohibited use?  Can people in the military industrial complex use it to plan their monthly picnic?

Would it be an acceptable use if the software improved ballistic missile trajectories, and the improved accuracy of the weapon prevented civilians from being killed?  Or would any use in a weapon be prohibited?

These are the kinds of questions you have to ask yourself, if you want to make a software license that satisfies your sensibilities.

Nevertheless, I'd try an keep it simple.  Yahoo's Terms of Use state that their software must not be used

"to operate nuclear facilities, life support or other mission critical applications where human life or property may be at stake."

That's probably as good a clause as any, if you add the word "weapons" to the prohibited list of uses.

Title: "Open-source" licenses that explicitly prohibit military applications

Body:
I am a researcher, and in my research I do a lot of programming. I am a big fan of the open-source concept - especially in research, where transparency and reproducibility is already a big part of the culture. I gladly contribute as much as I can to the community, and releasing my code for anyone to use is part of that.

However, in research there is always a certain measure of uncertainty about what the stuff you produce will be used for. I fully understand that I can't copyright any results or conclusions - but I can protect how others use my code, and I would like to make sure that there is no (legal) way to incorporate software I produce in military applications.

I've read through a few of the shorter ones of the common OSS licenses, and summaries of some more, but they all seem to focus solely on the questions "do you earn money on my code?" and "do you make my code available with your program?" - nothing about what the program actually does with the code.

Are there any good open-source licenses that explicitly prohibit all kinds of military applications?

Update:

After reading up some more on how OSS works, I've realized that a license that meets my needs by definition will not be open-source, since open-source licenses cannot discriminate against fields. Thus, I'm rather looking for a license that is like an open-source license, except that it prohibits military use. I want this license to be already existing, authored or at least reviewed by someone who actually knows licensing, since I don't.

Also, in response to a couple of remarks that this will be difficult to enforce: yes, I realize that. But this is more for myself than for the legal implications; if I use a license like this, and a military organization uses my code anyway, they are breaking the law and they are doing it despite my explicit instructions not to. Thus, the potentially gruesome things that they do with applications that include software I've written are no longer "on my conciousness", since they stole the software from me. (And somewhere I have a naïve hope that if they need something I've done, and my license prohibits them from using it legally, they'll get someone elses program that does the same thing and allows them to use it. Not that governments always do, but they always should abide by the law...)

It's a moral safeguard, so to speak, rather than something I actually expect to bring up in court (if my mediocre code is ever used by CIA...)


答:
There are two aspects to creating a good looking UI, and they need different skill sets.

On the one hand, there is the graphical design. Here an artist creates a design for the website, basically by arranging all the elements in a pleasing manner in a drawing and deciding on supporting artwork like (background) images.
This requires mostly someone with a sense of what your users will appreciate in a website and does not involve any actual programming (although it helps if the artist knows what can be achieved within reason).

On the other hand, there is the actual implementation of the design. This mostly requires someone familiar with HTML/CSS (and perhaps JS) to bring the design to life, but this person does not have to be artistically inclined.
During the implementation, there might be some back-and-forth between the artist and the implementer to create the images(-sections) that the implementer needs, but otherwise the work of the artist is done.

You need to ask yourself, which of these parts you want to outsource and if you want to outsource both, if it should be to one or to multiple parties.

If it is only the artistic side, then you don't need to give them access to your code, but it could help to give the URL so they can get a feeling for how the website operates.

Title: How to outsource the UI of a dynamic Web application?

Body:
I have a web application developed using Spring and Hibernate, which uses a REST API and Javascript to display and update content. The project is nearly completed, but I want to enhance the look and feel. This will include better graphics and some extra behaviour.

I want to outsource this task to a freelancer over the Internet. I don't have experience with outsourcing and don't know how to incorporate an outsider to the project. I mean I'd like to avoid other people to access the back-end source if I can. The only code that i want to be changed runs on the client side.

Is this doable? I thought I can just give the URL to the designer and require them to use "Augmented Browsing" tools, like Greasemonkey or Tampermonkey to work on the UI. Is this something Web designers are accustomed to or willing to do? Or are there any better options to accomplish this?

EDIT:

A basic requirement: There are items on a list which are generated on-the-fly according to JSON data, using handlebars templates. I want these items to be removable, like when the mouse is over these items a button should appear. I also want those items to look better. This will require some Javascript, HTML and CSS integrated into existing code.


问:
ASP.Net or WPF(C#)?
Our team is divided on this and I wanted to get some third-party opinions.

We are building an application and cannot decide if we want to use .Net WPF Desktop Application with a WCF server, or ASP.Net web app using jQuery. I thought I'd ask the question here, with some specs, and see what the pros/cons of using either side would be. I have my own favorite and feel I am biased.

Ideally we want to build the initial release of the software as fast as we can, then slow down and take time to build in the additional features/components we want later on. Above all we want the software to be fast. Users go through records all day long and delays in loading records or refreshing screens kills their productivity.

Application Details:

I'm estimating around 100 different screens for initial version, with plans for a lot of additional screens being added on later after the initial release.

We are looking to use two-way communication for reminder and event systems

Currently has to support around 100 users, although we've been told to allow for growth up to 500 users

We have multiple locations

Items to consider (maybe not initially in some cases but in future releases):

Room for additional components to be added after initial release (there are a lot of of these... perhaps work here than the initial application)

Keyboard navigation

Performance is a must

Production Speed to initial version

Low maintenance overhead

Future support

Softphone/Scanner integration

Our Developers:

We have 1 programmer who has been learning WPF the past few months and was the one who suggested we use WPF for this.

We have a 2nd programmer who is familiar with ASP.Net and who may help with the project in the future, although he will not be working on it much up until the initial release since his time is spent maintaining our current software.

There is me, who has worked with both and am comfortable in either

We have an outside company doing the project management, and they are an ASP.Net company.

We plan on hiring 1-2 others, however we need to know what direction we are going in first

Environment:

General users are on Windows 2003 server with Terminal Services. They connect using WYSE thin-clients over an RDP connection. Admin staff has their own PCs with XP or higher. Users are allowed to specify their own resolution although they are limited to using IE as the web browser.

Other locations connects to our network over a MPLS connection

Based on that, what would you choose and why?

答: It certainly sounds to me like a WPF app, with lot's of user interaction and potentially interacting with hardware.  You can deliver the app via Click-Once so deployment is mostly a non-issue.  Your WPF app can access a WCF service and deliver the data as binary so the performace will be excellent.  I would start reading up on WPF and getting familiar with it as soon as possible.</p>

Title: ASP.Net or WPF(C#)?


问:
Is licensing required for public repositories?
I am planning to start the public repository on github. In this repository I will be sharing code which I will be posting in my blog. I have seen lot of repositories without any license. Is it required to have a license file? Can't I just say "You're free to use this code in whatever way you need"? Please advise</p>

答:
Can't I just say "You're free to use this code in whatever way you need"?

That's a license, and yes, you do need one.  Otherwise, a substantial portion of people who might want to use your code won't use it, because they don't have explicit permission.

Public Domain software has the same problem; there's no statement granting explicit rights to use public domain software, only the assertion that you don't need permission.


答:
I found this explicitly non-military license for an encryption algorithm called OCB.

2.1 License.
  Subject to your compliance with the terms of this license, including the restrictions set forth in Section 2.2, Licensor hereby grants to you a perpetual, worldwide, non-exclusive, non-transferable, non-sublicenseable, no-charge, royalty-free, irrevocable license to practice any invention claimed in the Licensed Patents (i) for any Research Use, (ii) for any Noncommercial Use, and (iii) in any Software Implementation.

2.2 Restrictions

2.2.1 The license above does not apply to and no license is granted for any Military Use of the Licensed Patents.

You ought to be able to modify it to refer to your own code, and be covered the way you want.


问:
Conditional construct for a kleenean data type
I was thinking of an hypothetical programming language with a kleenean data type which would implement Kleene's three-valued logic. To sum up, it's an extension of the boolean data type with the three constants true, false and unknown where unknown means that the value is either true or false, but we don't know which.

The truth tables for a kleenean type are well-known and the logic is quite easy to understand. However, I was wondering how one would design a conditional construct to take in account this unknown value.

A basic if-then-else conditional construct is almost always as follows:

```<code>if (boolean condition) then
    condition is true, do something
else
    condition is false, do some other thing
end
</code>```

However, I have troubles seeing what a kleenean if construct would look like. How could we interpret the unknown constant? Technically speaking, it could satisfy the true condition as well as the false condition since it is one of these two. However, we can't have it match any of those since it could be the other, it is not really true nor false.

Is there a well-known way to implement such a construct?

EDIT: To specify a little bit, I would prefere something different than the way boost::tribool works, or from a simple switch as if was an enum. Answers about quantum superposition and semantics are welcome.

答:
From what you said, unknown represents represents true or false "at the same time". You shouldn't take it as another value, but as something special or exceptional.

If unknown is passed into if it becomes non deterministic which of the two code paths it should take. I think it is best to assume that passing unknown into an if should result in error.

But you should have way to detect if value is properly defined. Something like

```<code>if defined (boolean condition) then
    condition is defined true or false, do something
else
    condition is unknown, do some other thing
end
</code>```

and there should be negated version of this, because you cannot use normal logic to invert the code paths to remove one of the branches for code clarity.

Body:
From what you said, unknown represents represents true or false "at the same time". You shouldn't take it as another value, but as something special or exceptional.

If unknown is passed into if it becomes non deterministic which of the two code paths it should take. I think it is best to assume that passing unknown into an if should result in error.

But you should have way to detect if value is properly defined. Something like

if defined (boolean condition) then
    condition is defined true or false, do something
else
    condition is unknown, do some other thing
end

and there should be negated version of this, because you cannot use normal logic to invert the code paths to remove one of the branches for code clarity.


问:
Algorithm for Cyclical Sequence Alignment
Let's say we have 3 cyclic sequences, each of them of length n and containing every number from the interval 1..n once.

The goal is to align the sequences in order to maximize the number of matches between the sequences. By a match I mean a column that contains 3 identical values. Since the sequences are cyclical, we can move each sequence cyclically by any number of positions (so 1->2->3 may become 2->3->1 and 3->1->2 but not 1->3->2).

Example:

1 5 4 3 2

1 3 2 4 5

2 1 5 4 3

The answer should be 3 and the corresponding alignment is shown below (fives, threes and twos are matched).

1 5 4 3 2

4 5 1 3 2

1 5 4 3 2

A simple quadratic algorithm I came up with is:

for i in 1..n:

    align the sequences so that column (i, i, i) is created

    count the number of matches

    if larger than current maximum, then set new maximum

Unfortunately the sequences may have length 1000000 and thus my approach is not fast enough. I would appreciate I someone could suggest a subquadratic (linear, loglinear?) algorithm for this problem.

答:
First, to simplify the problem, renumber such that the first sequence is 1..n. The problem is then reduced to finding the shift offsets for two sequences such that for as many numbers i as possible both have an i in position i.

Then, create an associative map that maps from pairs of shift offsets to the score. For each number, increase the score for the pair of offsets that would yield a match. Finally, find the highest score in the map.

This runs in expected linear time if you use a hash map.


答:
Technically, you are not obliged to license your code at all: the default situation is that you as the author of the work are the copyright holder, and unless you give permission, nobody has any rights to your code.

Permission can be implied, e.g. if you send someone an e-mail with your code attached, that says, "here, please take this code, install it on your computer and run it", you are implying that you agree with this particular use. Implicit permission can be a lot more subtle though, which is why anyone who has anything at stake will usually avoid using code on an implicit permission - otherwise, there's always a risk of you claiming that you didn't really mean to imply any permission, go to court, and make them fight an expensive lawsuit.

Another problem that often goes hand in hand with the absence of explicit usage terms is unclear authorship. If you want to use copyrighted material, you have to get permission from the author, even if the author is unknown - in other words, if you don't know the author, you can't get permission, so technically you can't use the work.

Because of all this, it's better to make the terms under which you want to grant people permission to copy, use and redistribute your code explicit. This is what a license does: it says "if you want to use this code, you have to agree to these conditions". The remark "You are free to do with this code what you want" is a license, and it's about as permissive as it gets - but it's probably better to stick with an established license, because they have been reviewed by a lot of lawyers, so you can be fairly certain that the legalese actually means what you think it means. Something like an MIT or BSD license is usually appropriate if you want to be very permissive about your licensing.

Title: Is licensing required for public repositories?

Body: I am planning to start the public repository on github. In this repository I will be sharing code which I will be posting in my blog. I have seen lot of repositories without any license. Is it required to have a license file? Can't I just say "You're free to use this code in whatever way you need"? Please advise</p>


问:
How to make support for bindings for a scripting language

Main

I'm making a scripting language using C++. I plan to use it with a simple test game editor. But I have to make a support for bindings to call game engine's nodes' methods to update positions, rotations, etc.

What are the main approaches for this?

The game engine I plan to use also supports lua, so maybe I can also use this fact.

Details

The problem I have faced lies in the fact of how can I call library C++ object methods within a script. English is not my native language and the lack of knowledge in that sphere prevents me from making a good query on the topic. So I don't know what to search. Google shows me information on how to make bindings to some scripting languages not the fundamentals by search phrases like "how to make bindings support to a scripting language", "scripting bindings".

At this time I came up to the following things. I have to inherit all objects that will be used in script from a service class, ex. CLangObject. With its help I can identify the object's type within a C++ library objects' methods. Then I have to define the most general pointer to method types. I have also define a callback service class to pass it to a byte machine when C++ library method returns value. The game engine I want to use has bindning to lua, so maybe I can use its LuaObject and LuaCallback classes. At this time I don't know if this approach will lead to a normal result.

答:
To restate your concern, you have a piece of software, the game engine, that supports a particular scripting language, Lua, but are unsure how to expose, access, and interject game objects and events to Lua, or to do the same with your own custom external driver (a C++ based editor).

The game engine itself probably has a set of methods or decorators for exposing objects and events that would allow for tracking through external sources or programs.  It also probably has it's own specific protocol for manipulation by those external sources.  Without knowing which particular piece of software or engine you are looking at, it is impossible to give specific guidance.

What I can suggest, is review the documentation of that particular engine. Short of that, look at how known things are exposed to the script, and mimic the method by which those things are exposed and acted upon.

For example, Torque3D offers documentation that shows how to expose objects to script (or an external source like a compiled C++ based editor).

http://www.garagegames.com/products/torque-3d/documentation

http://www.garagegames.com/products/torque-3d/documentation/Scripting/Advanced/EngineInterface.html

The second document shows how to create the call-ins, call-outs, exposed types, and limitations to function definition shape within the game engine.

In order for the script or driver/editor to consume and craft those exposed data types, at some level you will need to be able to create types from within the scripting language (or editor) that can be marshaled, or transformed, onto structures that match the format and conventions of the engine, basically a map.  Each language has it's own way of implementing a structures layout, field order, and sizing.  Some follow a particular convention very well, others use their own convention.

The map might be unwieldy or ugly to use in the script, so you may want to create an additional second 'clean' type within the scripting language or driver/editor for normal use, with a 'transform' method to shape the 'easy to use type' into the type that can be marshaled back to the engine.

Lua has their own way of working with other languages, and it's documentation specifically talks about accessing and consuming C based [compiled] software:
http://www.lua.org/pil/26.html (look at section IV)


问:
Is this a Best Practice with Enum in C#
When Enum is used as below, say if we have

```<code>enum Designation
{
    Manager = 0,
    TeamLead = 1,
    Associate = 2
}
</code>```

then write the below code

```<code>if (designation == Designation.TeamLead) //somecode
</code>```

Now if we decide to change the enum element from "TeamLead" to "Lead" then we have to modify the above line of code as well i.e. designation == Designation.TeamLead to designation == Designation.Lead. So what is the best practice.

答:
I will answer, not because I think the other answers are bad, but because I think there is another thing to be said in this case.

We have two questions in one:

About best practice for you Enum

About refactoring an Enum

1)Is this a Best Practice with Enum in C#?

Well, in your case, since you Enum seems to be kind of hierarchic, I would define them as flags, and benefit from that when using and comparing the values.

```<code>[Flags]
enum Designation
{
    None = 0x0,
    TeamLead = 0x1,
    Manager = 0x2,
    Associate = 0x4
}
</code>```

Then you could use a code like this:

```<code>    string CheckAboveManager(Designation designation)
    {
        if (designation >= Designation.Manager)
            return "It's a manager or higher";
        return "Is lower than manager";
    }
</code>```

The other option of using a object-oriented structure will work only if there is specific behavior or structure you want to separate concerns with. If it is a case of just defining a property (that why there are enums!), them I see no need to create inheritance, but if it is the case, use the accepted answer.

2) Now if we decide to change the enum element from "TeamLead" to
  "Lead" then we have to modify the above line of code as well i.e.
  designation == Designation.TeamLead to designation == Designation.Lead

Well, it was already well explained that refactoring is not an issue if you are using VS IDE, you can even use other tools like DevExpress CodeRush! or ReSharper to get an even better (and very safe) result from refactoring.

Title: Is this a Best Practice with Enum in C#

Body:
I will answer, not because I think the other answers are bad, but because I think there is another thing to be said in this case.

We have two questions in one:

About best practice for you Enum

About refactoring an Enum

1)Is this a Best Practice with Enum in C#?

Well, in your case, since you Enum seems to be kind of hierarchic, I would define them as flags, and benefit from that when using and comparing the values.

[Flags]
enum Designation
{
    None = 0x0,
    TeamLead = 0x1,
    Manager = 0x2,
    Associate = 0x4
}

Then you could use a code like this:

    string CheckAboveManager(Designation designation)
    {
        if (designation >= Designation.Manager)
            return "It's a manager or higher";
        return "Is lower than manager";
    }

The other option of using a object-oriented structure will work only if there is specific behavior or structure you want to separate concerns with. If it is a case of just defining a property (that why there are enums!), them I see no need to create inheritance, but if it is the case, use the accepted answer.

2) Now if we decide to change the enum element from "TeamLead" to
  "Lead" then we have to modify the above line of code as well i.e.
  designation == Designation.TeamLead to designation == Designation.Lead

Well, it was already well explained that refactoring is not an issue if you are using VS IDE, you can even use other tools like DevExpress CodeRush! or ReSharper to get an even better (and very safe) result from refactoring.


问:
I use an IDE (Eclipse) to develop software.  Why should I switch to vim or emacs?
My day job is  java/web developer. I have been using eclipse for ~5years. I think its excellent and I also use Webstorm for javascript and html/jsp.

I do on occasion need to ssh into server and mess around with config files; for this I use vi and it pains me. I have to get up a webpage listing the syntax/commands : press escape, then asterix, turn around three times and the text will be entered two lines above your cursor. Its so unintuitive to me, and I imagine anyone who grew up in the late eighties nineties.

Here are the main reasons I think eclipse is brilliant(and I assume other IDE's), and do not switch to emacs and/or vim.

Error highlighting with no need to
recompile project.

Code assist.

Refactoring.

Opening call hiearchy/Opening
declaration.

Fully integrated with source control.

Debugger is included.

availablity of 3rd party plugins - eg
findbugs/checkstyle.

One of the arguments I hear is that with emacs/vim you can create your own plugins - well OK, but you can do that in eclipse too. But you don't need to as everything is already there!  Its like saying buy this half built car, you can build the rest yourself.

Why are people using emacs/vim ? Do people who use it actually work on complex object-oriented projects in large organisations ?

What are the reasons to switch to vim/emacs. How would my productivity increase if I did switch?

答:
Why should I switch to vim or emacs?

Most likely, you shouldn't switch. Vim is an excellent, powerful text-editor, but it isn't a substitute for an IDE, and shouldn't be!  Eclipse is very good at its subset of IDE-specific things, and vim is very good at its subset of text-editing-specific things. Each has its own, different, focus.

I know there are plugins that extends vim's functionality so that it can do many of the same IDE-specific things an IDE can. But it still isn't vim's main strength, and an IDE will almost always be able to do it better. Because that is what they are focused on.

What I do in my daily work is use both Visual Studio and vim for editing C#. It works very well for me, and I would never cut out one of them to rely exclusively on the other.

As far as emacs goes, I am no expert, but I don't think it can compete with Eclipse's IDE features when it comes to Java (please correct me if I'm wrong). If you're developing in lisp, then it certainly can be considered an excellent IDE, but I don't think it has the same support for Java.

So if you want a more powerful text editor to use alongside Eclipse, then I would definitely recommend you learn either vim or emacs. But as a supplement, not as a replacement. It can really pay off in the long run, even though neither of them have a particularly easy learning curve : )

Here is a nice longish read about the strengths of vim. And here's a list of some nice tricks you can do.


答:
Of course it depends on how the function is meant to be used.

These are really two separate (though not independent) design decisions:

What counts as invalid input?

What to do about invalid input?

About that first decision, any of "+3", "03", "0x3", "3.0", "3.", "3e0", "3 ", " 3" could in some domain reasonably be declared a valid or invalid int representation. Likewise, though we don't customarily represent the zero-value with an empty string, it can be a perfectly reasonable choice to declare that this function considers "" a representation of zero.

The second decision is more substantial. A well-written function might promise to handle invalid input with:

a standard way of signaling an error (exception, separate status return)

a standard way of marking the absence of a value (null return, "optional"/"maybe" return type, separate return-presence indicator)

a special "error" int return that is known to be invalid or highly unlikely in the domain the function is dealing with (e.g. -1 or maxint)

a default int return (0)

a well defined best-effort result (converting "123abc" to 123)

an undefined return value (but at least a return value)

completely undefined behaviour (no promises - might corrupt memory or crash)

Throwing an exception is obviously a common choice in the modern world, but depending on how the function will be used, any of those could make sense. If it will be called a jillion times in a super-tight loop across 10k cores (think Google scale), sometimes the right decision is to write other code so it never passes in invalid inputs.

And two or three of those choices make f("") return 0, assuming "" is invalid input in the first place.

I don't think a more concrete answer would truly be more useful here, but just in case that's all you're after: If we know we're designing a function for general use (e.g. in a new language's stdlib), a good rule of thumb is to treat invalid inputs in the highest-level way available, typically exception. But that should be abandoned if it's clearly overkill: e.g. if the rest of the lib only uses exceptions for catastrophic failures, or if catching them is too verbose or slow compared to how often the function will be used. (Think for a moment why Java of all languages avoids throwing exceptions on arithmetic ops.)

Title: Converting an empty string to a number


问:
Functional reactive programming — is Fay expressive enough?
So I'm doing a fairly involved javascript/html client with lots of ajax calls and other involvements of callback-ism. I'm entertaining the thought of using Fay for this purpose. I'm aware of Elm. Tried it and liked the FRP elements. Now I'm looking to know if similar structure is possible in Fay.

Are there any concrete examples of FRP in Fay out there at this point?

Some relevant technologies:

Arrowlets, arrowised FRP in javascript

FlapJax, another javascript alternative

Bacon.js, FRP in javascript

One possible solution, using Bacon. With demo.

答:
At OdHac a couple of people successfully ported a Haskell FRP library to Fay, but I don't think they have released it yet.

Writing an FFI library should be easier, but it depends on the library you are using. Mainly how hard it is to type it. People have experimented with Bacon.js, for instance Bacon-n-fay (This doesn't compile with the latest version of Fay but I'm guessing it would be easy to update it.)

So yes it's doable, and I hope someone will release a package for it soon.


问:
How can a single developer make use of Agile Methods?
I am a freelancer and work as a single developer. In all cases, I am the person wearing different hats. I am the Scrum Master and I am the only person in the development. What I am not is the Product Owner?

Are there any Agile Methods and free tools that a freelancer can make use of?

答:
Regarding tooling, have a look at https://www.flying-donut.com. It is a new online product, and I've used it for my solo projects and team projects with great deal of success. It is inspired by scrum and could easily host any iterative project. In Flying Donut you are working on iterations and items. Items are then broken down into tasks.There is a nice way of organising your backlog and its GUI is clean with quick response times.

Regarding the methodology I think that scrum is suitable to freelancers since the methodology has a clear communication path to the client. And yes you will be the product owner. The product owner is the one that makes sure that the client gets what he wants. And you will be the team that  is delivering functional code. And finally you will be the scrum master to make sure you are on schedule and remove any impediments the team (you) has. It sounds harder that it is. The iterative mode comes to the rescue. If you do weekly or biweekly sprints and have a clear communication path with the client and the client sees what he is getting then you can quickly respond to potential emerging requirements the client never thought of.

Disclaimer: I have been using Flying Donut for many months, since I helped building it.


问:
Passing an object between different handlers or a Superclass that contains most of the logic
I'm going to try to make this as concise and concrete as possible, but apologies since I can think of multiple ways to make it work.  This question might also relate to handling production workflows or manufacturing, but I have no experience in these areas.

I have a problem where I need to move an Object, O, from different states to other states (like a Nondeterministic finite automata). The problem is the Object can be in different states at the same time, and the interaction sometimes matters.

For example say there are 10 states, O can be in up to 3 of those states at the same time. I'm a bit lost as to what type of code design I should use to model this.  The two ideas I am thinking about are

Pass O from handler to handler, and manage the transitions between states, and keep some sort of info in O saying which states they are in, so that each state can figure out what to do based on what other states O is in.

Have a larger Superclass that handles which states O is in, and handles the interactions.

I'd normally say 1. but handling all the interactions between handlers in each handler sounds messy.

What would be the better option between these 2? Or is there another method that is preferred?

** Update and Clarification **

As a concrete example. The Object can be in one of many physical locations, while it can also be in one of several stages of processing (The object might move back and forth between locations, or back and forth between the stages of processing). As additional complexity each physical location might have sublocations, but I think I can ignore that for now.  So if it's clearer, it can be considered to be two independent automata, but choosing the edge to move to the next state in either automata depends on it's state from both automata.

答:
The Object can be in one of many physical locations, while it can also be in one of several stages of processing ...

This got me thinking about the Bridge Pattern. For structure.

(The object might move back and forth between locations, or back and forth between the stages of processing).

This got me thinking about the Visitor Pattern. For behavior.

State

In general an object's state is the sum-total of the current values of all its properties. So I'm assuming location, stage, and object can all have their own self-contained state. Further, the combination of location and stage state for a given object gives us the 10 possible states you refer to.

Code Sketch

Look at the overall class, interface definitions. Don't get hung up on method names and details.

abstract class vis-a-vis interface - use either or both as needed. This is not a discussion of "code to interfaces not implementation"

If these 10 states can be described succinctly perhaps an enum defining them is in order.

If state is as I describe above then object holding location and stage references is notionally the same as an enum, but very fungable.

If concrete location and stage vary then each should have a base.

If and object's location & stage can both vary independently, and object state should change when these do, thus we utilize bridge pattern.

If a location (or stage) changes that new location can/must calculate its own state, and possibly directly affect object's other properties (and/or vice versa!), thus we have the visitor pattern. i.e. concrete location (or stage) driven state change.

Not shown well here, but I'm thinking.. in general return new copies of objects rather than directly changing properties of the current object,location,stage. then you can utilize a "functional" programming style; and can keep the obsolete objects as state history.

```
    public class Object {
        public Location currentLocation;
        public Stage currentProcess;
        // other properties
    }

    public abstract class Location {
        public  DoYourThing();
        public Object myObject;  // this could be handy
        // other properties
    }

    public abstract class Stage {
        public Object myObject;  // this could be handy
        //other properties

        public  DoA();
        public  DoB();
    }

    // Smart enough to calculate Location state relative to concrete Object & Object.currentStage
    public abstract class LocationVisitor {
        public  CalcNewState(Object obj) {
            obj.Location.DoYourThing();
            . . .
        };
    }

    // Smart enough to calculate Stage state relative to concrete Object & Object.currentLocation
    public abstract class StageVisitor {
        // base implementation stuff
        // if certain things must be in a specific order, let's say:

        public  DoStageing(Object obj) {
            obj.currentStage.DoB();
            DoExtraStuffDefinedinVisitor();
            obj.currentStage.DoA();
            // and so on
        }
    }

    public abstract ObjectStateMachine {
        protected Object            theObject;
        protected LocationVisitor   locVisitor;
        protected StageVisitor      stageVisitor;

        // constructors to fix properties above, and/or
        // public properties to set each individually at will
        . . .

        public Object CalcNewState() {
            var locationState   = locVisitor.CalcNewState(theObject);
            var stageState      = stageVisitor.DoStaging(theObject);
            var allEncompassingState = CalcNewState (locationState, stageState);
        }

        public  CalcNewState (locationThing, stageThing) {
            // magic happens...
        }
    }
```

Body:
The Object can be in one of many physical locations, while it can also be in one of several stages of processing ...

This got me thinking about the Bridge Pattern. For structure.

(The object might move back and forth between locations, or back and forth between the stages of processing).

This got me thinking about the Visitor Pattern. For behavior.

State

In general an object's state is the sum-total of the current values of all its properties. So I'm assuming location, stage, and object can all have their own self-contained state. Further, the combination of location and stage state for a given object gives us the 10 possible states you refer to.

Code Sketch

Look at the overall class, interface definitions. Don't get hung up on method names and details.

abstract class vis-a-vis interface - use either or both as needed. This is not a discussion of "code to interfaces not implementation"

If these 10 states can be described succinctly perhaps an enum defining them is in order.

If state is as I describe above then object holding location and stage references is notionally the same as an enum, but very fungable.

If concrete location and stage vary then each should have a base.

If and object's location & stage can both vary independently, and object state should change when these do, thus we utilize bridge pattern.

If a location (or stage) changes that new location can/must calculate its own state, and possibly directly affect object's other properties (and/or vice versa!), thus we have the visitor pattern. i.e. concrete location (or stage) driven state change.

Not shown well here, but I'm thinking.. in general return new copies of objects rather than directly changing properties of the current object,location,stage. then you can utilize a "functional" programming style; and can keep the obsolete objects as state history.

    public class Object {
        public Location currentLocation;
        public Stage currentProcess;
        // other properties
    }

    public abstract class Location {
        public  DoYourThing();
        public Object myObject;  // this could be handy
        // other properties
    }

    public abstract class Stage {
        public Object myObject;  // this could be handy
        //other properties

        public  DoA();
        public  DoB();
    }

    // Smart enough to calculate Location state relative to concrete Object & Object.currentStage
    public abstract class LocationVisitor {
        public  CalcNewState(Object obj) {
            obj.Location.DoYourThing();
            . . .
        };
    }

    // Smart enough to calculate Stage state relative to concrete Object & Object.currentLocation
    public abstract class StageVisitor {
        // base implementation stuff
        // if certain things must be in a specific order, let's say:

        public  DoStageing(Object obj) {
            obj.currentStage.DoB();
            DoExtraStuffDefinedinVisitor();
            obj.currentStage.DoA();
            // and so on
        }
    }

    public abstract ObjectStateMachine {
        protected Object            theObject;
        protected LocationVisitor   locVisitor;
        protected StageVisitor      stageVisitor;

        // constructors to fix properties above, and/or
        // public properties to set each individually at will
        . . .

        public Object CalcNewState() {
            var locationState   = locVisitor.CalcNewState(theObject);
            var stageState      = stageVisitor.DoStaging(theObject);
            var allEncompassingState = CalcNewState (locationState, stageState);
        }

        public  CalcNewState (locationThing, stageThing) {
            // magic happens...
        }
    }


问:
How do I handle 3rd party search result data (via cache)
I have a search function on my site and it is taking data from 6 different 3rd party resources. The problem is, it takes too long requesting the data over and over again on the results page.

I've read for questions like this on SO about session not being a good choice but for me 'memcache' is not an option, because the server doesn't have memcached installed and I have no way to install it now.

Is there any other approach to do this? Storing in the database seem inappropriate because the data depends on the search terms requested.

What I've been thinking is writing a file on the server that would act as a cache for this file but I don't know how I would know when to delete it after.

答:
You can cache the results using the file system to store the data. The Zend Cache system is pretty simple to setup and use.

You will need to convert the search terms used to make the query into a cache key. Pretty much any hashing algorithm would work for this.

```<code>$md5Value = 0;

foreach ($searchTerms as $searchTerm) {
    $md5Value = md5($md5Value.$searchTerm);
}
</code>```

The is a minuscule chance of a hash collision so you may choose to either used longer/strong hashes than md5, or just also store the searchTerms with the search result, and double-check they're the same after retrieving from the cache

```<code>class SearchTerms {
    public $term = array();
}

class SearchResult {
    public $result;
}

class StoredSearch {
    public $searchTerms;//instance of SearchTerms
    public $searchResult; //instance of SearchResult
}
</code>```

i.e. StoredSearch is stored rather than just the search results.

Body:
You can cache the results using the file system to store the data. The Zend Cache system is pretty simple to setup and use.

You will need to convert the search terms used to make the query into a cache key. Pretty much any hashing algorithm would work for this.

$md5Value = 0;

foreach ($searchTerms as $searchTerm) {
    $md5Value = md5($md5Value.$searchTerm);
}

The is a minuscule chance of a hash collision so you may choose to either used longer/strong hashes than md5, or just also store the searchTerms with the search result, and double-check they're the same after retrieving from the cache

class SearchTerms {
    public $term = array();
}

class SearchResult {
    public $result;
}

class StoredSearch {
    public $searchTerms;//instance of SearchTerms
    public $searchResult; //instance of SearchResult
}

i.e. StoredSearch is stored rather than just the search results.


问:
Checklist for coding MVVM web application
We are a small team working on a web application using MVVM design pattern using technologies like .NET, Knockout and HTML. I am trying to come up with a code review checklist for this, so that my team can make use of it while coding as well as while reviewing. I tried to find in google, but no help there.

Can you guys suggest me what I have to look for code review checklist?

答:
Instead of using a checklist I think what you're looking for is a coding standard, something that tells your team what you expect of their code and provide guidelines.

The coding standard could be something as simple as a pattern for variable naming and a convention for how the code should be laid out (for example parenthesis on a line of its own), or it could be something far more in-depth, it entirely depends on your requirements and your teams requirements. If the whole team sticks to this standard it will make the code a lot easier for anyone to pick up, and it will mean there's a guideline to review the code against.

Since the code review is something that the team is going to be doing it's worth getting the team involved in creating the coding standard. If the team is involved in they'll feel a lot happier about sticking to the standard that if they are handed down "rules from above" because it's something that the team has come up with.

Once you have this standard it means that the team can review the code against the standard and highlight any issues in the code.


问:
Is it still worth learning desktop gui development?
For the last couple of years, all of the serious projects I have worked on have been either web based, or had a non graphical user interface (services, command line scripts etc...).  I can throw together a WinForms app or do some simple WPF when needed, but I've never really delved into some of the lower level API's like MFC or QT.

I understand that this depends on the situation but in general is it still worth taking the time to learn desktop development well or are applications moving to the web and mobile devices at a pace which makes this knowledge less relevant?  Also, do you expect developers you work with to have desktop gui expertise?

答:
Of course "it depends" -- but I think your experience is typical.  I have rarely had to create a thick client for any of the applications I have written.  Unless there is a specific reason that the client needs to be running on the desktop (connectivity issues or 3D game, etc) -- I believe that it's easier for the developer and admins to maintain one "instance" of the application.  If they have the skill set to design a web application they should be OK moving into the desktop app realm generally.

Actually I think it's more important that a thick client developer learn web application programming -- the inherit statelessness of HTTP makes it a more difficult application development paradigm to wrap your head around (or at least you have to do a little more thinking than just slapping controls on a panel).

Don't forget -- you have technologies like Silverlight and Adobe Flex/AIR which can straddle the line between desktop/web application.