问:
Taking strong, static typing to an extreme?
It is common in strong, static typing to use different types even for variables with simple, primitive types to ease static analysis and indicate intent to the programmer. A color and a point in 3D space might both be represented by an array of 3 floats, but given different type names. In C, a lot of common types are simply typedef'd ints.

I'm wondering: just how far is it practical to take this? If you're writing a function that takes a float between 0 and 1 (perhaps it represents a probability distribution) do you create a separate type? What about a function that must take a non-zero integer? Would it be reasonable to create a type nonZeroInt, not for the purposes of encapsulation, but simply for type-safety?

You can take this arbitrarily far, encoding all preconditions of functions into the type system. For example, you could define a "primeNumber" type for the input to a function that only takes a prime. A function which must take two integers with no common factors could be changed to take one argument of type "coprimePair."

The two hypothetical functions above would presumably be part of a library that includes functions to generate prime numbers and coprime pairs, and return them with the appropriate type. If I wanted to call a function in that library that requires a prime number, and I didn't get it from the included prime-generating function, I'd have to explicitly cast an int, essentially forcing me do a reality check and ask myself, "Am I certain that this variable will always be prime?"

My specific question is this: How far is this philosophy ever successfully taken in practice? Are there programming languages, or well-respected programming texts, that encourage a philosophy that says: every function that cannot accommodate the entire range of any existing type as its input, and return a meaningful result for all possible inputs, should instead define a new type?

答:
The comments by Jack and tp1 (which should actually been answers) already explain how this is implemented in functional languages.

My answer adds a point about non-functional languages, especially the one quite popular in development industry: C#.

In languages such as C# or Java, it is indeed a current practice to create types when you need to constraint your values a little bit. If the only thing you need is a positive integer, you'll end up with PositiveInt class, but in general, those wrappers will reflect a bit more the business logic (ProductPrice, RebatePercentage, etc.), again with validation inside (a product price should be superior to zero, a rebate percentage don't accept a value superior to 100, etc.)

The benefits and the drawbacks and the risk of going too far with such types was recently discussed here.

Once you have your wrapper, you may start adding logic to it, and especially the validation. Basically, since the wrapper hides the value it wraps, the validation logic will be located in the constructor, and can be as basic as:

```<code>if (value > 100)
{
    throw new ArgumentOutOfRangeException("value", "The allowed range is (0..100].");
}
</code>```

Another possibility provided by C# is to use code contracts, which provides several benefits:

The static checking catches misusing of those wrappers before you hit the error during the runtime,

Code contracts being enforced during runtime as well, you are sure the contract will not be misused even if static checking was disabled (or its warnings were dismissed by the developers),

With invariants checking the wrapped value, there is no way to assign an invalid value (with the limitation that the checks are done when a method starts or ends, and not at every step during the execution of the method),

Visual Studio integration makes the code self-documenting, by providing hints about the contracts to the callers.

Is it successfully taken in practice? Well, there are thousands of methods within the .NET Framework itself which contain code contracts. For business code, it mostly comes to how critical is the code. If the consequences of a failure are expensive, it could be very attractive to use code contracts. On the other hand, code contracts have a substantial cost in terms of developer's time (ensuring all contracts work well on a all but tiny projects requires a lot of time), and may not be a good idea for the projects which don't necessarily need this level of reliability.

This also answers your other question:

I'm wondering: just how far is it practical to take this?

This is a strictness vs. flexibility question.

If you need to develop very fast, and accept the risk of having runtime errors, you'll pick a weakly-typed language. The benefit of writing less code, for example print(123) outweighs the risk of problems which may be more or less difficult to debug, for example 123 + "4" (would it result in 127 or "1234"?)

In this case, types either won't exist or will be managed implicitly by the language/framework. While you could still do range validation (for instance to sanitize user input), it would look weird to do such validation outside the interfaces with the outside world.

If you are working on life-critical software, you'll use formal proof which will take a huge amount of time, but will make sure there are no errors in the code.

In this case, chances are types will have strict validation: range and precision for numeric values, length and allowed characters for strings, etc.

In between, you'll pick the approach which corresponds the most to your needs. For most software, code contracts would be an overkill. But for most software, having basic checking within a type wrapper (such as Percentage) may be a good idea. Without going into extremes (as discussed in the link already provided above) of creating classes for everything, it could be a good compromise to have a few generic types such as Range<T> or LengthLimitedString which are not that difficult to implement in languages such as C# or Java.

Body:
The comments by Jack and tp1 (which should actually been answers) already explain how this is implemented in functional languages.

My answer adds a point about non-functional languages, especially the one quite popular in development industry: C#.

In languages such as C# or Java, it is indeed a current practice to create types when you need to constraint your values a little bit. If the only thing you need is a positive integer, you'll end up with PositiveInt class, but in general, those wrappers will reflect a bit more the business logic (ProductPrice, RebatePercentage, etc.), again with validation inside (a product price should be superior to zero, a rebate percentage don't accept a value superior to 100, etc.)

The benefits and the drawbacks and the risk of going too far with such types was recently discussed here.

Once you have your wrapper, you may start adding logic to it, and especially the validation. Basically, since the wrapper hides the value it wraps, the validation logic will be located in the constructor, and can be as basic as:

if (value > 100)
{
    throw new ArgumentOutOfRangeException("value", "The allowed range is (0..100].");
}

Another possibility provided by C# is to use code contracts, which provides several benefits:

The static checking catches misusing of those wrappers before you hit the error during the runtime,

Code contracts being enforced during runtime as well, you are sure the contract will not be misused even if static checking was disabled (or its warnings were dismissed by the developers),

With invariants checking the wrapped value, there is no way to assign an invalid value (with the limitation that the checks are done when a method starts or ends, and not at every step during the execution of the method),

Visual Studio integration makes the code self-documenting, by providing hints about the contracts to the callers.

Is it successfully taken in practice? Well, there are thousands of methods within the .NET Framework itself which contain code contracts. For business code, it mostly comes to how critical is the code. If the consequences of a failure are expensive, it could be very attractive to use code contracts. On the other hand, code contracts have a substantial cost in terms of developer's time (ensuring all contracts work well on a all but tiny projects requires a lot of time), and may not be a good idea for the projects which don't necessarily need this level of reliability.

This also answers your other question:

I'm wondering: just how far is it practical to take this?

This is a strictness vs. flexibility question.

If you need to develop very fast, and accept the risk of having runtime errors, you'll pick a weakly-typed language. The benefit of writing less code, for example print(123) outweighs the risk of problems which may be more or less difficult to debug, for example 123 + "4" (would it result in 127 or "1234"?)

In this case, types either won't exist or will be managed implicitly by the language/framework. While you could still do range validation (for instance to sanitize user input), it would look weird to do such validation outside the interfaces with the outside world.

If you are working on life-critical software, you'll use formal proof which will take a huge amount of time, but will make sure there are no errors in the code.

In this case, chances are types will have strict validation: range and precision for numeric values, length and allowed characters for strings, etc.

In between, you'll pick the approach which corresponds the most to your needs. For most software, code contracts would be an overkill. But for most software, having basic checking within a type wrapper (such as Percentage) may be a good idea. Without going into extremes (as discussed in the link already provided above) of creating classes for everything, it could be a good compromise to have a few generic types such as Range<T> or LengthLimitedString which are not that difficult to implement in languages such as C# or Java.


问:
Why can't there be any implicit conversions?
As I understand it, implicit conversions can cause errors.

But that doesn't make sense -- shouldn't normal conversions also cause errors, then?

Why not have

```<code>len(100)
</code>```

work by the language interpreting (or compiling) it as

```<code>len(str(100))
</code>```

especially since that's the only way (I know of) for it to work. The language knows what the error is, why not fix it?

For this example I used Python, though I feel that for something this small it's basically universal.

答:
ColdFusion did most of this. It defines a set of rules to handle your implicit conversions, has a single variable type, and there you go.

The result is total anarchy, where adding "4a" to 6 is 6.16667.

Why? Well, because the first of the two variables is a number, so the result will be numeric.
"4a" is parsed as a date, and seen as "4 AM". 4 AM is 4:00/24:00, or 1/6th of a day (0.16667). Add to 6 and you get 6.16667.

Lists have default separator characters of a comma, so if you ever add an item to a list containing a comma, then you just added two items. Also, lists are secretly strings, so they can get parsed as dates if they only contain 1 item.

String comparison checks if both strings can be parsed to dates first. Because there's no date type, it does that. Same thing for numbers and string containing numbers, octal notation, and booleans ("true" and "yes", etc.)

Rather than failing fast and reporting an error, instead ColdFusion will handle datatype conversions for you. And not in a good way.

Of course, you could fix the implicit conversions by calling explicit functions like DateCompare... but then you've lost the "benefits" of implicit conversion.

For ColdFusion, this is a way to help empower developers. Especially when all those developers are used to is HTML (ColdFusion works with tags, it's called CFML, later they added scripting via <cfscript> as well, where you don't need to add tags for everything). And it works well when you just want to get something working. But when you need things to happen in a more precise way, you need a language that refuses to do implicit conversions for anything that looks like it could have have been a mistake.

ContentLicense: CC BY-SA 3.0


问:
Save flags in an int32
Unity3d PlayerPrefs only allow saving certain types - string, float, and int32. Since int is composed of 32 bits, it should be able to store 32 flags or a bool[] of length 32.

So far, I've thought about setting the int based on a binary number of 32 digits, where each digit represents a flag. I'm having trouble doing this with consideration of negative numbers.

Is there a way to access each individual bit of the int without recursive math to store and use them as flags?

答:
Here is what I came up with:

The Flags attribute way consisted of several tricky pitfalls. For example, bit shifts on signed ints are arithmetic so the sign bit can't be easily used. Also, reconstructing the array of flags from a bitmask can get really mess, as blorgbeard mentioned.

Instead, I used the System.BitArray class which which is easily accessible with indexes. BitArray allows for easy serialization and deserialization to and from an int. BitArray offers a CopyTo() method to copy its bits to a byte array which can then be converted to an int with BitConverter.ToInt32(). To reconstruct the BitArray, a constructor can be used that takes a byte array generated from BitConverter.GetBytes().

I.e.

```<code>//Serializing 32 flags into int
BitArray bitArray = new BitArray (32);
byte[] byteBuffer = new byte[4];
bitArray.Copyto (byteBuffer, 0);
int SerializedFlags = BitConverter.ToInt32 (byteBuffer, 0);

//Reconstructing 32 flags from int
byteBuffer = BitConverter.GetBytes(SerializedFlags);
bitArray = new BitArray (byteBuffer);
</code>```

Title: Save flags in an int32

Body:
Here is what I came up with:

The Flags attribute way consisted of several tricky pitfalls. For example, bit shifts on signed ints are arithmetic so the sign bit can't be easily used. Also, reconstructing the array of flags from a bitmask can get really mess, as blorgbeard mentioned.

Instead, I used the System.BitArray class which which is easily accessible with indexes. BitArray allows for easy serialization and deserialization to and from an int. BitArray offers a CopyTo() method to copy its bits to a byte array which can then be converted to an int with BitConverter.ToInt32(). To reconstruct the BitArray, a constructor can be used that takes a byte array generated from BitConverter.GetBytes().

I.e.

//Serializing 32 flags into int
BitArray bitArray = new BitArray (32);
byte[] byteBuffer = new byte[4];
bitArray.Copyto (byteBuffer, 0);
int SerializedFlags = BitConverter.ToInt32 (byteBuffer, 0);

//Reconstructing 32 flags from int
byteBuffer = BitConverter.GetBytes(SerializedFlags);
bitArray = new BitArray (byteBuffer);


问:
Libraries and licenses
Before I started making software for a company which requires its software to be closed-source everything was easy, but now I'm drowning in license issues and I have no idea what to do.

I have found several great libraries for TLS and other crypto but all (obviously) have licenses. I am talking about the following licenses:

GNU General Public license, version 2 for Mbed TLS

Apache license, version 2

Microsoft Limited Permissive License (Ms_LPL) for CLR Security

Adaptation of MIT X11 License for Bouncy Castle

I know GNU GPL can only be used if my project is open source, but is it OK to have an example project which we can provide when asked for, which is similar to the code we use on our embedded devices but is just a much simpler version. or do we actually need to provide the entire source code of what is currently running on the device.

Because it is impossible to have the crypto bit open source and the rest of our source code closed source under this license right?

I believe the Apache License would allow us to use the library in closed source projects without problems and only needs a copy of that license when we distribute it, am I correct?

Ms-LPL, for as far as I can see, allows the use and adaptation of the code without restrictions, one can also keep it closed source. but would need to add a copy of the license, same goes for the bouncy castle license if i'm not mistaking?

In all cases there are part of our source code we do not want to give to anyone. The products in which the code is used are being sold. In some cases we might change the code a bit (especially in the case of mbedTLS).

It would be great if someone could help me understand these licenses and could tell me if I'm right about these licenses. And perhaps recommend the license which would be the least problematic (e.g. needing to provide as little paperwork as possible).

答:
I have no idea what to do.

Ask your company's legal department. It's their job, not yours. And, unlike you, they do know what they are doing.

Title: Libraries and licenses


问:
Handling my antiquated coworker
I'm a fairly young programmer, and I work at a medium sized company's IT department. I have a coworker, and he is a really good Visual Basic 6 programmer. And I mean really good. Honestly. He can deliver working applications, containing very few bugs, in the time I need to get my first cup of coffee, and boot my machine. He is just that good.

Thing is, we are working with a team, and his working style is completely antiquated. He doesn't believe in versioning software (if you just make sure your code is correct, you don't need all that nonsense). Doesn't believe in deployment (I can deliver a working executable. How that is deployed is for the sysadmins to figure out). Doesn't believe in abstraction. ('if you want to create a subroutine, go ahead, but don't call any subroutines from that subroutine. It gets messy that way, and the code is hard to follow. This way every one can follow every step on the way.' or 'yeah, sure you can use that library to do that for you, but that way you don't really understand what's going on') and certainly doesn't believe in OOP. (we work in VB.net)

He is so good in what he does, he can deliver applications way faster than I can. But it just doesn't work in a team. Our other team member is quiet, and doesn't like to speak out, though he tends to agree. Our manager thinks I make valid points, but is not a programmer.

I have a really hard time maintaining programs he has written, and it doesn't make for a good team atmosphere. What do you think is the best thing for me to do?

答:
Challenge him (in a good way) to prove you otherwise, show him the cool side of the tools and practices. Don't patronize.

For example, perhaps he doesn't believe in versioning as an aid, but show him how branching/merging and how he can work on several experimental features without needing to have a bloat of files.

Regarding OOP, show him some cool/complex design patterns, such as the command pattern, the task pattern and how it can save him valuable time, and all of your team .

If you don't have him interested in the slightest... he might be a lost case, but then again, you have the tools for your team and you to outperform him. Try to use a repository software that shows/emails commit messages your manager can see, that will bring transparency to your manager and leave your coworker out of the picture (bitbucket.org has free private repositories with unlimited space, if you use mercurial).

In the end, don't try to convince with words but with irrefutable actions, that is the best
way to deal with stubborn people IMHO (reverse psychology works sometimes too, lol).

Title: Handling my antiquated coworker

ContentLicense: CC BY-SA 2.5


答:
Implicit conversions can be a real pain to work with. In PowerShell:

```<code>$a = $(dir *.xml) # typeof a is a list, because there are two XML files in the folder.
$a = $(dir *.xml) # typeof a is a string, because there is one XML file in the folder.
</code>```

Suddenly there is twice as much testing needed and twice as many bugs as there would be without implicit conversion.

Title: Why can't there be any implicit conversions?

Body:
As I understand it, implicit conversions can cause errors.

But that doesn't make sense -- shouldn't normal conversions also cause errors, then?

Why not have

```<code>len(100)
</code>```

work by the language interpreting (or compiling) it as

```<code>len(str(100))
</code>```

especially since that's the only way (I know of) for it to work. The language knows what the error is, why not fix it?

For this example I used Python, though I feel that for something this small it's basically universal.

Body:
Implicit conversions can be a real pain to work with. In PowerShell:

$a = $(dir *.xml) # typeof a is a list, because there are two XML files in the folder.
$a = $(dir *.xml) # typeof a is a string, because there is one XML file in the folder.

Suddenly there is twice as much testing needed and twice as many bugs as there would be without implicit conversion.


答:
I know GNU GPL can only be used if my project is opensource

That seems to be a misunderstanding. When you use a GPL library, you only need to open source your own project under GPL again, if

your project links directly to that library (due to this part of the GPL FAQ, the relevant thing is how the communication between your prog and the GPLed code works)

you are going to publish your project outside of your company (internal use does not require you open your sources)

the vendor does not provide a different, alternative license (maybe a commercial one).

So you should first check if these conditions fit to your project, for the specific library you would like to use. And about the other licenses, I think you already found out what you wanted to know.

Title: Libraries and licenses

Body:
Before I started making software for a company which requires its software to be closed-source everything was easy, but now I'm drowning in license issues and I have no idea what to do.

I have found several great libraries for TLS and other crypto but all (obviously) have licenses. I am talking about the following licenses:

GNU General Public license, version 2 for Mbed TLS

Apache license, version 2

Microsoft Limited Permissive License (Ms_LPL) for CLR Security

Adaptation of MIT X11 License for Bouncy Castle

I know GNU GPL can only be used if my project is open source, but is it OK to have an example project which we can provide when asked for, which is similar to the code we use on our embedded devices but is just a much simpler version. or do we actually need to provide the entire source code of what is currently running on the device.

Because it is impossible to have the crypto bit open source and the rest of our source code closed source under this license right?

I believe the Apache License would allow us to use the library in closed source projects without problems and only needs a copy of that license when we distribute it, am I correct?

Ms-LPL, for as far as I can see, allows the use and adaptation of the code without restrictions, one can also keep it closed source. but would need to add a copy of the license, same goes for the bouncy castle license if i'm not mistaking?

In all cases there are part of our source code we do not want to give to anyone. The products in which the code is used are being sold. In some cases we might change the code a bit (especially in the case of mbedTLS).

It would be great if someone could help me understand these licenses and could tell me if I'm right about these licenses. And perhaps recommend the license which would be the least problematic (e.g. needing to provide as little paperwork as possible).


问:
What are my choices for server side sandboxed scripting?
I'm building a public website where users share data and scripts to run over some data. The scripts are run serverside in some sort of sandbox without other interaction this cycle:
my Perl program reads from a database a User made script, adds the data to be processed into the script ( ie: a JSON document) then calls the interpreter, it returns the response( a JSON document or plain text), i save it to the database with my perl script.
The script should be able to have some access to built in functions added to the scripting language by myself, but nothing more.

So i've stumbled upon node.js as a javascript interpreter, and and hour or so ago with Google's V8(does v8 makes sense for this kind of thing?).
CoffeeScript also came to my mind, since it looks nice and it's still Javascript.

I think javascript is widespread enough and more "sandboxeable" since it doesn't have OS calls or anything remotely insecure ( i think ).

by the way, i'm writing the system on Perl and Php for the front end.

To improve the question:
I'm choosing Javascript because i think is secure and simple enough to implement with node.js, but what other alternatives are for achieving this kind of task?
Lua? Python? I just can't find information on how to run a sandboxed interpreter in a proper way.

答:
Java contains built-in JavaScript interpreter. It is not by default sandboxed, but this can be enabled by:

setting correct class shutter - JavaScript can normally load Java classes. Class shutter is a kind of security manager which decides which classes can be loaded and which can't.

"startup" script - short JavaScript initialization which deletes access points to the outer system: java = undefined;Packages = undefined;org = undefined;

If you do this, scripts running inside should not be able to access outside environment in any way.

It also provides script time-out and instruction count limiting functionality which is useful for sandboxing - you can limit how long or how complex the script is.

I used this in Java 7 which has Rhino JavaScript engine. Java 8 has newer, more modern engine Nashorn - I didn't try it with Nashorn but I expect it should be similar.


答:
Explicit casts are important for they're making your intent clear. First of all using explicit casts tells a story to someone who is reading your code. They reveal that you intentionally did what you did. Moreover the same applies to the compiler. The following is illegal in C# for example

```<code>double d = 3.1415926;
// code elided
int i = d;
</code>```

The cast will make you loose precision, which could easily be a bug. Hence the compiler refuses to compile. By using an explicit cast you are telling the compiler:"Hey, I know what I'm doing." And he will go:"Okay!" And compile.

Body:
Explicit casts are important for they're making your intent clear. First of all using explicit casts tells a story to someone who is reading your code. They reveal that you intentionally did what you did. Moreover the same applies to the compiler. The following is illegal in C# for example

double d = 3.1415926;
// code elided
int i = d;

The cast will make you loose precision, which could easily be a bug. Hence the compiler refuses to compile. By using an explicit cast you are telling the compiler:"Hey, I know what I'm doing." And he will go:"Okay!" And compile.


问:
Similar multidimensional array detection
I'm looking for some sort of algorithm so I can quickly identify similar matrices, the matrices are not stored permanently so I'd need a way of mapping each matrix to an easily stored values, after which I can use the same mapping on future matrices and quickly compare against the calculated values.

The way I'm defining a similar matrix is simply whether or not they are identical when mirrored by vertical line, horizontal line, major diagonal and minor diagonal.

For example

```<code>1 2 3
4 5 6
7 8 9
</code>```

is identified as the same as all the following matrices

```<code>3 2 1
6 5 4
9 8 7
-----
7 8 9
4 5 6
1 2 3
-----
1 4 7
2 5 8
3 6 9
-----
9 6 3
8 5 2
7 4 1
</code>```

I've been stumped on this problem for days now, the matrices aren't stored permanently therefore comparing them directly isn't possible.  Could anyone point me in the right direction?
Thanks

答:
Instead of storing one hash value, store 5 hash values

```<code>M0= 1 2 3
    4 5 6
    7 8 9
</code>```

is identified as the same as all the following matrices

Operations which creates M1 to M4 are written below

```<code>M1= 3 2 1  (vertical mirror  M1:= VM(M0) )
    6 5 4
    9 8 7
-----
M2= 7 8 9 (horizontal mirror M2:= HM(M0) )
    4 5 6
    1 2 3
-----
M3= 1 4 7 (transpose M3= T(M0) )
    2 5 8
    3 6 9
-----
M4=     9 6 3 (M4= VM(T(MO) )
    8 5 2
    7 4 1
</code>```

all your equivalent matrices (total 7 in addition to the original) can be written as combinations of VM(), HM(), and T().

so if you hold 8 hash values for a matrix, you can compare your hash values.

To calculate a hash value of the matrix M0 (numbers are only digits in your case), you can convert it to the string "123456789" and use a hash function.

I hope this helps.

Body:
Instead of storing one hash value, store 5 hash values

M0= 1 2 3
    4 5 6
    7 8 9

is identified as the same as all the following matrices

Operations which creates M1 to M4 are written below

M1= 3 2 1  (vertical mirror  M1:= VM(M0) )
    6 5 4
    9 8 7
-----
M2= 7 8 9 (horizontal mirror M2:= HM(M0) )
    4 5 6
    1 2 3
-----
M3= 1 4 7 (transpose M3= T(M0) )
    2 5 8
    3 6 9
-----
M4=     9 6 3 (M4= VM(T(MO) )
    8 5 2
    7 4 1

all your equivalent matrices (total 7 in addition to the original) can be written as combinations of VM(), HM(), and T().

so if you hold 8 hash values for a matrix, you can compare your hash values.

To calculate a hash value of the matrix M0 (numbers are only digits in your case), you can convert it to the string "123456789" and use a hash function.

I hope this helps.


答:
You can use mathematics to identify similarity. I have assumed each example you have given after the initial matrix for similarity as condition.

For the matrix in your example -

```<code>Let Ux = 1 2 3
         4 5 6
         7 8 9

Let Ix = 0 0 1
         0 1 0
         1 0 0
</code>```

If you perform the matrix multiplication of Ux and Ix you would obtain -

```<code>Ux . Ix = 3 2 1
          6 5 4
          9 8 7
</code>```

Which is condition 1.

If you do

```<code>Ix . Ux = 7 8 9
          4 5 6
          1 2 3
</code>```

Which is condition 2.
So, you could use Ix to identify two conditions of similarity you have defined.

For the condition 3 it is Transpose(Ux).

For the condition 4 it is Trasnpose(Ix . Ux . Ix).

Hope this helps!

Title: Similar multidimensional array detection

Body:
I'm looking for some sort of algorithm so I can quickly identify similar matrices, the matrices are not stored permanently so I'd need a way of mapping each matrix to an easily stored values, after which I can use the same mapping on future matrices and quickly compare against the calculated values.

The way I'm defining a similar matrix is simply whether or not they are identical when mirrored by vertical line, horizontal line, major diagonal and minor diagonal.

For example

```<code>1 2 3
4 5 6
7 8 9
</code>```

is identified as the same as all the following matrices

```<code>3 2 1
6 5 4
9 8 7
-----
7 8 9
4 5 6
1 2 3
-----
1 4 7
2 5 8
3 6 9
-----
9 6 3
8 5 2
7 4 1
</code>```

I've been stumped on this problem for days now, the matrices aren't stored permanently therefore comparing them directly isn't possible.  Could anyone point me in the right direction?
Thanks

Body:
You can use mathematics to identify similarity. I have assumed each example you have given after the initial matrix for similarity as condition.

For the matrix in your example -

Let Ux = 1 2 3
         4 5 6
         7 8 9

Let Ix = 0 0 1
         0 1 0
         1 0 0

If you perform the matrix multiplication of Ux and Ix you would obtain -

Ux . Ix = 3 2 1
          6 5 4
          9 8 7

Which is condition 1.

If you do

Ix . Ux = 7 8 9
          4 5 6
          1 2 3

Which is condition 2.
So, you could use Ix to identify two conditions of similarity you have defined.

For the condition 3 it is Transpose(Ux).

For the condition 4 it is Trasnpose(Ix . Ux . Ix).

Hope this helps!


问:
Key bindings war in my brain
How many key bindings are there in your brain? I personally use Intellij Idea as my primary IDE for development, but sometimes switch to Eclipse and Netbeans a bit, and sometimes I use Jedit,Notepad++, Emacs, Vim.

I am always trying to find a perfect key bindings that I can use crossing all the editors.
What's your idea to solve this problem?

答: According to me, you should know any one editor/IDE fully, and a little bit of everyone of the others. e.g. I know Emacs most than others, Vim a little less than emacs, and knows where to click in visual studio. Each of the editor/ide is created with certain ideas in mind and the default key bindings are the best suited for that idea. So better to learn those than to try changing those. </p>

Title: Key bindings war in my brain


答:
I know GNU GPL can only be used if my project is open source, but is it OK to have an example project which we can provide when asked for, which is similar to the code we use on our embedded devices but is just a much simpler version. or do we actually need to provide the entire source code of what is currently running on the device.

No, it is not acceptable. If you distribute code (either as a binary download or as part of a physical product) that contains code under the GPL license, then you must provide the actual sources from which your program can be recreated.

When writing a closed-source embedded product, libraries under the GPL license are effectively unusable.

To comply with the Apache 2.0 license, you must accompany your product with a document containing the Apache 2.0 license text and a description which part of the software it applies to. This can be a document with all kinds of legal fine-print.

For the MIT license, you just need to keep the existing copyright and permission notices intact in the source code.

For the Ms_LPL license, you must make sure that your device uses a Microsoft Windows operating system and you must keep the existing copyright and permission notices in the source intact.

For choosing which library to use, all can be used in a closed source embedded product (Mbed TLS has a commercial license option available for closed source projects). You should also involve other considerations like

correspondence between the features you need and the features provided

the amount of adaptation needed

support for the library

Title: Libraries and licenses


答:
For what it's worth, len(str(100)), len(chr(100)) and len(hex(100)) are all different. str is not the only way to make it work, since there's more than one different conversion in Python from an integer to a string. One of them of course is the most common, but it doesn't necessarily go without saying that's the one you meant. An implicit conversion literally means, "it goes without saying".

One of the practical problems with implicit conversions is that it isn't always obvious which conversion will be applied where there are several possibilities, and this results in readers making errors interpreting the code because they fail to figure out the correct implicit conversion. Everyone always says that what they intended is the "obvious interpretation". It's obvious to them because it's what they meant. It might not be obvious to someone else.

This is why (most of the time) Python prefers explicit to implicit, it prefers not to risk it. The main case where Python does do type coercion is in arithmetic. It allows 1 + 1.0 because the alternative would be too annoying to live with, but it doesn't allow 1 + "1" because it thinks you should have to specify whether you mean int("1"), float("1"), ord("1"), str(1) + "1", or something else. It also doesn't allow (1,2,3) + [4,5,6], even though it could define rules to choose a result type, just like it defines rules to choose the result type of 1 + 1.0.

Other languages disagree and do have lots of implicit conversions. The more they include, the less obvious they become. Try memorising the rules from the C standard for "integer promotions" and "usual arithmetic conversions" before breakfast!


问:
What is language-agnosticism and why is it called that?
When is something language agnostic? Why is it called that?</p>

答:
Language agnostic refers to aspects of programming that are independent of any specific programming language. At least, that's how I've heard it used for the last thirty years.

The word "agnostic" is derived from the ancient Greek for "don't know". So something which is "language agnostic" doesn't need to know about computer languages; it means the same thing as language independent. Things that would be language agnostic include algorithms, or Agile, or a runtime library with bindings to many languages.

Some Mac OS X features are not language agnostic, because they're really designed to be used from Objective C, can only be used with difficulty from C or C++, and don't even have bindings for many languages.

There can also be a subtext to using "language agnostic" rather than other terms.

In colloquial English, someone who says they're "agnostic" means they are neither religious nor an atheist: they "don't know" about God. This is usually verbal code for "I don't like to talk about religion, so don't try to convert me."

So sometimes when people talk about being "language agnostic", they're trying to stay out of arguments about what computer language is better.

ContentLicense: CC BY-SA 4.0


答:
I used to write real-world software this way in Ada, for military aircraft.  We used separate types not only for ranges, but for units and array indices.  For example, a distance in meters was a different type than a distance in feet.  The index into a 100-element array had a different type than an index into a 10-element array.

First, the good.  Quite a few bugs were indeed caught at compile time.  Runtime bugs were usually caught closer to the source.  For example, an array index out of bounds would be caught at the point the index was first assigned, rather than when you try to dereference it.  Also, there are some speed advantages, because the runtime doesn't have to check things that the type system checked statically.

There were a number of drawbacks as well:

Large volume of compile errors, often with weird messages.  This is the side effect of catching bugs at compile time.  You feel like you're always fighting the compiler.  On the other hand, it often worked the first time when you fixed all the compiler errors.

A ton of type annotations.

Heavy use of generics.  I was some two years into my C++ job when I first had to look up the syntax to create my own templated class.  I did the Ada equivalent every day.

A robust coding standard and peer review process was needed in order to prevent programmers from taking the less safe shortcuts.

It was difficult to get new programmers up to speed who were used to looser types.

For something safety critical, it was definitely worth it.  However, I think I would prefer a language with type inference and strong programmer control over implicits, like Scala, where you could get a lot of the safety with less typing.

Title: Taking strong, static typing to an extreme?

Body:
It is common in strong, static typing to use different types even for variables with simple, primitive types to ease static analysis and indicate intent to the programmer. A color and a point in 3D space might both be represented by an array of 3 floats, but given different type names. In C, a lot of common types are simply typedef'd ints.

I'm wondering: just how far is it practical to take this? If you're writing a function that takes a float between 0 and 1 (perhaps it represents a probability distribution) do you create a separate type? What about a function that must take a non-zero integer? Would it be reasonable to create a type nonZeroInt, not for the purposes of encapsulation, but simply for type-safety?

You can take this arbitrarily far, encoding all preconditions of functions into the type system. For example, you could define a "primeNumber" type for the input to a function that only takes a prime. A function which must take two integers with no common factors could be changed to take one argument of type "coprimePair."

The two hypothetical functions above would presumably be part of a library that includes functions to generate prime numbers and coprime pairs, and return them with the appropriate type. If I wanted to call a function in that library that requires a prime number, and I didn't get it from the included prime-generating function, I'd have to explicitly cast an int, essentially forcing me do a reality check and ask myself, "Am I certain that this variable will always be prime?"

My specific question is this: How far is this philosophy ever successfully taken in practice? Are there programming languages, or well-respected programming texts, that encourage a philosophy that says: every function that cannot accommodate the entire range of any existing type as its input, and return a meaningful result for all possible inputs, should instead define a new type?


问:
Is a class representing a JSON response a DTO, a domain object, or something else?
Consider a restful service in Spring MVC. I am wondering how to package my response classes, i.e. how to name the containing package.

First I thought of them as being domain objects. But they are actually a bit different, because they wrap my true domain objects like this:

```<code>{
    header: {
        // ...
    },
    domainObjectSpecificKey: {
        // domain object properties
    }
}
</code>```

The response class is mapped to the top-level JSON object. So then I thought they may be DTOs actually -- but as far as I understand DTOs are used between application layers, and not for "output" objects to be used between separate applications.

So my questions is: does this kind of object have a special name? If yes, what's that? If not, can we definitely state that it is NOT a DTO or a domain object, i.e. should I name the package differently or can I use the one of that seems better to my liking?

答: I would consider a class representing a JSON response to be a Data Contract. Keeping it separate from your DTOs and Domain Objects also keeps the clients consuming your service decoupled from the rest of your system.</p>


问:
Design patterns for implementing optionally supported features
Here's the original problem. There are two classes: Protocol and, say, ProtocolUser (which actully uses the Protocol class instance). Now, I need to support multiple protocols, whose feature sets only partly intersect, doing similar but not equal things. I grouped the features into several interfaces. That is:

```<code>interface IA {}
interface IB {}
interface IC {}

interface IP {};
class P_AB : IP, IA, IB {}
class P_AC : IP, IA, IC {}
class P_BC : IP, IB,IC {}

class P_User
{
    IP m_p;

    ??? // needs to use m_p via IA, IB or IC, depending on which are supported
}
</code>```

And the most vexed part: the protocols are to be switched on-the-fly. Methods of P_User will have to choose which interfaces to operate on, depending on which will be supported by the call time.

The initial plan was to rely on is & as operators. But it does look suspiciously cumbersome. The only alternative I see is to invent some kind of "CanDoThis / CanDoThat" infrastructure, but that doesn't differ much from a plain is.

Are there any helpful patterns I'm unaware of?

答:
Dependency Inversion should be best fit in your case.

The interfaces should not be defined based on supported capabilities, but on what P_User is expecting from the protocol. Each protocol can then implemented what P_User needs based on it's capabilities.


问:
Multiplicities and ternary relations in UML and ER
With entity–relationship diagrams, there are two conventions of denoting multiplicities, (I) and (II):

Say, a teacher T is giving ‹G› some lectures L. Then we can either write this as

```<code>        1       M
 (I)  T ———‹G›——— L,
</code>```

reading

“Every teacher is giving multiple lectures and every lecture is given by exactly one teacher.”,

or as

```<code>        M       1
(II)  T ———‹G›——— L,
</code>```

reading

“Any teacher participates in multiple giving-relations and any lecture participates in exactly one giving-relation”.

The picture becomes more complicated when we introduce ternary relations, say we want to express that a teacher is giving lectures in a certain room R:

```<code>       1       ?                  M       1
 (I) T ———‹G›——— L    and  (II) T ———‹G›——— L
           |                          |
           | ?                        | MC
           R                          R
</code>```

Whereas I can interpret (II) by reading it as

“Any teacher participates in multiple giving-relations, any lecture participates in exactly one giving-relation, and any room participates in none or multiple giving-relations.”

and everything makes perfect sense, I see no way to interpret or express the situation in the case of (I).

For example, we (still) want to say that

“Every lecture is being given by exactly one teacher in exactly one room.”

So this seems to determine the multiplicity ‘1’ at the teacher (as already put in). But then, from the perspective of the room, the relation would read as

“In every room, there are being given (multiple) lectures by exactly one teacher.”

This is already false, as there might be many teachers giving lectures in a certain room.

As I understand is, interpretation (I) is used in UML class diagrams (and of course, sometimes for ER diagrams) – how is this resolved? What should I fill in for the question marks? Am I reading this stuff incorrectly?

答:
I don't think UML prescribes the exact meaning. My impression is that UML limits itself to defining the possible number of things on each end.

For example, spinning up Sparx EA, I create a new basic UML model and a class diagram. I make a class "teacher" and a class "lecture"  I then draw an "aggregation" relationship from "lecture" to "teacher" such that the empty diamond is at the "teacher" end.

(This seems to be roughly what you have in mind above)

UML (Sparx) then happily allows me to assign multiplicities of "1-*" at each end. What EXACTLY aggregation means is not clarified by UML. I think this sort of lingering "exercise left to the reader" ambiguity is one reason that UML does not attempt to prescribe the behavior of code generators.

Hope this helps...


问:
How to best encapsulate features in code and enabling/disabling them at runtime?
I would like to be able to abstract each feature developed by the team in a way that it can be enabled or disabled at runtime by using a distributed shared configuration system. Features are small and deployed daily.

What practices can I use to maintain the code clean and avoid series of if/else cluttering the code ? The codebase is mostly Python, has anybody ever tried using decorators for this purpose ?

答:
What practices can I use to maintain the code clean and avoid series of if/else cluttering the code

Though your original plan sounds a little bit crazy, if you replace the requirement of "every ticket" by "a lot of different features", then the above questions makes IMHO a lot more sense. To my experience, the key to keep code maintainable when having a lot of different configuration options is

breaking down different features into very small, mostly orthogonal subfeatures.

"Orthogonal" here means that each subfeature is independent from each other. If you let the end user have direct acess to the switch of each subfeature, or if you group subfeatures and let the end user just choose between some complete "subfeature configuration bundles" is up to you, but orthogonality will ensure that the whole thing still keeps beeing testable. For example, if you have 3 customers and 10 different subfeatures, for customer A you enable them all, for customer B you disable them all and for customer C you enable every second feature - this makes 3 bundles, and you can provide a configuration set "config A", "B" or "C" as a group.

And even if there are some dependencies between subfeatures, as long as the dependencies are local and you can express them in terms like "this list of subfeatures is only available when subfeature X is active", such a configuration can still be handled.

This is not theory. I am currently working at a product where at least parts are highly configurable, with hundreds of different options, and it did not become a mess because we strictly focused on orthogonality whereever possible. Or look at the list of configuration options available in a software like the Firefox Internet Browser ("about:config"). Such a degree of configurability is IMHO only possible by paying attention to orthogonality.

However, this kind of design does not automatically emerge from your "tickets". For each ticket (or requirement, or "user story"), you have to think about if and how it makes sense to map it to some configurable feature(s) or subfeature(s). And you also have to make an individual decision how to implement that in code (maybe a conditional is the way to go, maybe by subclassing/polymorphism, maybe by utilizing a decision table) - there is no "one size fits all" solution. That's one of the important parts of software design - breaking down requirements to abstractions in your code.


问:
Non-null alternative to Void (Java unit type)
I have a map-like type SmurfMap<K, V> which in certain contexts I use as a set-like SmurfMap<K, Void>.  Implementation details forbid the values of the map from being null, so I cannot actually use Void as a unit type.  Are there any non-null alternatives to Void in the JCL or Guava?

Types considered and not yet rejected:

new singleton enum Unit

Class<Void>

TypeToken<Void>

Object

EDIT SmurfMap<K, V> does not implement java.util.Map.  The datastructure backing a SmurfMap is terabytes to petabytes in size.

答:
If you don't need the values, don't use a map. Use a Set. It's a collection that contains no duplicate elements (by equals and hashCode) and has O(1) membership checking.

If the code is impossible to structure in a way that uses a set, and it must use a map*, then of these options I'd make a singleton Unit type. I'd pick this because as a map value, it does the best job communicating that the value is unused. A Map<T, Boolean> implies that the boolean-ness of the values matters and should be checked.

* This indicates a pretty nasty code smell, and you should examine your design more.


问:
Should angularjs directive directly interact with services or is it considered an anti-pattern?
Which one is considered better:

having a directive that interacts with services directly

or

having a directive that exposes certain hooks to which controller may bind behaviour (involving services)?

答:
I think the "should a directive interact with a service" question depends on what your service is doing.

I've had directives interact with services that don't do anything with HTTP requests and I think it's a good pattern. Services/Factories are great for encapsulating more data oriented logic, and directives are great for encapsulating presentation oriented logic. The stated purpose of services in the Angular docs are: "You can use services to organize and share code across your app.". That's pretty broad but services can be used to achieve that goal in directives.

That being said, I do understand the desire in some cases to make it so that directives do not directly make any HTTP requests. Again, it depends on the service and how you're organizing your services.


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

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

答:
It's all talk until the code runs.

    — Ward Cunningham

LastEditorDisplayName: Roger Pate


答: Like the other posters have said, choose one of the two great editors - Vim or Emacs. I am a Vim user, and after having learnt to use vim well, I realised that the best way to keep up with this key sequence complexity is to learn to synthesize, and combine existing ones. I also use my muscle memory of vim keyboard shortcuts everywhere - I use vimperator in firefox, and xmonad as my window manager, apart from a host of other settings.</p>

Title: Key bindings war in my brain

Body:
How many key bindings are there in your brain? I personally use Intellij Idea as my primary IDE for development, but sometimes switch to Eclipse and Netbeans a bit, and sometimes I use Jedit,Notepad++, Emacs, Vim.

I am always trying to find a perfect key bindings that I can use crossing all the editors.
What's your idea to solve this problem?


问:
What is the most efficient way to find a set of locations within a radius of a certain point?
Imagine a dataset of all the restaurants in the US (similar to Yelp, etc), how would you return a set of restaurants within a certain range of a particular zip code.  (Assuming you have already a function, distanceBetweenZipCodes, which figures out the distance for you.)

The brute force method would be

```<code>For each restaurant in restaurantsInUSA
  if(distanceBetweenZipCodes(restaurant.zipcode, user.zipcode) < walkingDistance)
    save restaurant
</code>```

However, it seems fairly inefficient to include New York restaurants in the search if the user is in California.  But, it is possible that a restaurant is located close to a state line so segmenting the data by state would be problematic.  You get the same problem if trying to segment by counties, cities or any other administrative boundary.

What would be the most appropriate way to segment the data to avoid having to check each and every record for all searches?

答:
You've discovered the need for spatial indexing.  R-trees are probably the most common approach.  The basic idea is a tree structure with rectangular bounding boxes computed over all the children of a given node.  That way searching for a region or a point can traverse the tree, pruning out any parts of the tree (most of it) where the bounding box is not a match.

This is implemented in various libraries, including SQL databases PostgreSQL and SQLite (with module), and C++ library boost::geometry.


问:
At what point do you drop attribution to original work?
Lets say I have a project which has evolved over the past year. When I began the project, I looked around for open source projects which provided as much of the base system as I could find, and finally settled on an Apache 2.0 Licensed project.

Over the past year, the project has evolved a lot, leaving very little resemblance to the original project. Basically the only similarities left are the project's source directory structure, and ideas left in-tact here and there (very few complete class files are original, most are either totally re-written or mostly due to this project's requirements).

At what point do I stop attributing to the original project? At what point have I diverged so severely as to be safe in saying I own copyright over this entire work as well as licensed under my terms?

答:
Never

As long as the project's code has a direct descendent to an Apache 2.0 License you should never remove attribution.

If you do a greenfield project where every single line is new and not copied over, then you can remove attribution.

There are some things you should never cut corners on, proper procedures around licensing are one of them.


问:
How can I have objects interacting and communicating with each other without forcing a hierarchy?
I hope these ramblings will make my question clear — I'd totally understand if they wont, though, so let me know if that's the case, and I'll try making myself clearer.

Meet BoxPong, a very simple game I made to get acquainted with object-oriented game development. Drag the box to control the ball and collect yellow things.

Making BoxPong helped me formulate, among other things, a fundamental question: how can I have objects that interact with each other without having to "belong" to each other? In other words, is there a way for objects to not be hierarchical, but instead coexist? (I'll go into further detail below.)

I suspect the problem of objects coexisting is a common one, so I hope there's an established way to solve it. I don't want to reinvent the square wheel, so I guess the ideal answer I'm looking for is "here's a design pattern that's commonly used to solve your kind of problem."

Especially in simple games like BoxPong, it's clear that there are, or should be, a handful of objects coexisting on the same level. There's a box, there's a ball, there's a collectible. All I can express in object-oriented languages, though — or so it seems — are strict HAS-A relationships. That's done through member variables. I can't just start off the ball and let it do its thing, I need it to permanently belong to another object. I've set it up so that the main game object has a box, and the box in turn has a ball, and has a score counter. Each object also has an update() method, which calculates position, direction etc., and I go a similar way there: I call the main game object's update method, which calls the update methods of all its children, and they in turn call the update methods of all their children. This is the only way I can see to make an object-oriented game, but I feel it's not the ideal way. After all, I wouldn't exactly think of the ball as belonging to the box, but rather as being on the same level and interacting with it. I suppose that can be achieved by turning all game objects into member variables of the main game object, but I don't see that solving anything. I mean... leaving aside the obvious clutter, how would there be a way for the ball and the box to know each other, that is, to interact?

There's also the issue of objects needing to pass information between each other. I have quite a bit of experience writing code for the SNES, where you have access to practically the entire RAM all the time. Say you're making a custom enemy for Super Mario World, and you want it to remove all of Mario's coins, then just store zero to address $0DBF, no problem. There's no limitations saying enemies can't access the player's status. I guess I've been spoiled by this freedom, because with C++ and the like I often find myself wondering how to make a value accessible to some other objects (or even global).

Using the example of BoxPong, what if I wanted the ball to bounce off the edges of the screen? width and height are properties of the Game class, and I would need the ball to have access to them. I could pass these kinds of values on (either through constructors or the methods where they're needed), but that just screams bad practice to me.

I guess my main problem is that I need objects to know each other, but the only way I can see to do that is strict hierarchy, which is ugly and impractical.

I've heard of "friend classes" on C++ and kinda know how they work, but if they're the end-all solution, then how come I don't see friend keywords poured all over every single C++ project, and how come the concept doesn't exist in every OOP language? (The same goes for function pointers, which I've just recently learned of.)

Thanks in advance for answers of any kind — and again, if there's a part that doesn't make sense to you, do let me know.

答:
In general, it turns out very badly if objects of the same level know about each other. Once objects know about each other they are tied, or coupled to each other. This makes them hard to change, hard to test, hard to maintain.

It works out much better if there is some object "above" that knows about the two and can set the interactions between them. The object that knows about the two peers can tie them together via dependency injection or via events or via message passing (or any other of decoupling mechanisms). Yes, that leads to a bit of an artificial hierarchy, but it's far better than the spaghetti mess that you get when things just interact willy-nilly. That is only more important in C++, since you need something to own the lifetime of the objects too.

So in short, you can do it by just having objects side by side everywhere tied together by ad hoc access, but it's a bad idea. The hierarchy provides order and clear ownership. The main thing to remember is that objects in code are not necessarily objects in real life (or even the game). If the objects in the game don't make a good hierarchy, a different abstraction may be better.


答:
well, the techniques you mention are obviously good, but you also need to ask yourself whether you're pushing them as ideology.  I find that younger programmers do tend to be a bit evangelical about what they picked up in college.  remember that these techniques are good because of outcomes: version control enables concurrent development, clearer tracking of design, development, testing, bugfix  stages.  if your projects really are short-term, a lot of that is simply inappropriate, and will wind up making you less agile.  it's simply not the case that best practice means using every possible best practice.  abstraction, for instance, definitely can be more a liability than an aid, at least some times.  version control makes the most sense when you have extended development timelines, complex code, multiple programmers - there's a sort of synergy, which is hard to get traction with piecemeal.

I think the place to start is keeping an eye out for potential reuse - as projects go by, think about commonalities, or more general frameworks.  trying to get out in front of the projects would be a powerful move, and might let you work in more technique...

Title: Handling my antiquated coworker

Body:
I'm a fairly young programmer, and I work at a medium sized company's IT department. I have a coworker, and he is a really good Visual Basic 6 programmer. And I mean really good. Honestly. He can deliver working applications, containing very few bugs, in the time I need to get my first cup of coffee, and boot my machine. He is just that good.

Thing is, we are working with a team, and his working style is completely antiquated. He doesn't believe in versioning software (if you just make sure your code is correct, you don't need all that nonsense). Doesn't believe in deployment (I can deliver a working executable. How that is deployed is for the sysadmins to figure out). Doesn't believe in abstraction. ('if you want to create a subroutine, go ahead, but don't call any subroutines from that subroutine. It gets messy that way, and the code is hard to follow. This way every one can follow every step on the way.' or 'yeah, sure you can use that library to do that for you, but that way you don't really understand what's going on') and certainly doesn't believe in OOP. (we work in VB.net)

He is so good in what he does, he can deliver applications way faster than I can. But it just doesn't work in a team. Our other team member is quiet, and doesn't like to speak out, though he tends to agree. Our manager thinks I make valid points, but is not a programmer.

I have a really hard time maintaining programs he has written, and it doesn't make for a good team atmosphere. What do you think is the best thing for me to do?


答: Calculate a hash value for each of the eight symmetric matrixes and keep only the smallest of them - that should do the trick. This gives you the same value for each matrix of an equivalence class.</p>


问:
The need for Explicit Type Conversion in C#
Consider the following code:

```<code>DerivedClass drbObj = (DerivedClass)obj;
</code>```

Here obj is of type Object and this is reasonable since Object is the base type of every Class in C#.

Here, since the type of derObj is defined at compile time, what is the need to explicitly use type conversion here. Can't the compiler predict on it's own that it will be of DerivedClass. I understand that, the Conversion type doesn't have to match the Derived type, but for practical purpose, it will only be as useful as the Derived type.

Could someone explain with a small, hypothetical example, as to why the Explicit Type Conversion is necessary when a reference of type Object is being assigned to a derived class.

From what I know, in C, there is no  need to do perform Explicit type conversion from void* to any pointer and the compiler can handle it, based on the type of the pointer to which the converted value is being assigned.

答:
The C# language uses casting syntax to mean a number of different things, depending upon the operand and result types.  The meaning here is "I think the operand is a reference to a thing of type X, and I would like to make it available to something requiring a reference of type X; throw an exception if the thing isn't of the proper type.

When trying to write any sort of sane code, it's important to have at least some kinds of statements which can be guaranteed not to throw any exception unless a thread is rudely aborted.  Given a local variable x of some reference type, it's important that if the evaluation of some expression can be guaranteed not to throw an exception, so can the statement x = expression;.

If x is of a type more derived than y, the expression (typeOfX)y; might throw an exception if y cannot be cast to the type of x, but the statement x = (typeOfX)y; obeys the rule that an assignment to a local variable cannot throw an exception once the evaluation of the right-hand argument is complete.  Since downcasts are a situation where exceptions might get thrown, requiring a programmer to write x = (typeOfX)y; rather than just x = y; makes clear that the statement might throw an exception.


问:
null vs missing key in REST API Response
Say in my application, some users give us their last name, and others do not. In a REST API response, which body is preferred:

With a "null" value:

```<code>{"firstName": "Bob",
 "lastName": null}
</code>```

Or just a missing key:

```<code>{"firstName": "Bob"}
</code>```

答:
Consider removing empty or null values.

If a property is optional or has an empty or null value, consider dropping the property from the JSON, unless there's a strong semantic reason for its existence.

```<code>{
  "volume": 10,

  // Even though the "balance" property's value is zero, it should be left in,
  // since "0" signifies "even balance" (the value could be "-1" for left
  // balance and "+1" for right balance.
  "balance": 0,

  // The "currentlyPlaying" property can be left out since it is null.
  // "currentlyPlaying": null
}
</code>```

Further Reading

Google Style Guide - Empty or Null Property Values

Should null values be included in JSON responses from a REST API?

Body:
Consider removing empty or null values.

If a property is optional or has an empty or null value, consider dropping the property from the JSON, unless there's a strong semantic reason for its existence.

{
  "volume": 10,

  // Even though the "balance" property's value is zero, it should be left in,
  // since "0" signifies "even balance" (the value could be "-1" for left
  // balance and "+1" for right balance.
  "balance": 0,

  // The "currentlyPlaying" property can be left out since it is null.
  // "currentlyPlaying": null
}

Further Reading

Google Style Guide - Empty or Null Property Values

Should null values be included in JSON responses from a REST API?


答:
You have really two options here:

factoring - isolate interfaces of each object and use soft casting (as operator) to determine extended capabilities of the class

optional feature pattern - implement all methods available on all classes in one base class and throw NotSupportedException when the given function is not supported.

Both of those have their pros and cons:
Factoring:

pro: responsibilities/capabilities of your code are well separated

con: the code becomes more complex, and functionality hard to discover

Optional features pattern:

pro: Functionality is easier to discover using tools like Intellisense

con: The base class is bloated with unnecessary functions that might throw

Since you've said that your interfaces should intersect only a little I would go with the factoring approach, it is more suited for such cases. A more realistic example would be needed to give you more detailed answer.

Edit: If some of the interface combinations are expected to be used more than other you might consider combining them in another interface:

```<code>public interface IAB : IA, IB
</code>```

This would of course result in interface explosion if you did it for every possible combination, so use this sparingly only in cases where it really makes sense. It's always easier to add a new interface than to remove one.

Title: Design patterns for implementing optionally supported features

Body:
Here's the original problem. There are two classes: Protocol and, say, ProtocolUser (which actully uses the Protocol class instance). Now, I need to support multiple protocols, whose feature sets only partly intersect, doing similar but not equal things. I grouped the features into several interfaces. That is:

```<code>interface IA {}
interface IB {}
interface IC {}

interface IP {};
class P_AB : IP, IA, IB {}
class P_AC : IP, IA, IC {}
class P_BC : IP, IB,IC {}

class P_User
{
    IP m_p;

    ??? // needs to use m_p via IA, IB or IC, depending on which are supported
}
</code>```

And the most vexed part: the protocols are to be switched on-the-fly. Methods of P_User will have to choose which interfaces to operate on, depending on which will be supported by the call time.

The initial plan was to rely on is & as operators. But it does look suspiciously cumbersome. The only alternative I see is to invent some kind of "CanDoThis / CanDoThat" infrastructure, but that doesn't differ much from a plain is.

Are there any helpful patterns I'm unaware of?

Body:
You have really two options here:

factoring - isolate interfaces of each object and use soft casting (as operator) to determine extended capabilities of the class

optional feature pattern - implement all methods available on all classes in one base class and throw NotSupportedException when the given function is not supported.

Both of those have their pros and cons:
Factoring:

pro: responsibilities/capabilities of your code are well separated

con: the code becomes more complex, and functionality hard to discover

Optional features pattern:

pro: Functionality is easier to discover using tools like Intellisense

con: The base class is bloated with unnecessary functions that might throw

Since you've said that your interfaces should intersect only a little I would go with the factoring approach, it is more suited for such cases. A more realistic example would be needed to give you more detailed answer.

Edit: If some of the interface combinations are expected to be used more than other you might consider combining them in another interface:

public interface IAB : IA, IB

This would of course result in interface explosion if you did it for every possible combination, so use this sparingly only in cases where it really makes sense. It's always easier to add a new interface than to remove one.


答:
Meet BoxPong, a very simple game I made to get acquainted with object-oriented game development.

Making BoxPong helped me formulate, among other things, a fundamental question: how can I have objects that interact with each other without having to "belong" to each other?

I have quite a bit of experience writing code for the SNES, where you have access to practically the entire RAM all the time. Say you're making a custom enemy for Super Mario World, and you want it to remove all of Mario's coins, then just store zero to address $0DBF, no problem.

You appear to be missing the point of object-oriented programming.

Object Oriented Programming is about managing dependencies by selectively inverting certain key dependencies in your architecture so that you can prevent rigidity, fragility, and non-reusability.

What is dependency? Dependency is reliance on something else. When you store zero to address $0DBF, you are relying on the fact that that address is where Mario's coins are located and that the coins are represented as an integer. Your Custom Enemy code is reliant on the code implementing Mario and his coins. If you make a change to where Mario stores his coins in memory, you must manually update all the code referencing the memory location.

Object oriented code is all about making your code depend upon abstractions and not on details. So instead of

```<code>class Mario
{
    public:
        int coins;
}
</code>```

you would write

```<code>class Mario
{
    public:
        void LoseCoins();

    private:
        int coins;
}
</code>```

Now, if you want to change how Mario stores his coins from an int to a long or a double or store it on the network or store it in a database or kick off some other long process, you make the change in one place: the Mario class, and all your other code keeps working with no changes.

Therefore, when you ask

how can I have objects that interact with each other without having to "belong" to each other?

you are really asking:

how can I have code that directly depends on each other without any abstractions?

which is not object oriented programming.

I suggest you begin by reading everything here: http://objectmentor.com/omSolutions/oops_what.html and then search youtube for everything by Robert Martin and watch all of it.

My answers derive from him, and some of it is directly quoted from him.

Title: How can I have objects interacting and communicating with each other without forcing a hierarchy?

Body:
I hope these ramblings will make my question clear — I'd totally understand if they wont, though, so let me know if that's the case, and I'll try making myself clearer.

Meet BoxPong, a very simple game I made to get acquainted with object-oriented game development. Drag the box to control the ball and collect yellow things.

Making BoxPong helped me formulate, among other things, a fundamental question: how can I have objects that interact with each other without having to "belong" to each other? In other words, is there a way for objects to not be hierarchical, but instead coexist? (I'll go into further detail below.)

I suspect the problem of objects coexisting is a common one, so I hope there's an established way to solve it. I don't want to reinvent the square wheel, so I guess the ideal answer I'm looking for is "here's a design pattern that's commonly used to solve your kind of problem."

Especially in simple games like BoxPong, it's clear that there are, or should be, a handful of objects coexisting on the same level. There's a box, there's a ball, there's a collectible. All I can express in object-oriented languages, though — or so it seems — are strict HAS-A relationships. That's done through member variables. I can't just start off the ball and let it do its thing, I need it to permanently belong to another object. I've set it up so that the main game object has a box, and the box in turn has a ball, and has a score counter. Each object also has an update() method, which calculates position, direction etc., and I go a similar way there: I call the main game object's update method, which calls the update methods of all its children, and they in turn call the update methods of all their children. This is the only way I can see to make an object-oriented game, but I feel it's not the ideal way. After all, I wouldn't exactly think of the ball as belonging to the box, but rather as being on the same level and interacting with it. I suppose that can be achieved by turning all game objects into member variables of the main game object, but I don't see that solving anything. I mean... leaving aside the obvious clutter, how would there be a way for the ball and the box to know each other, that is, to interact?

There's also the issue of objects needing to pass information between each other. I have quite a bit of experience writing code for the SNES, where you have access to practically the entire RAM all the time. Say you're making a custom enemy for Super Mario World, and you want it to remove all of Mario's coins, then just store zero to address $0DBF, no problem. There's no limitations saying enemies can't access the player's status. I guess I've been spoiled by this freedom, because with C++ and the like I often find myself wondering how to make a value accessible to some other objects (or even global).

Using the example of BoxPong, what if I wanted the ball to bounce off the edges of the screen? width and height are properties of the Game class, and I would need the ball to have access to them. I could pass these kinds of values on (either through constructors or the methods where they're needed), but that just screams bad practice to me.

I guess my main problem is that I need objects to know each other, but the only way I can see to do that is strict hierarchy, which is ugly and impractical.

I've heard of "friend classes" on C++ and kinda know how they work, but if they're the end-all solution, then how come I don't see friend keywords poured all over every single C++ project, and how come the concept doesn't exist in every OOP language? (The same goes for function pointers, which I've just recently learned of.)

Thanks in advance for answers of any kind — and again, if there's a part that doesn't make sense to you, do let me know.

Body:
Meet BoxPong, a very simple game I made to get acquainted with object-oriented game development.

Making BoxPong helped me formulate, among other things, a fundamental question: how can I have objects that interact with each other without having to "belong" to each other?

I have quite a bit of experience writing code for the SNES, where you have access to practically the entire RAM all the time. Say you're making a custom enemy for Super Mario World, and you want it to remove all of Mario's coins, then just store zero to address $0DBF, no problem.

You appear to be missing the point of object-oriented programming.

Object Oriented Programming is about managing dependencies by selectively inverting certain key dependencies in your architecture so that you can prevent rigidity, fragility, and non-reusability.

What is dependency? Dependency is reliance on something else. When you store zero to address $0DBF, you are relying on the fact that that address is where Mario's coins are located and that the coins are represented as an integer. Your Custom Enemy code is reliant on the code implementing Mario and his coins. If you make a change to where Mario stores his coins in memory, you must manually update all the code referencing the memory location.

Object oriented code is all about making your code depend upon abstractions and not on details. So instead of

class Mario
{
    public:
        int coins;
}

you would write

class Mario
{
    public:
        void LoseCoins();

    private:
        int coins;
}

Now, if you want to change how Mario stores his coins from an int to a long or a double or store it on the network or store it in a database or kick off some other long process, you make the change in one place: the Mario class, and all your other code keeps working with no changes.

Therefore, when you ask

how can I have objects that interact with each other without having to "belong" to each other?

you are really asking:

how can I have code that directly depends on each other without any abstractions?

which is not object oriented programming.

I suggest you begin by reading everything here: http://objectmentor.com/omSolutions/oops_what.html and then search youtube for everything by Robert Martin and watch all of it.

My answers derive from him, and some of it is directly quoted from him.


答:
Based on some back-of-the-envelope thinking, I would suggest the following approach:
If you sum each individual row, each column, each diagonal, and the 4 corners, you will obtain a set of 9 numbers, which can then be sorted. This sorted list of numbers will be identical for all the cases you listed and their rotations, but should be unique (i.e., not collide with any other arrangements). If this analysis is true, you could use a trivial hash function of that 9-number list as your stored value.

(Of course, if rotations are excluded from your similarity classification, then I will have to go back to the drawing board.)


问:
Functional Programming - Functions defining specific evaluation of functions passed to it for optimization
Firstmost, I am just getting started with functional programming so I would appreciate corrections in any terminology I may have used incorrectly.

Story time, While doing a Project Euler Problem 1 in Haskell I came to a solution that look roughly like

```<code>sum [3,6..999] + sum [5,10..999] - sum[15,30..999]
</code>```

Which each sum is evaluated into

```<code>foldl (+) [x1,x2,x3,x4,x5,x6,etc] -- yep, the sum is evaluated one element at a time
</code>```

So, my understanding is that lazy evaluation means that sum(2) could be optimized to pattern match the Enumeration(3) so that instead of folding it could optimize for special cases such as

However, at least in Haskell, you cannot pattern match and grab the arguments from another function. The basic idea would be whether sum should be intelligent enough to recognize known mathematical formula for optimization of calculation by evaluating other functions itself:

```<code>-- Doesn't work; didn't intend to; not valid Haskell
-- Try known formulas first if the list generator is known
-- This would match sum [1..100] and return 5050 in O(1)
sum `EnumFromTo` 1 n = n*(n+1)/2
-- If the sum is not recognized then it would do it 1 by 1 as a fallback in O(n)
-- This is the current and only implementation of sum
sum = foldl (+) 0
</code>```

I would guess it would be easier, more straightforward, and betterstyle to define a new sum function with a different name that covers the given formula such as

```<code>sumTo n
    | n >= 1 = n*(n+1)/2
</code>```

But conceptually speaking

Is redefining specific functions from within another function possible?

Would allowing this break something?(IE, in this case, "EnumFromTo 1 n" would not be evaluated, but sum would still return the correct result)

Are there any examples of this evaluation scheme?

Is this a concept any programming language implements?

答:
Check this (Clojure code, sorry I don't know Haskell):

(declare m-enum-upto)

(defn enum-upto [n]
  (cond
    (= n 0) 0
    (= n 1) 1
    :else (+ n (m-enum-upto (dec n)))))

(def m-enum-upto (memoize enum-upto))

; at the first run
(enum-upto 5) ; 0.497711 msec
;again
(enum-upto 5); 0.1130686 msec
;and now
(enum-upto 3); 0.09372 msec
(enum-upto 30); 0.883901 msec
(enum-upto 5); 0.100872 msec
(enum-upto 20); 0.100515 msec
```

The trick is using memoize, it use a cache for storing enum-upto's values. This way only new values have to be calculated.

or you could use reducers:

(defn r-enum-upto [n] (reduce + (map inc (range n))))

(r-enum-upto 200); 0.18883 msec
(r-enum-upto 200000); 43.050614 msec

I hope it helps!

Body:
Check this (Clojure code, sorry I don't know Haskell):

(declare m-enum-upto)

(defn enum-upto [n]
  (cond
    (= n 0) 0
    (= n 1) 1
    :else (+ n (m-enum-upto (dec n)))))

(def m-enum-upto (memoize enum-upto))

; at the first run
(enum-upto 5) ; 0.497711 msec
;again
(enum-upto 5); 0.1130686 msec
;and now
(enum-upto 3); 0.09372 msec
(enum-upto 30); 0.883901 msec
(enum-upto 5); 0.100872 msec
(enum-upto 20); 0.100515 msec

The trick is using memoize, it use a cache for storing enum-upto's values. This way only new values have to be calculated.

or you could use reducers:

(defn r-enum-upto [n] (reduce + (map inc (range n))))

(r-enum-upto 200); 0.18883 msec
(r-enum-upto 200000); 43.050614 msec

I hope it helps!


问:
Caching query results vs Querying each time (finding a middle ground)
This is kind of an expansion on a previously asked question

Some background info:

Querying Over 5,000 items from SQL database that eventually get sorted
into a list depending on who the user is.  One problem is that users
are allowed to have customized lists which means that filtering these
5,000+ items in a uniform way is probably impossible.

Also, important that the amount of users (and users wanting to have
custom item lists) is constantly growing, so there will be an
unprecedented amount of ways to sort. Basically, we won't be paying
attention to filtering this growing list.

Two methods we've come up with so far:
-Option 1: Cache item list PER USER (and filter the items needed after) OR
-Option 2: Cache the list once for the whole site (every user accesses this one cached list)

The issue with Option 1 is that there will be duplicated lists in
cache. Although we do not have an amount of users that will strain our
server's memory, we obviously want our system to have scalability.

The issue with Option 2 is that there will be duplicated items in the
single, cached list. With the amount of users we have, this can
quickly turn into a disorganized list full of duplicated items (i.e.
5,000 items can quickly turn into 10,000 based on a few user's custom
item preferences)

Is there a "middle ground" for dealing with this situation? One that combines some benefits of querying and caching.

Even if a response is a link to a potentially helpful source, I would appreciate it as I am kind of at a fork in the road.

Looking to open up new possible paths in my brainstorming.

答:
Some may not feel this is not an answer, but it is a way to derive a better answer.

Collect data on user behavior.
Many users may prefer a default configuration. If so, it would make sense to cache this list. I've seen some apps that are highly configurable, but I just use it the way it came out of the box. I'm sure there are hundreds of settings for Microsoft Word that 90% of users never bother using.

Otherwise, pull it from the database/disk. Depending on the size of the db and your particular RDBMS, most of your data may be in memory anyway (I know SQL Server does this.). This is where you'll start seeing any bottlenecks. You can address those later.

Don't be too anxious to solve a problem too soon. It may not be a problem. The wrong problem or the wrong solution. As much as you may want some sort of "best practice" or standard use case, there probably isn't one that matches your situation.


问:
Semantically more appropriate package name than `util` for the following things?
As a strawman consider the package java.util it is a dumping ground for various classes that in most cases do not share anything in common other than the person that put them there was lazy or uninspired to come up with a more semantically correct package name for their class.

As but one example, take the class UUID what would have been a semantically correct package name for that class?

I am working on implementing my own UUID class to be more lightweight. I do not want to use me.myproject.util.UUID for my package name.

I considered me.myproject.rfc4122.UUID but that does not imply the semantic of the use of UUID.

I also considered me.myproject.uuid.UUID but I do not like the tautology in that, even though it is a popular approach in Python to put a class in a module with the same name, and packages in Java are not semantically equivalent to modules in Python.

I also considered me.myproject.UUID but rejected it because I do not want to pollute that part of the namespace with things that are not related. This just moves the problem up a level.

I also considered me.myproject.lib.UUID but this has no more semantic meaning than .util and just renames the problem.

semantics : the branch of linguistics and logic concerned with meaning.

答:
Uncle Bob has some guidelines on package separation.

The first three package principles are about package cohesion, they tell us what to put inside packages:

The granule of reuse is the granule of release

Classes that change together are packaged together

Classes that are used together are packaged together

So, answering your question, who/what is going to use the UUID class, have it as an attribute or invoke operations in it? How is your dependency graph? UUID will be used together with what other classes?

Depending on your answer, maybe you should call it the me.myproject.identity package, the me.myproject.serialization package, me.myproject.DTO or even something else entirely. Maybe, the UUID class should be kept together with your models and you will put it in a package that you already have, like me.myproject.models.


答:
You should cache the query by the query parameters. In this case user id.

However, the point of caching is to prevent running the same query multiple times in quick sucession.

This would usualy be caused by each user running the same query per request. When you have 1000 users on the site and each making requests at the same time and running a getMenu query for example, wont all hit the database and overload your db. The first one runs and  the rest get the cached result. Your Db has to run a query per second instead of 1000 queries per second.

Assuming your code is reasonably well written though, you wouldnt expect a single request to make the same call lots of times, or a single user to make many multiple requests for the same thing. As each user is making a unique query they will all hit the db. They dont benefit from a differnt user already having made the call. If you cache al the results, you dont really see much benefit and will run out of memory.

so caching is unlikely to help you much.

I think the comments hit the nail on the head that your custom per user list is inherrently unscaleable.

Maybe you can divide it into a standard list and per user modifications? or opt in groups of items?

OR

you can cache the list client side. ie a cookie. this allows your effective memory to scale with your users.

Title: Caching query results vs Querying each time (finding a middle ground)

Body:
This is kind of an expansion on a previously asked question

Some background info:

Querying Over 5,000 items from SQL database that eventually get sorted
into a list depending on who the user is.  One problem is that users
are allowed to have customized lists which means that filtering these
5,000+ items in a uniform way is probably impossible.

Also, important that the amount of users (and users wanting to have
custom item lists) is constantly growing, so there will be an
unprecedented amount of ways to sort. Basically, we won't be paying
attention to filtering this growing list.

Two methods we've come up with so far:
-Option 1: Cache item list PER USER (and filter the items needed after) OR
-Option 2: Cache the list once for the whole site (every user accesses this one cached list)

The issue with Option 1 is that there will be duplicated lists in
cache. Although we do not have an amount of users that will strain our
server's memory, we obviously want our system to have scalability.

The issue with Option 2 is that there will be duplicated items in the
single, cached list. With the amount of users we have, this can
quickly turn into a disorganized list full of duplicated items (i.e.
5,000 items can quickly turn into 10,000 based on a few user's custom
item preferences)

Is there a "middle ground" for dealing with this situation? One that combines some benefits of querying and caching.

Even if a response is a link to a potentially helpful source, I would appreciate it as I am kind of at a fork in the road.

Looking to open up new possible paths in my brainstorming.


答:
Because of the way the expression is parsed and evaluated, a sum function will get the results of the EnumFromTo, and therefore under normal conditions there is no way to get at its arguments.

To receive the unevaluated arguments, you would need to use a macro.  I don't know anything about Template Haskell, but supposedly it provides this ability.  In practice, macros are notoriously difficult to use outside of homoiconic languages like LISP.  The laziness of Haskell also removes a lot of the cases where macros would be useful.  Your sumTo function is much easier to implement, so that's what people will use.

Title: Functional Programming - Functions defining specific evaluation of functions passed to it for optimization

Body:
Firstmost, I am just getting started with functional programming so I would appreciate corrections in any terminology I may have used incorrectly.

Story time, While doing a Project Euler Problem 1 in Haskell I came to a solution that look roughly like

```<code>sum [3,6..999] + sum [5,10..999] - sum[15,30..999]
</code>```

Which each sum is evaluated into

```<code>foldl (+) [x1,x2,x3,x4,x5,x6,etc] -- yep, the sum is evaluated one element at a time
</code>```

So, my understanding is that lazy evaluation means that sum(2) could be optimized to pattern match the Enumeration(3) so that instead of folding it could optimize for special cases such as

However, at least in Haskell, you cannot pattern match and grab the arguments from another function. The basic idea would be whether sum should be intelligent enough to recognize known mathematical formula for optimization of calculation by evaluating other functions itself:

```<code>-- Doesn't work; didn't intend to; not valid Haskell
-- Try known formulas first if the list generator is known
-- This would match sum [1..100] and return 5050 in O(1)
sum `EnumFromTo` 1 n = n*(n+1)/2
-- If the sum is not recognized then it would do it 1 by 1 as a fallback in O(n)
-- This is the current and only implementation of sum
sum = foldl (+) 0
</code>```

I would guess it would be easier, more straightforward, and betterstyle to define a new sum function with a different name that covers the given formula such as

```<code>sumTo n
    | n >= 1 = n*(n+1)/2
</code>```

But conceptually speaking

Is redefining specific functions from within another function possible?

Would allowing this break something?(IE, in this case, "EnumFromTo 1 n" would not be evaluated, but sum would still return the correct result)

Are there any examples of this evaluation scheme?

Is this a concept any programming language implements?


问:
What are standard directory layouts for source code, other libraries, build scripts, etc.?
I'm in the process of proposing a new standard directory layout that will be used across all the projects in our organization.  Projects can have compiled source code, setup scripts, build scripts, third-party libraries, database scripts, resources, web services, web sites, etc.

This is partly inspired by discovering Maven's standard layout.

Are there any other standard layouts that are generally accepted in the industry?

答:
I am just starting in programing, but i have seen many project use this one:

src: where you place your source code, generally in folders by hierarchy and the project own structure

bin: where you can place the compiled files

script: where you can place, scripts for the user

test: where you can place scripts that test the program

docs: where you should place documents explaining the project

examples: where you should place examples of how to use the project

dist: where you can place the uncompiled source code package

build: where you can place the compiled distributions, generally in folders by platform

you should also place your building/compiling/distribution script in the project root folder, along with files like copyrights and readmes

I found an Oracle document describing and standard layout for some project, you can see many similarities:

https://docs.oracle.com/cd/E17076_04/html/porting/layout.html

edit

It have also seen a lib folder, i imagine here you should place external libraries, i did not think of it because i use python where tools like pip automatically download and install them