问:
Pure C Vector Implementation
I am implementing a vector in C. I am doing this for the fun of programming, for the fun of learning, and for the use of the data structure in later projects. This is not homework. My question is regarding methodology, not necessarily implementation, therefore I am not really looking for a code review.

Now, I have read over many implementation examples and most of them take the size of an individual element as an argument to the Vector_create() function, and use this for later memmove()/memcpy() calls and what not and more or less keep (for instance) the vector's elements in contiguous memory. In other words, the underlying array is essentially a single void*.

In the implementation I wrote before doing a lot of looking at how other people have done it, I allow(force) the client code to allocate an "object" and pass that as a pointer to the Vector_append() function. So my underlying array is a void**. So I guess the real question I am asking is if this is wrong. Wrong as in best practices wrong.

I see that the "normal" way of doing this doesn't use an array of pointers and instead just copies the memory of a struct (for example) into the underlying void* array and thereby keeping the actual data of the elements contiguous, as mentioned earlier. My way avoids a crap load of memmove()/memcpy() because I just copy pointer values, however, I am forcing the client to malloc() everything that is sent to the vector, and thereby do a bunch of screwing around on the heap.

Along those lines, I do call free() on the underlying data item when the item is removed, so the vector library does a free() that the vector library never did the original malloc() on. Is this bad practice too? The only trouble I seem to get into is if there was a member variable (for lack of a better term) that points to dynamic memory within the struct. It then becomes the client responsibility to free() that data, but again, the struct itself is freed from within the vector library call Vector_remove().

答:
Yes, the design of your Vector is 'wrong'.

Such a vector is usually thought of as a resizeable array, with the associated expectation that, like an array, it directly contains the elements. Your requirement that Vector stores pointers to allocated elements breaks that expectation.

Storing pointers is inefficient if the elements to be stored are small (for example, integers or doubles), because the overhead of dynamic allocation becomes significant (2 to 3 times the data size) and you need to store both the pointer and the actual data, where in the traditional design, you only need to store the few bytes for the actual data. Additionally, in the traditional design, all the elements are in adjacent memory locations, which makes the typical access patterns (looping over the items) much more cache-friendly for the CPU than your design, where the elements are scattered around in memory.

Sometimes it is necessary to conceptually store items in multiple containers. With the conventional design, this can be accommodated by storing pointers in the containers and managing the actual objects yourself. This technique can also be used to limit the amount of copying that needs to be done, if the user of the container thinks that it is a reasonable trade-off. With your design, you would need to dynamically allocate the pointers that get stored in the container, which is far from convenient and completely counter-intuitive for most developers.

Any interface that requires a pointer to allocated memory is prone to misuse, because the compiler can't see that Vector_append(&a) is an error and to a human reviewer it is also not immediately obvious. If you are lucky, this is detected during testing, but in some cases it will go undetected for a very long time.

The fact that Vector_remove() deletes the data item will also not sit nicely in most development circles, because

Many coding guidelines require that corresponding malloc and free calls should be made from the same module. Your design makes it impossible to keep that requirement.

It is common practice to create, for complex structures that contain pointers to allocated memory, to create a pair of 'constructor'/'destructor' functions that take care of all the allocations/cleanup in one go, including the 'root' struct. This also does not work correctly with Vector_remove calling free.

Title: Pure C Vector Implementation


问:
How do I design a card game?
I can not come up with a good architecture for my card game. I need help to understand how games usually are designed.

First, I will describe game rules.

Game Rules

Setup

There are four players, each two player form a team.

Each player gets 12 shuffled cards

There are 4 blinded cards on table(river)

Players order are like this

Betting

Each player can pass or select a number greater than current bet between 100 to 160

Betting starts from first player and circles until a team pass

Once a player pass they can't bet anymore

The team that wins the betting round should at least collect points equal to their bet in order to win the game

The team that lost the betting round should not allow the their team achieve their goal

If the team that won betting round gets all the points the other team will get negative points equal to their bet

if the team that lost the betting round collects all the points the other team will get double negative points

Game flow and collecting points

Player that won betting round (the king) gets four remaining cards on the table.

Then she/he can save a set of four cards in their team cards bank without even playing them.

The king will pick a suit as the ruler suit and let others know that

King starts the game by putting a card from his/her hand on table. Each other player should play in this order

if they have the same suit of that card in their hand, they have to play one of those cards

if they don't have it, they can play any other suit

After all other players played their hands, winner of the round will be:

The one who has highest card if all cards are the same

The one who has highest "ruler" card if there is any

Winner of the round will collect cards and put it in their bank

Player who won previous round will start the next round

This will continue until everybody's hand is empty

Counting points

Winning each round has 5 points. This means every 4 cards has at least 5 points.

Having Ace, 10 or 5 in bank each adds 5 points

My Design

Classes

```<code>class Card {
   string suit;
   string rank
}
class Deck {
  List cards = [];
  List suits = ['S', 'H', 'D', 'C'];
  List ranks = ['1', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
  private void init(){..}
  void shuffle(){...}
}

class Game{
  Deck deck = new Deck();
  Player player1;
  Player player2;
  Player player3;
  Player player4;
  int _isOn = 0;

  Game(this.player1, this.player2, this.player3, this.player4){
    deck.makeCards();
    deck.shuffle();
    start();
  }

  void start(){
    player1.cards.addAll( deck.cards.getRange(0, 12) );
    player2.cards.addAll( deck.cards.getRange(12, 24) );
    player3.cards.addAll( deck.cards.getRange(24, 36) );
    player4.cards.addAll( deck.cards.getRange(36, 48) );
    deck.cards.removeRange(0, 48);
  }

  String toJson(){
  }

  String toString(){
  }
}
class Player{
  String name;
  int points;
  List cards = [];

  Player(this.name, {this.points});

  String toJson(){}

  String toString(){}
}
</code>```

My Problem

Now that I've defined all these classes I don't know how to bind this definitions to a database (like Mongo) and control the game flow.

Where should all that logic go?

How should I keep state in a server/client scenario?

Note:

I'm using Dart to program this but I don't necessary want answers be written in Dart.

答:
Where should all that logic go?

Start with putting it in your Game class.

This is a rule based game with a limited number of states. I would model it as a state machine. The state pattern will help you immensely.

Eventually you will want to extract that FSM into separate class(es), but don't worry about that for now.

How should I keep state in a server/client scenario?

This is impossible to answer without knowing more about your setup. Serializing your Game object and states to the database every turn might do the trick.

ContentLicense: CC BY-SA 3.0

Title: How do I design a card game?


问:
Apache License 2.0 and source code recompile
I am not a licenses expert so I got confused a bit... The license Apache 2.0; Does it allow to get source codes and modify them for new projects? I mean modify source codes (some its parts) and recompile them?</p>

答:
If you have received/downloaded source code that is covered by the Apache 2.0 licence, then you are allowed to

Create modified versions of the source code

Distribute the original program/library, either in source code format or as a compiled program/library

Distribute the modified program/library, either in source code format or as a compiled program/library

If you have received/downloaded a compiled program/library that is covered by the Apache 2.0 license, then you can ask to get the source code, but there is no obligation to give it to you.

Technically, you have the same rights, whether or not you received the source code, but creating modifications without access to the source is so much harder that it probably isn't worth the effort.


答:
You're making a classic mistake here.  Someone told you to make a web application for a card game, and you're trying to determine how to make all of it at once.  This approach confuses even the best programmers, since studies have shown that you can only retain 7 pieces of information readily available in your mind at one time.  Trying to juggle with more requires intense concentration and you cannot expect to keep that up.

Rather, try to focus more on writing a card game library like someone were going to call your library in order to play your card game.  You seem to have an excellent start on your model.  That is good, but you need to make Game the interface by which callers can use make moves and so forth.

So I would expect Game would have several new methods like:

```<code>getPlayers()        // Get all player info
getCurrentPlayer()  // Get information about the active player in his turn (hand, money to bet with, etc.)
fold()              // Current player folds and current player changes
bet(float amount)   // Current player bets and current player changes
</code>```

In short, everything you need to know in order to run the game, you can do so using your object Game.  Only once you have this do you proceed to step 2.

Write a separate class whose sole purpose is to receive incoming requests, apply them to Game and send the output back to the user.  If you want to convert Game output to JSON, you do it outside of Game since that is not the purpose of Game!

In order to persist this information, you could create another class which provides an interface to MongoDB.  This class would not know of the existence of Game and neither would Game know of the existence of this class.

In short, focus on the individual components, and you'll be fine.  You start to go wrong when you're trying to take too many aspects into consideration when writing your program.  As a wise professor once told me, "Know and embrace the fact that the first program you write for a project will be rewritten in its entirety by the end."

Title: How do I design a card game?

Body:
I can not come up with a good architecture for my card game. I need help to understand how games usually are designed.

First, I will describe game rules.

Game Rules

Setup

There are four players, each two player form a team.

Each player gets 12 shuffled cards

There are 4 blinded cards on table(river)

Players order are like this

Betting

Each player can pass or select a number greater than current bet between 100 to 160

Betting starts from first player and circles until a team pass

Once a player pass they can't bet anymore

The team that wins the betting round should at least collect points equal to their bet in order to win the game

The team that lost the betting round should not allow the their team achieve their goal

If the team that won betting round gets all the points the other team will get negative points equal to their bet

if the team that lost the betting round collects all the points the other team will get double negative points

Game flow and collecting points

Player that won betting round (the king) gets four remaining cards on the table.

Then she/he can save a set of four cards in their team cards bank without even playing them.

The king will pick a suit as the ruler suit and let others know that

King starts the game by putting a card from his/her hand on table. Each other player should play in this order

if they have the same suit of that card in their hand, they have to play one of those cards

if they don't have it, they can play any other suit

After all other players played their hands, winner of the round will be:

The one who has highest card if all cards are the same

The one who has highest "ruler" card if there is any

Winner of the round will collect cards and put it in their bank

Player who won previous round will start the next round

This will continue until everybody's hand is empty

Counting points

Winning each round has 5 points. This means every 4 cards has at least 5 points.

Having Ace, 10 or 5 in bank each adds 5 points

My Design

Classes

```<code>class Card {
   string suit;
   string rank
}
class Deck {
  List cards = [];
  List suits = ['S', 'H', 'D', 'C'];
  List ranks = ['1', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'];
  private void init(){..}
  void shuffle(){...}
}

class Game{
  Deck deck = new Deck();
  Player player1;
  Player player2;
  Player player3;
  Player player4;
  int _isOn = 0;

  Game(this.player1, this.player2, this.player3, this.player4){
    deck.makeCards();
    deck.shuffle();
    start();
  }

  void start(){
    player1.cards.addAll( deck.cards.getRange(0, 12) );
    player2.cards.addAll( deck.cards.getRange(12, 24) );
    player3.cards.addAll( deck.cards.getRange(24, 36) );
    player4.cards.addAll( deck.cards.getRange(36, 48) );
    deck.cards.removeRange(0, 48);
  }

  String toJson(){
  }

  String toString(){
  }
}
class Player{
  String name;
  int points;
  List cards = [];

  Player(this.name, {this.points});

  String toJson(){}

  String toString(){}
}
</code>```

My Problem

Now that I've defined all these classes I don't know how to bind this definitions to a database (like Mongo) and control the game flow.

Where should all that logic go?

How should I keep state in a server/client scenario?

Note:

I'm using Dart to program this but I don't necessary want answers be written in Dart.

Body:
You're making a classic mistake here.  Someone told you to make a web application for a card game, and you're trying to determine how to make all of it at once.  This approach confuses even the best programmers, since studies have shown that you can only retain 7 pieces of information readily available in your mind at one time.  Trying to juggle with more requires intense concentration and you cannot expect to keep that up.

Rather, try to focus more on writing a card game library like someone were going to call your library in order to play your card game.  You seem to have an excellent start on your model.  That is good, but you need to make Game the interface by which callers can use make moves and so forth.

So I would expect Game would have several new methods like:

getPlayers()        // Get all player info
getCurrentPlayer()  // Get information about the active player in his turn (hand, money to bet with, etc.)
fold()              // Current player folds and current player changes
bet(float amount)   // Current player bets and current player changes

In short, everything you need to know in order to run the game, you can do so using your object Game.  Only once you have this do you proceed to step 2.

Write a separate class whose sole purpose is to receive incoming requests, apply them to Game and send the output back to the user.  If you want to convert Game output to JSON, you do it outside of Game since that is not the purpose of Game!

In order to persist this information, you could create another class which provides an interface to MongoDB.  This class would not know of the existence of Game and neither would Game know of the existence of this class.

In short, focus on the individual components, and you'll be fine.  You start to go wrong when you're trying to take too many aspects into consideration when writing your program.  As a wise professor once told me, "Know and embrace the fact that the first program you write for a project will be rewritten in its entirety by the end."


问:
Is a PHP file secure enough on a GoDaddy Server to hard code an AES salt into the file?
So I am creating a web api for an app I am making. The data is sanitized before it is sent to my web api and then encrypted before it is stored in my MySql server.

The phone app sanitizes then behind the scenes calls -> web php api which encrypts aes style with a hard coded salt then calls -> server

My question is if I hard code a salt value into the php page is it at risk on a go daddy server?

I mean I know NOTHING is truly secure however what are the odds that someone would be able to hack a go daddy server and see my php source code. Assuming they disassemble my app and see the URL call to the api.

Since php code executes on the server I am assuming that there is no way to extract it?

答:
I would say that it is very common practice to put constants (passwords, salts etc.) in php files.

How could you store your salt else? In a database? Where do you put your database credentials - again in the source code.
You can also store it in an include file (.inc) and use that in your php code. It does not matter very much.

Speaking of GoDaddy: I have no clue if that hoster is more secure than another hoster, but technically it is all the same.


问:
Why does the US government disallow dynamic languages for secure projects?
I know some people that are currently working on a project for the US military (low security level, non-combat human resources type data).

An initial state of the project code was submitted to the military for review, and they ran the program through some sort of security analyzer tool. It returned a report of known security issues in the code and required changes that needed to be implemented before delivery of the final product.

One of the items that needed to be resolved was removal of part of the project that was written in Ruby as it is a dynamic language.

What is the background/reason for not allowing a dynamic language to be used in a secure setting? Is this the government being slow to adopt new technologies? Or do dynamic languages pose an additional security risk compared to static languages (ala C++ or Java)?

答:
Both DoD and NASA have a long history with programming fails that cost them billions of dollars. Both institutions have accepted processes that should protect them from repeating the same mistakes.

```<code>Is this the government being slow to adopting new technologies?
</code>```

This is a misconception - dynamic languages are not a new technology, they are quite old. The problem is that if you ever had a problem caused by a dynamic language (e.g. by weak/dynamic typing) and that problem cost you a lot of money, you could accept a policy that would prevent you to do the same mistake again - e.g. banning the use of dynamic languages in sensitive systems.

Dynamic languages will often "swallow" bugs and will end up with some unexpected behavior. This is very dangerous in sensitive systems. If something wrong is happening, you want to know it as soon as possible.

If security is concerned, it would be necessary to see the actual use case. For example, I don't think that a Ruby on Rails web page would be automatically less secure than a Java webpage.

Body:
Both DoD and NASA have a long history with programming fails that cost them billions of dollars. Both institutions have accepted processes that should protect them from repeating the same mistakes.

Is this the government being slow to adopting new technologies?

This is a misconception - dynamic languages are not a new technology, they are quite old. The problem is that if you ever had a problem caused by a dynamic language (e.g. by weak/dynamic typing) and that problem cost you a lot of money, you could accept a policy that would prevent you to do the same mistake again - e.g. banning the use of dynamic languages in sensitive systems.

Dynamic languages will often "swallow" bugs and will end up with some unexpected behavior. This is very dangerous in sensitive systems. If something wrong is happening, you want to know it as soon as possible.

If security is concerned, it would be necessary to see the actual use case. For example, I don't think that a Ruby on Rails web page would be automatically less secure than a Java webpage.


答:
Whether a codebase is secure or not depends on how you write your code, how you test it and how you validate and monitor your development and deployment process. Languages are neither secure nor insecure, it's how you code.

The majority of security incidents due to malicious input (sql injections, buffer overflows), viruses, rootkits and trojans. No language can protect you from that.

So banning classes of languages for being "insecure" is not a valid reason.

I suspect that someone, for whatever reason - informed or not - decided to ban these languages. After a while it became an organizational truth. It may have been true at that point in time for some projects, but control cultures are not keen on changing decisions (admit they were wrong) and rather prefers simple rules. They thrive on rules and regulations and it does not matter if they make sense or not, it is the perceived safety that counts.

This happens all the time in control cultures. I see it more or less daily. It makes no sense, but that's how it goes. If you want to read more about this highly relevant topic, I recommend Schneider's book "The Reengineering Alternative". Here is a culture diagram by Michael Sahoto/Agilitrix, based on Schneider's book:

Title: Why does the US government disallow dynamic languages for secure projects?

Body:
I know some people that are currently working on a project for the US military (low security level, non-combat human resources type data).

An initial state of the project code was submitted to the military for review, and they ran the program through some sort of security analyzer tool. It returned a report of known security issues in the code and required changes that needed to be implemented before delivery of the final product.

One of the items that needed to be resolved was removal of part of the project that was written in Ruby as it is a dynamic language.

What is the background/reason for not allowing a dynamic language to be used in a secure setting? Is this the government being slow to adopt new technologies? Or do dynamic languages pose an additional security risk compared to static languages (ala C++ or Java)?


问:
How can I reverse engineer a hash code?
I am building an application in C# that works with a Progress database. The passwords that are stored in this database are stored using a hash algorithm that Progress has not made public. However, I would like to authenticate using these hashes. Is it feasible to reverse engineer such a hash algorithm and how would I go about doing this?

To be clear: I am not looking for a way to get the unhashed passwords from the hashes. I'm looking for the algorithm to get a hash from a password.

答: Well, you could take a list of all hashing algorithms you can think of, run them against a list of the most popular passwords and check whether any of the results match any of your hashes. Of course this will only work if the site did not enforce a strong password policy and the hashing algorithm isn't exotic (or parameterized).</p>

Title: How can I reverse engineer a hash code?


答:
You could use progress to insert a hashed password into a temp var and compare that to the stored hash.

Using progress to make that hash.

Title: How can I reverse engineer a hash code?

Body:
I am building an application in C# that works with a Progress database. The passwords that are stored in this database are stored using a hash algorithm that Progress has not made public. However, I would like to authenticate using these hashes. Is it feasible to reverse engineer such a hash algorithm and how would I go about doing this?

To be clear: I am not looking for a way to get the unhashed passwords from the hashes. I'm looking for the algorithm to get a hash from a password.


问:
Why does Java compiler decide whether you can call a method based on the "reference" type and not on actual "object" type?
I was just wondering why does Java compiler decide whether you can call a method based on the "reference" type and not on actual "object" type? To explain I would like to quote an example:

```<code>class A {
    void methA() {
        System.out.println("Method of Class A.");
    }
}

class B extends A {
    void methB() {
        System.out.println("Method of Class B.");
    }
    public static void main(String arg[]) {
        A ob = new B();
        ob.methB();       // Compile Time Error
    }
}
</code>```

This will produce a Compile Time Error that method methB() not found in class A, although Object Reference "ob" contains an object of class B which consists of method methB(). Reason for this is that Java Compiler checks for the method in Class A (the reference type) not in Class B (the actual object type). So, I want to know whats the reason behind this. Why does Java Compiler looks for the method in Class A why not in Class B(the actual object type)?

答:
I was just wondering why does Java compiler decide whether you can call a
  method based on the "reference" type and not on actual "object" type?

Instead of debating on Why does Java compiler decide whether you can call a method based on the “reference” type and not on actual “object” type? let say java compiler does allow this.Consider the following example

```<code>class A {
    void methA() {
        System.out.println("Method of Class A.");
    }
}

class B extends A {
    void methB() {
        System.out.println("Method of Class B.");
    }
    public static void main(String arg[]) {
        A ob = new B();
        ob.methC();       // Compile Time Error
    }
}
</code>```

See the method ob.methC(); ? This method is neither in Class A or Class B. If Java compiler would have allowed this it would have cause an Error. As the saying goes it is better to take care of your self than to fall ill and eat medicines. Java was designed to be simple and not allow error that we know have high probability of occurring(One of the reason why Exceptions were introduced from very beginning).

Also whole concept of polymorphism is based on the fact that the concrete class is only known at runtime but not at compile time. So for safety java compilers are designed that way. Though you can decide just to declare your method in superClass(like making it abstract) and then implement it in the sub class.

Body:
I was just wondering why does Java compiler decide whether you can call a
  method based on the "reference" type and not on actual "object" type?

Instead of debating on Why does Java compiler decide whether you can call a method based on the “reference” type and not on actual “object” type? let say java compiler does allow this.Consider the following example

class A {
    void methA() {
        System.out.println("Method of Class A.");
    }
}

class B extends A {
    void methB() {
        System.out.println("Method of Class B.");
    }
    public static void main(String arg[]) {
        A ob = new B();
        ob.methC();       // Compile Time Error
    }
}

See the method ob.methC(); ? This method is neither in Class A or Class B. If Java compiler would have allowed this it would have cause an Error. As the saying goes it is better to take care of your self than to fall ill and eat medicines. Java was designed to be simple and not allow error that we know have high probability of occurring(One of the reason why Exceptions were introduced from very beginning).

Also whole concept of polymorphism is based on the fact that the concrete class is only known at runtime but not at compile time. So for safety java compilers are designed that way. Though you can decide just to declare your method in superClass(like making it abstract) and then implement it in the sub class.


问:
Why must a constructor's call to the superconstructor be the first call?
It is an error if you do anything in a constructor before calling the superconstructor. I remember that I had problems because of that. Yet, I do not see how this saves us from errors. It could save you from using uninitialized fields. But, the Java compiler that checks for using uninitalized variables does that and this stupid rule does not improve anything here.

The only serious consideration argument I remember was that we need it for OOP, because objects in real life are constructed this way: you create a cucumber by first creating a vegetable and then add cucumber attributes. IMO, it is opposite. You first create a cucumber and, by duck is a duck principle, it becomes a vegetable. Another argument was that it improves safety. Not writing the code improves the dependability much better, so I do not consider this as argument. Creating more complex code when you need to workaround a stupid restriction, is what makes the program more error-prone.

This rule creates a serious pain (at least for me). So, I want to hear the serious argument and serious example where it could be useful.

答:
When you inherit from an object, you may not be able to see the implementation of the constructor or underlying methods.

There may be more going on in the constructor than just initialization of variables.
such as hardware access, database access, network communication, etc. Not saying this is good design or not - just saying you may not be aware of it.

But even if it was just variables. There may be member functions that rely on those variables being instantiated properly. There may be function calls that occur in the instantiation of those variables. Because of encapsulation you can't be sure that isn't the case, so to be safe you fully construct your base item first - otherwise your implementation may cause the super class to "break".

And it works the other way around to. If someone inherits from your class, you know that your construction code will execute properly. The programmer inheriting your class can never break your code, just his. If he is having a problem, he knows he should check his code.


答:
The object initialization sequence is complex enough as it is and already sometimes causes headaches. Allowing subclasses to run code before the superclass constructor would make it more complex and confusing still, with more potential for subtle bugs, especially if there is a hierarchy of multiple classes which all do this.

It also reduces the conceptual coupling between superclasses and subclasses. You look at the superclass and can see how it will be initialized before it is used. Allowing subclass code to do arbitrary stuff before the superclass initialization could easily break some assumptions made by the superclass code, and subclasses should, as much as possible, not have to depend on understanding of implementation details of the superclass.

All in all, not allowing subclass code to run before the superclass is fully initialized leads to code that is easier to understand and less error-prone. It may sometimes require workarounds, but just because a rule prevents you from doing what would be convenient in your immediate circumstances does not mean it's a bad or stupid rule.

Title: Why must a constructor's call to the superconstructor be the first call?

Body:
It is an error if you do anything in a constructor before calling the superconstructor. I remember that I had problems because of that. Yet, I do not see how this saves us from errors. It could save you from using uninitialized fields. But, the Java compiler that checks for using uninitalized variables does that and this stupid rule does not improve anything here.

The only serious consideration argument I remember was that we need it for OOP, because objects in real life are constructed this way: you create a cucumber by first creating a vegetable and then add cucumber attributes. IMO, it is opposite. You first create a cucumber and, by duck is a duck principle, it becomes a vegetable. Another argument was that it improves safety. Not writing the code improves the dependability much better, so I do not consider this as argument. Creating more complex code when you need to workaround a stupid restriction, is what makes the program more error-prone.

This rule creates a serious pain (at least for me). So, I want to hear the serious argument and serious example where it could be useful.


问:
Best practice regarding security in mobile applications
A friend asked me recently about mobile applications and the security surrounding them. As he wishes to make a mobile app that would handle very secure information such as credit card numbers, I was starting to wonder about the issue of security surrounding these devices. Does it seem reasonable to store sensitive information inside of a mobile app? I wonder this because I have seen dex to class to java decompilers online and I imagine that on any mobile device there is no guarentee that the data in the secure locations is as secure as they would like you to believe.

But, I'm not an expert on these things; I feel like I'm a stranger when it comes to the wonderful world of security. So that's why I ask you this, what is the best way to securely store the data? Is it feasible to securely store credit card information/passwords/etc on a mobile device? If so, what methods should one take in order to assure the users that the best possible measures were taken to securely store their information. If not, what is a good alternative to store all that sensitive information? Even then, with the stories in the news about user data stored in web sites being compromised what measures should be taken to ensure that the data stored there is also secure?

答:
Only download apps from trusted enterprise app stores. However, McRee says that’s not even 100% foolproof. Enterprises should assume that the unknown third-party mobile apps users download should not be trusted. Enterprises should restrict the use of synchronization services, and distribute organization-specific apps from a dedicated mobile application store.

Encrypt data in transit. This is a simple step but one that is often overlooked, Frank Kim, founder of mobile application security consultancy ThinkSec, tells TechTarget. “In the rush to deliver mobile apps, developers are making a lot of the same mistakes they made with early Web apps.


问:
Need help understanding UML diagram
I'm focusing on trying to understand UML diagrams and learning to interpret them in order to implement the designs they describe. In the following diagram, I am not clear on what the implementation for Port Operation should be.

It looks like it should be a class/entity the same as the others in the diagram. I understand the relationship between Leg and Port Operation is bidirectional. But it seems that it does not make sense to have a class just for port operations, and having Load() and Unload() methods in Leg doesn't make much sense since a Leg class does not represent a port or its' operations.

When reading UML diagrams, is it expected that there are multiple ways for someone to implement it? i.e some ways are better than others, and it's a judgement call as to how someone implements it?

What would be the recommened implementation for the above diagram with regards to Port Operation?

答:
UML is a drawing/design language, but it does not specify how the drawing elements are mapped to the constructs of your programming language. In that way, UML provides for multiple ways to implement things.

Also, an UML diagram usually does not show everything, because that would clutter the diagram too much, so only the relevant details are shown in each diagram.

With the above in mind, you should regard each UML diagram as a definitive design document for the portion of the application that is shown therein. Presumably someone has put thought into the diagram and can give a reason for the existence of each of the classes and interconnections.
When implementing the design from an UML diagram, you should strive that other programmers, who know the design, can recognize the design in your code.

In the design in question, Port Operation and Leg are two distinct classes. Between these classes, there are two bi-directional links. As I read it, a Leg instance knows about two, different, Port Operation instances, one for loading and the other for unloading. The names next to the lines/arrows are not method names, but they clarify the context of the connection. In the implementation they are typically used as basis for the attribute name of the reference that signifies the connection.

Title: Need help understanding UML diagram


答:
Let me propose a question. Lets have this code:

```<code>class A {
    void methA() {
        System.out.println("Method of Class A.");
    }

    public static void main(String arg[]) {
        A ob;
        if ((new Random().nextInt(2)) == 0){
            ob = new B();
        } else {
            ob = new C();
        }
        ob.methB(); // what now?
    }
}

class B extends A {
    void methB() {
        System.out.println("Method of Class B.");
    }
}

class C extends A {
    void methC() {
        System.out.println("Method of Class C.");
    }
}
</code>```

Now, what will happen if instance of class C is saved in ob? What method will be called?

The point is, that method calls are resolved at compile time and compiler cannot know what concrete class instance will be inside variable during compilation. That is why you can only call method that exist in class that is defined as type of given variable. And if said method is virtual, then the runtime will pick correct overload when the program runs. This is basis for late binding in OOP languages.

Title: Why does Java compiler decide whether you can call a method based on the "reference" type and not on actual "object" type?

Body:
I was just wondering why does Java compiler decide whether you can call a method based on the "reference" type and not on actual "object" type? To explain I would like to quote an example:

```<code>class A {
    void methA() {
        System.out.println("Method of Class A.");
    }
}

class B extends A {
    void methB() {
        System.out.println("Method of Class B.");
    }
    public static void main(String arg[]) {
        A ob = new B();
        ob.methB();       // Compile Time Error
    }
}
</code>```

This will produce a Compile Time Error that method methB() not found in class A, although Object Reference "ob" contains an object of class B which consists of method methB(). Reason for this is that Java Compiler checks for the method in Class A (the reference type) not in Class B (the actual object type). So, I want to know whats the reason behind this. Why does Java Compiler looks for the method in Class A why not in Class B(the actual object type)?

Body:
Let me propose a question. Lets have this code:

class A {
    void methA() {
        System.out.println("Method of Class A.");
    }

    public static void main(String arg[]) {
        A ob;
        if ((new Random().nextInt(2)) == 0){
            ob = new B();
        } else {
            ob = new C();
        }
        ob.methB(); // what now?
    }
}

class B extends A {
    void methB() {
        System.out.println("Method of Class B.");
    }
}

class C extends A {
    void methC() {
        System.out.println("Method of Class C.");
    }
}

Now, what will happen if instance of class C is saved in ob? What method will be called?

The point is, that method calls are resolved at compile time and compiler cannot know what concrete class instance will be inside variable during compilation. That is why you can only call method that exist in class that is defined as type of given variable. And if said method is virtual, then the runtime will pick correct overload when the program runs. This is basis for late binding in OOP languages.


答:
In layman's words:

An inheritance relationship is an "IS A" relationship.

If Human inherits from Ape, it means that a Human is, firstly, an Ape then a Human. ( I'm not saying humans descent from apes, but that they are apes ).

It makes sense that you first initialize your Ape self in order to built upon it and get to be your Human self.

The superclass is the base you built upon, meaning you have to have an instance of the supeclass to extend from.

It makes no sense to built the second story of your house prior to building the first story.


问:
Is there a name for a randomized heap?
I've made a container which functions like a Binary Heap in terms of insertions and popping the root element.  The key difference is that the comparison steps are all replaced with a random call for deciding when to go left/right.  (The underlying data structure is a Vector, written as an expandable array, so you don't need to know how many elements the heap will contain in advance.)  The idea is, you can insert items, and when you pop them, you'll get any element at random.  You can also iterate through the whole collection, after which the heap is reshuffled (by simply popping and reinserting N times).

Insertion and Removal are both O(log N), reshuffling is O(N log N).  Its main use is for games, think a deck of cards or a Bingo-tumbler.  It isn't really a true Heap in that there's no guarantee that elements will be less than or greater than their children.  But insertion and removal are both done Heap-style, just at random.  (Also, unlike a regular Heap, the items do not need to be comparable to eachother.)

Is there a standard name for this sort of thing?  Or maybe a better way of achieving the same results?  I'm calling it a "GrabBag" for now, since that seems to describe it pretty well, but I was just wondering if there was a more widely-recognized name for it.

I looked around for possible standard names for this, but couldn't find anything.  All I could find was either Randomized Meldable Heaps, which are a different thing, or people complaining about random heap corruption, which isn't even related.

答:
This need comes up a lot in game programming when you want to guarantee a certain probability distribution over time. For example, if the orc should hit 30% of the time, you create a Bag with 30 hits and 70 misses, in random order, then pop a value from the end of the array each time you need one.

Usually it is implemented as an array, so that creation is O(n) (i.e. insertion is O(1)) and removal are O(1). (No reshuffle is necessary; you just recreate it when you need a new one. Your reshuffle can be implemented by pushing each popped item into a new heap as you pop it, so these are similar.) The array solution is going to be a superior performer both in retrieval time unless you can't batch inserts.

Also, I am concerned about the actual randomness of your algorithm. Unless you randomly sink non-leaf nodes during insertion, earlier nodes are going to tend to be at the top of the tree.  Am I missing something?

Title: Is there a name for a randomized heap?


答:
You first create a cucumber and, by duck is a duck principle, it becomes a vegetable.

Except Java isn't a structurally (duck) typed language. It's a nominatively typed language.

If Java was a structurally typed language (or simply a dynamic one), then your mental picture of how it works would be good.

Since it is not, it needs to build the object layout in memory which is most efficiently done by layering the derived types around the base types (think Shrek's onion) so that the base type's layout can be reused for just the base type as well as its derived types.

Does it have to be that way? Not at all, and it often isn't for languages that are not nominatively typed (or can have multiple base types). But in Java it is, and frankly is one of the least onerous restrictions the language puts on you.

As for your question, you're getting pushback because you come off as a know-it-all who clearly does not. It's good to ask why, but to say that this design is completely stupid because it's causing you trouble (because you can't do object oriented design well) is ignorant at best.

And yes, if you're in a scenario where you want to do operations in the constructor before calling the base constructor that is a pretty solid indication that you're not so great at OOD.


问:
What's a good way to manage long piece of code in files?
I am a web developer and at the moment am finding it hard to cope with long un-documented code written by previous developers in an organisation I work for. With the deadline gun always pointed at my forehead, it's doing my head in. I use aptana studio's search feature for some quick wins but it is becoming overwhelming to a point that I do not want to work with them anymore.

Is there any quick/proven approach that I can take to help me with a scenario like this?

答:
The short answer:

The only way to go fast is to go well. - Uncle Bob

If you don't take the time to gradually make things better they will never be good. You do it bit by bit, day by day.

A rule that I find useful:

Find out where to make your code change

Take some time to do some changes to the existing code to make your change easier to implement

Implement you change

Usually this doesn't take longer than trying to implement the change directly but you check in something that is better than what you checked out.

If you haven't done it already I recommend you reading Clean code by Robert C. Martin


问:
C++ class with only pure virtual functions: what's that called?
So i'm looking for some input/consensus on what terminology we should be using to describe something that looks like this:

```<code>class Printable
{
  public:
    virtual void printTo(Printer *) = 0;
    virtual double getWidthInPoints() = 0;
    virtual double getHeightInPoints() = 0;
};
</code>```

So this is a class that only has pure virtual methods. Any class that inherits it needs to implement the whole thing, i.e. there is no partial implementation.

So what is this called?

I have mostly seen two different names:

1) Interface

Used in Windows COM programming (perhaps it came from the IDL), it's a keyword in both C# and Java and also a compiler directive/keyword in Objective-C (but isn't the same thing). I've heard engineers using the phrase 'interface' synonymously with 'API', but, at least in this scenario, it's a single thing whereas an API could comprises more than one.

2) Protocol

I've seen this used in various open-source libraries such as Bloomberg BSL and it's a compiler directive/keyword in Objective-C, but does not necessarily need to be in the inheritance hierarchy. In the broader computer science sense, protocol is a formal definition of information exchange between two parties, like TCP and HTTP, but this definition kind of holds for the above class too.

Is there any clear distinction between these in C++ or are they pretty much interchangeable?

答:
The technical term for a class with a pure virtual function is abstract class, but that terms also applies if the class has additional non-pure virtual functions.

Often the term Interface is used in C++ to describe an abstract class like Printable, that describes a service that can be provided by a range of different, otherwise unrelated classes. This corresponds to the use of the interface keyword in C#/Java.

I have never encountered the term 'protocol' in connection with a C++ class


问:
Where to put entity model classes in case of using a dataservice layer?
If my solution has both a "dataservice" project and a "business logic" project, where do the entity models, which represent database tables, belong?

At first i thought putting them in the dataservice layer, but then i would need duplicate models in the business logic layer, if i wanted to provide reusable logic dealing with or being dependant of database data.

Putting models in the business logic project, would force the dataservice layer to be dependant on the core project.

答:
Create a separate "Domain" project that contains your Domain Entities.

Important note:  Your Entities may not be the same thing as your datatables.

Your "DataService" project should know how to map from Domain Entities to datatables.


问:
Custom PHP Template Engine
I've been developing a custom PHP template engine to suit just my needs and also to get a little more practice with PHP.

What I did was to create a Template class that simply receives as constructor parameter a path to a template file and a string that should be the placeholder for the contents of the pages. In that case, the template file is an HTML file with some placeholders written as [placeholder]. These will be filled with real content by another class. So for instance, [title] should be filled with the title, [content] with the content of the selected page and so on.

I've created also a Page class that receives as constructor parameter the directory of the pages and then has methods to set which name of file it should use (this is filled in as we like in the initialization, when working with friendly URL's the most common way I use this is setting as the first piece of the URL) and methods to set more data as pairs of placeholder string and real content.

My only problem is with how to deal with titles and meta tags. For each page there's a title and a collection of meta tags. My only way to deal with this was to create in different files one array with titles and one array with meta tags. Both of them receives as index the name of the page file. So for instance $titles["home"] should be the title of the home page and $meta_tags["home"] should be the html code for the meta tags of the home page.

The problem is that as soon as there are lots of pages this will have one unecessary cost of memory: the system would be loading for every requests all the titles and all meta tags, while it must load only the required one. I thought on using database, but it seems like killing one ant with an atomic bomb. So the next best thing I thought of was XML.

Now, what's the best solution for this kind of situation? Use XML, use a MySQL database, or some other method?

As I've said, I know that the recommended is that we use the template engines that are already out there since they are tested lots of times, are already stable and so on, but I'm struggling with those things as a way to get more practice developing with PHP.

Thanks very much in advance for the help. Also, I didn't think it was needed to post any code I've written, but if some of the code will help, please ask and I'll post it.

答:
I cannot give you a specific code example for your problem but the general direction for your problem. If you use a template engine (self programmed or not), it should have the ability to parse templates based on method calls and the ability to assign variables (look for Smarty).

Example:

```<code>public function display($templateName, $sendHeaders = true) {
   $this->compile($templateName); // compiles the template language into php script

   if ($sendHeaders) //send Headers

   include($this->getCompiledFilename($templateName));
   exit;
}

public function assign($name, $value) {
    $this->v[$name] = $value;
}
</code>```

That being said you just use variables in the template for meta tags and the controller for the displayed page will first assign the variables and then display the template (via the template engine's methods).

An example for a template (you can combine multiple templates) would be:

```<code>{include file='header'}
{if $var1}
    <p>This is incredible.</p>
{/if}
{include file='footer'}
</code>```

I hope that I helped you.

Title: Custom PHP Template Engine

Body:
I cannot give you a specific code example for your problem but the general direction for your problem. If you use a template engine (self programmed or not), it should have the ability to parse templates based on method calls and the ability to assign variables (look for Smarty).

Example:

public function display($templateName, $sendHeaders = true) {
   $this->compile($templateName); // compiles the template language into php script

   if ($sendHeaders) //send Headers

   include($this->getCompiledFilename($templateName));
   exit;
}

public function assign($name, $value) {
    $this->v[$name] = $value;
}

That being said you just use variables in the template for meta tags and the controller for the displayed page will first assign the variables and then display the template (via the template engine's methods).

An example for a template (you can combine multiple templates) would be:

{include file='header'}
{if $var1}
    <p>This is incredible.</p>
{/if}
{include file='footer'}

I hope that I helped you.


问:
Who should be responsible to write test cases?
Should tests in some project be written by the actual person that does the coding (usually senior in our team) or it can be done by junior coders with less experience?</p>

答:
There is no single answer to this question. Obviously, if you're a business with a single developer then the developer should write the tests. If you're an organization of a thousand developers, the answer will be different.

Assuming a "normal" team with a few developers and possibly a few people dedicated to testing, it goes something like this:

developers write unit tests

developers and/or QA write integration tests

QA writes acceptance tests

In the scrum model, there is no distinction between "developer" and "QA". The team as a whole is responsible for the quality of the software, and the team decides on a case-by-case basis who should be doing the testing.

Many smart people think developers should write all their tests. I've worked in organizations like that, and we always delivered exceptionally high quality software. In those companies, not only should senior devs write tests, they must.

Other very smart people believe that developers should not test their own code because they have blinders on. "I don't need to test X, my changes couldn't possibly have affected it". To combat that you should always have someone else write the tests. I've worked in those types of organizations, and there, too, we also delivered  high quality code.

The bottom line is that if you're a developer, you are ultimately responsible for the quality of the code you produce. That means you should be writing tests -- regardless of organizational structure -- and if you have other team members, then you should work with them to make sure the code is properly tested.

In practical terms, the only people who can answer this for you is you and your team. It's perfectly reasonable for senior level programmers to write tests (and if they are good programmers, you won't ever have to ask them to do it because that's just part of the job). It's also perfectly reasonable for junior people to write tests -- this is a good way for them to learn the software.

In either case, there is no should. You should do whatever allows your team to create software with an appropriate level of quality.


答:
Edit: I read the title as unit tests:

I have heard this idea before, and IMHO I think it is a terrible idea to force unit testing solely on junior developers.

You would be creating an unnecessary division in your team.

Developers should write unit tests for their own code. Both the code and unit tests will then in the future be updated by other developers as features changes and bugs are discovered depending on resource availability.

Not trusting juniors with real features is not the best way to manage projects. Start them on smaller or easier features, let them unit test them, and they can work their way up to bigger, harder features.

Title: Who should be responsible to write test cases?

Body: Should tests in some project be written by the actual person that does the coding (usually senior in our team) or it can be done by junior coders with less experience?</p>


答:
I'm not sure if I've understood your problem correctly or not, but that seems to me that Loading the data is your problem, not anything else related to your template engine, right?

If yes, my questions is, where are the other contents of your application? I mean where is the page content? Put the meta tags, titles, etc. just where you have the other data.

If you're storing your page content in the database, then add these meta tags (whatever) to your database, load them when you loading the page content and then just pass them to your template engine.

If you have static pages, then add something like these to each page, and later you can grab it and pass it to your template engine:

```<code><?php
/* Sample.php */
$title = 'Sample Page';
$meta = 'whatever';
?>
<!-- Page Content -->
<h3>Welcome!</h3>
...
</code>```

P.S. BTW, such an array of titles and meta tags is not an issue for a real-world web server.

Title: Custom PHP Template Engine

Body:
I've been developing a custom PHP template engine to suit just my needs and also to get a little more practice with PHP.

What I did was to create a Template class that simply receives as constructor parameter a path to a template file and a string that should be the placeholder for the contents of the pages. In that case, the template file is an HTML file with some placeholders written as [placeholder]. These will be filled with real content by another class. So for instance, [title] should be filled with the title, [content] with the content of the selected page and so on.

I've created also a Page class that receives as constructor parameter the directory of the pages and then has methods to set which name of file it should use (this is filled in as we like in the initialization, when working with friendly URL's the most common way I use this is setting as the first piece of the URL) and methods to set more data as pairs of placeholder string and real content.

My only problem is with how to deal with titles and meta tags. For each page there's a title and a collection of meta tags. My only way to deal with this was to create in different files one array with titles and one array with meta tags. Both of them receives as index the name of the page file. So for instance $titles["home"] should be the title of the home page and $meta_tags["home"] should be the html code for the meta tags of the home page.

The problem is that as soon as there are lots of pages this will have one unecessary cost of memory: the system would be loading for every requests all the titles and all meta tags, while it must load only the required one. I thought on using database, but it seems like killing one ant with an atomic bomb. So the next best thing I thought of was XML.

Now, what's the best solution for this kind of situation? Use XML, use a MySQL database, or some other method?

As I've said, I know that the recommended is that we use the template engines that are already out there since they are tested lots of times, are already stable and so on, but I'm struggling with those things as a way to get more practice developing with PHP.

Thanks very much in advance for the help. Also, I didn't think it was needed to post any code I've written, but if some of the code will help, please ask and I'll post it.

Body:
I'm not sure if I've understood your problem correctly or not, but that seems to me that Loading the data is your problem, not anything else related to your template engine, right?

If yes, my questions is, where are the other contents of your application? I mean where is the page content? Put the meta tags, titles, etc. just where you have the other data.

If you're storing your page content in the database, then add these meta tags (whatever) to your database, load them when you loading the page content and then just pass them to your template engine.

If you have static pages, then add something like these to each page, and later you can grab it and pass it to your template engine:

<?php
/* Sample.php */
$title = 'Sample Page';
$meta = 'whatever';
?>
<!-- Page Content -->
<h3>Welcome!</h3>
...

P.S. BTW, such an array of titles and meta tags is not an issue for a real-world web server.


问:
Are PGP keys as good for certificates as X.509 keys?
I'm working on a decentralized transaction processing system that needs both authentication and general encryption, and I have a design decision to make: should I use PGP or X.509 certificates?

While the world tends to use X.509 for authentication (especially in browsers), they are based on the principle of having a central authority vouch for each certificate, meaning the system would need a CA and anyone who wants to participate in the system would need to have their keys signed by that CA.

PGP, on the other hand, is based on a "Web of Trust", where parties who want to communicate merely need to have any trusted party in common who will sign both keys. A CA isn't necessary in this case.

My overall design goals prefer the Web-of-Trust model, to keep the system decentralized, but I may also have customers who prefer a centralized model, and I don't want to prohibit that possibility. Is there anything stopping the Web-of-Trust principle from working with X.509? Likewise, is it easy and straightforward to mimic CAs in the PGP cryptosystem? Are they interchangeable in practice?

(For some reason, this is making me think of the false dichtomy: "I'm trying to bang in a nail, should I use a beer bottle or the heel of a shoe?")

答: PGP keyservers can act as an authoritative point of trust(similar to a CA).  The thing I like about PGP keys/keyservers is that I choose which sources to trust to build this web.  In most modern OSes and applications using x509/CA/web-browser model there are "chain of trust" issues where there are several ways to fool/break the chain.  Alternately, you can run your own CA, but if you do and someone with a signing certificate from an automatically imported one(an isp/foreign government for example) could break your chain of trust trivially.  You wouldn't even know.</p>

ContentLicense: CC BY-SA 2.5


问:
Pre-screening coding test - How long is reasonable?
EDIT

After a good amount of thinking and self-reflection on the topic, I realised that most of the issues I raised in this question was coming only from a personal, rather than a professional perspective. Hence the moderators put this question on hold because of the highly personal, subjective nature of the problem I tried to talk about. I was thinking about rephrasing the question but I could not really find a possible way to manifest the question in more objective way so it can be the subject of a discussion where answers can be back up with some sort of evidence or references.

For the sake of those who are still interested, I am trying to give a summary of the discussion emerged from this question:

a 4 hours pre-interview, offsite programming test is not usual but

many people pointed it out that for some companies you would interview for much-much longer than that all together

it is our personal decision if we take a test or not, and we can evaluate this based on our circumstances and the perceived benefits of getting hired for the company

all companies are different, as people are, and it can be perfectly reasonable for a company to employ a longer pre-interview offsite test, if that is what fits their needs or circumstances

I wanted my original question to be about how reasonable to expect 4 hours from me, and how ethical to give out a problem so the solution (not the code, but the design) can be possibly used for the company. As I can now see both of these questions can only (at best) be explored in a forum discussion, rather than using a question-answer type community tool like stackexchange.

However, I found all your answers valuable and thanks for sharing.

ORIGINAL POST

I am interviewing for several positions, and most of them include a pre-screening phase where I have to submit a coding test before the telephone interview or the onsite interview would take place. I have pretty much got used to this idea, and find it quite reasonable that companies expect me to do this so they can check what type of work I can produce on my own.

Generally, my experience is that these type of coding exercises are mostly small programming tasks. Do some logic, maybe implement a small algorithm, open a file and read/write data, stuff like that. Even the most simple task can be implemented with nice separation of logic, testable components, etc, to see how the candidate is coding, generally how well he is prepared for the type of job a company want to fill in.

Recently I came across a company who sent me a coding test with a whole page long description of their exercise, asking me to solve a real life problem of their business (I don't want to say specifics to protect the company, but the test was pretty much about what they do). They described a pretty complex system to implement, included real data, and in the end they concluded that the coding test should not take more than 4 hours.

Is it reasonable from a company to expect me to spend 4 hours working on their dummy assignment in my free time, even before they would say hi to me? (the recruiter sent me the coding test)

Don't get me wrong, I am motivated to find a new job and new challenges, but most companies expect me to spend maximum 1-2 hours on a task like that, and such tasks has always been far less complicated.

What I came up as a conclusion with this company is that either:

1) My motivation is not good and probably they are looking for someone else

2) They do not respect their future employees to expect such a long coding tests to do even without saying hi to them

3) They just want to give out one of the problems they work on and see if there is an enthusiastic young fella who would solve it for them for free (again, don't get me wrong I am not a conspiracy theorist but I have heard such stories ...)

How much do you think is reasonable for a company to expect candidates spend time on their dummy coding tests without talking to them? What is your experience generally?

答:
No, not typical, why are you solving their problems for free? (4 hours)

1 hour is typical for a programming test.  In the past our programming test was 4 questions. First 3 questions took 1/2 hour, last one 1/2 hour.  We also gave the test to existing hires in house to make sure we were in the expected timeframe and the test was fair and adjusted accordlingly.

The first few question(s) were "Fizz Buzz" type to weed out people who can't program.  They got progressively harder.  The last question was a problem solving exercise.  Generally we tried to limit the amount of code written to around a few hundred lines (total) and not require any clever tricks.  We also scored people on error handling, style, syntax, organization, etc.   The questions were not related to our business but rather the skills and technology that the current platform was written in.

Typically, great candidates finished in less time than was allotted.  Sometimes people requested extra time which we allowed because of the stress involved in taking a quiz, but we capped everyone at a certain limit.  The quiz was in the current development environment and people had access to the internet for reference information.  We also went over the expectations of the quiz to every candidate.

At one time we did discuss incorporating our code base (real world) into the quiz but we eventually discarded that due to concerns that code copied off/stolen/etc (our boss was a bit paranoid).   Eventually we just went with a separate quiz.sln in an isolated development machine.

Finally, we found it was hard to come up with a test that was fair, but neither too hard nor too easy.  We always asked our candidates about the quiz after they took it and garnered their feedback to refine it for future candidates.


答:
According to this topic you are not the first one who is looking for that algorithm. As already mentioned Progress is not willing to share much about this algorithm.

While it's most probably possible to do crack the algorithm, it's generally easier to use Progress itself to calculate hashes. The other option is to switch from using that Progress funtion to a more standard variants (like SHA-1).

Now, more clarification of what "variation" could possibly mean. Suppose something like:

```<code>string Encode(string pass) {
    string salt = "123456";
    return CRC16(pass + salt); // + for catenation
}
</code>```

while it's still same CRC16 it will produce totally different results (comparing to CRC16(pass)). So the only way to get real algorithm is to use disassembler to see the actual code, since it's probably impossible to do anything observing only input and output.

There is no "structural approach" to guess algorithm from input and result unless you have a pattern, and that's exactly that ideal hash need not to have.

Title: How can I reverse engineer a hash code?

Body:
According to this topic you are not the first one who is looking for that algorithm. As already mentioned Progress is not willing to share much about this algorithm.

While it's most probably possible to do crack the algorithm, it's generally easier to use Progress itself to calculate hashes. The other option is to switch from using that Progress funtion to a more standard variants (like SHA-1).

Now, more clarification of what "variation" could possibly mean. Suppose something like:

string Encode(string pass) {
    string salt = "123456";
    return CRC16(pass + salt); // + for catenation
}

while it's still same CRC16 it will produce totally different results (comparing to CRC16(pass)). So the only way to get real algorithm is to use disassembler to see the actual code, since it's probably impossible to do anything observing only input and output.

There is no "structural approach" to guess algorithm from input and result unless you have a pattern, and that's exactly that ideal hash need not to have.


问:
Using multiple Git repositories instead of a single one containing many apps from different teams?
I am migrating a 10-years-old big CVS repository to Git. It seemed obvious to split this multiple-projects repository into several Git ones. But the decision-makers are used to CVS, therefore their point of view is influenced by CVS philosophy.

To convince them to migrate from one CVS repo to different Git repositories I need to give them some arguments.

When I speak with mates working on Git repo for years, they say that using multiple Git repo is the way to use Git. I do not know really why (they give me some ideas). I am a newbie in this field so I ask here my question.

What are the arguments to use multiple Git repositories instead of a single one containing different applications and libraries from different teams?

I have already listed:

branches/tags impact the whole Git repository files => pollutes other team projects

4GB limit Git repo size but this is wrong

git annotate may be slower on bloat Git repo...

Eamon Nerbonne has noticed the related question:

Choosing between Single or multiple projects in a git repository?

The reason the team managers finally have accepted the split: the single Git repo (550 MB) was requiring 13 minutes to be cloned on Windows (one minute on Linux).

The bloat CVS repo split in 100 Git repositories:

each dead apps in one repo

each stabilized library in one repo (source code almost never changed any longer)

related apps/libs kept together in one repo

moved large files not used for compilation (config...) to other repos (Git does not like large files)

skipped other unrelevant files (*.jar, *.pcb, *.dll, *.so, *.backup ...)

Successfully installed the repo tool used by Android Open Source Project in order to handle all these Git repos:

easy installation on Linux

more difficult on Windows because of Cygwin and NTFS native symlinks requirements

答:
If you're willing to play ball with them in order to appease, you could set it up this way. Or this method. Other than that, I think they're just expecting a single point of entry into the system to access assets.

Depending on access needs, the separated GIT repos might still be the better way to go, as "John Smith" may need access to certain data, but not other data. While "Suzy Que" may be a sys admin needing access to everything.

If you go with a single repo, you might run into issues with your internal access requirements. If it's an "everybody gets full access" type of thing, then I could possibly see their point of view.


答:
I find coding tests in interview are a load of tosh anyway. No-one codes anything but the simplest routine under pressure without the usual environment and tools, so the results you get are dubious at best.

What I have found to be really good tests of a programmer's ability is to give him some project code and ask him to review it, this works really well if the code has several obvious bugs, several obvious code issues, and a few questionable practices. A good coder will tell you all of them, and will engage with you in discussion of why some code isn't 'wrong' but could be done better to ease maintenance or so. A poor programmer will find a bug and stop.

Any job that expects you to do a test that takes more than half an hour just hasn't spent even that long working out a good, targetted test that provides them with more than a vague idea of your skills. (most companies find it very hard to spend any time working on pre-interview setup).

If I was given a test like you'd got, I'd write the answer in pseudo-code. That should be enough to demonstrate my understanding of coding and design, without going through the entire compile, build and test phases you would for a normal work project.

Title: Pre-screening coding test - How long is reasonable?

Body:
EDIT

After a good amount of thinking and self-reflection on the topic, I realised that most of the issues I raised in this question was coming only from a personal, rather than a professional perspective. Hence the moderators put this question on hold because of the highly personal, subjective nature of the problem I tried to talk about. I was thinking about rephrasing the question but I could not really find a possible way to manifest the question in more objective way so it can be the subject of a discussion where answers can be back up with some sort of evidence or references.

For the sake of those who are still interested, I am trying to give a summary of the discussion emerged from this question:

a 4 hours pre-interview, offsite programming test is not usual but

many people pointed it out that for some companies you would interview for much-much longer than that all together

it is our personal decision if we take a test or not, and we can evaluate this based on our circumstances and the perceived benefits of getting hired for the company

all companies are different, as people are, and it can be perfectly reasonable for a company to employ a longer pre-interview offsite test, if that is what fits their needs or circumstances

I wanted my original question to be about how reasonable to expect 4 hours from me, and how ethical to give out a problem so the solution (not the code, but the design) can be possibly used for the company. As I can now see both of these questions can only (at best) be explored in a forum discussion, rather than using a question-answer type community tool like stackexchange.

However, I found all your answers valuable and thanks for sharing.

ORIGINAL POST

I am interviewing for several positions, and most of them include a pre-screening phase where I have to submit a coding test before the telephone interview or the onsite interview would take place. I have pretty much got used to this idea, and find it quite reasonable that companies expect me to do this so they can check what type of work I can produce on my own.

Generally, my experience is that these type of coding exercises are mostly small programming tasks. Do some logic, maybe implement a small algorithm, open a file and read/write data, stuff like that. Even the most simple task can be implemented with nice separation of logic, testable components, etc, to see how the candidate is coding, generally how well he is prepared for the type of job a company want to fill in.

Recently I came across a company who sent me a coding test with a whole page long description of their exercise, asking me to solve a real life problem of their business (I don't want to say specifics to protect the company, but the test was pretty much about what they do). They described a pretty complex system to implement, included real data, and in the end they concluded that the coding test should not take more than 4 hours.

Is it reasonable from a company to expect me to spend 4 hours working on their dummy assignment in my free time, even before they would say hi to me? (the recruiter sent me the coding test)

Don't get me wrong, I am motivated to find a new job and new challenges, but most companies expect me to spend maximum 1-2 hours on a task like that, and such tasks has always been far less complicated.

What I came up as a conclusion with this company is that either:

1) My motivation is not good and probably they are looking for someone else

2) They do not respect their future employees to expect such a long coding tests to do even without saying hi to them

3) They just want to give out one of the problems they work on and see if there is an enthusiastic young fella who would solve it for them for free (again, don't get me wrong I am not a conspiracy theorist but I have heard such stories ...)

How much do you think is reasonable for a company to expect candidates spend time on their dummy coding tests without talking to them? What is your experience generally?


答:
Ideally, in test driven design, the test is written before a single line of code is written.  Someone writes the failing test, someone writes the code (that passes).

In this model, it doesn't matter too much who writes the test (or who does the code).  What is required is that the test accurately describes the functionality to be written before writing code.  If this understanding of the requirements requires a senior programmer, then that is who writes it.

However, once the test is written, if it was well written, anyone should be able to write the code for it that passes the test.  If anything, this points to that seniors should be writing the all tests and then delegating out the coding of the guts of the code to other people who can do it.

After the fact unit testing is.. less than ideal.  Unfortunately, when this happens this is often left to the juniors to "get the required coverage."  Such endeavors are often difficult because they are tedious and don't fully test the code in question (leaving bugs that get scapegoated on the person who wrote the test for not catching it).

It is great having junior programmers gain experience with the code base.  Forcing them to write after the fact unit testing isn't the way to do it.


答:
Let me take the company's side for a moment, since the other answers haven't so far.  It would be nearly impossible to build a usable code base out of a conglomeration of 4-hour coding test submissions from people whose qualifications are completely unknown.  Creating a detailed enough specification, vetting the responses, and integrating it with the rest of your code would take longer than 4 hours.  Not to mention most useful enterprise-level software projects require thousands of man hours.  The thought of building a business on splitting that out into 4-hour increments with weeks of turnaround time each is frankly ridiculous.

Giving a real life problem of the business is one of the best ways to determine if someone will be good at, shockingly, solving real life problems of the business.  I do this frequently in interviews (although I ask for general design principles and not 4 hours worth of code), and every single time it has been a problem I have already solved.  If I hadn't already solved it, the test would lose almost all probative value.

Whether a 4-hour test is worth it to you is a personal decision.  I was always taught to treat looking for full-time work as a full time job.  When you're unemployed or underemployed and spending 8 hours a day looking for work, a 4-hour coding test is nothing.  I've spent far longer than that on tasks like brushing up on rusty languages, writing portfolio programs, and customizing resumes for specific positions.

On the other hand, some of the best workers are already gainfully employed, and only casually looking for better opportunities.  People in that situation are unlikely to go through the rigamarole of a 4-hour test, unless the opportunity is stellar.  However, that's the company's problem, not yours.

As far as discerning what it means about the company's attitude toward their employees, I don't think you can really say anything either way, other than they are probably tired of dealing with unqualified applicants, to a degree that they're willing to throw out some of the good with the bad.


问:
when is it necessary or when should a controller be async
When is it absolutely necessary for a controller to be async? Should all controllers be async or is it bad practice to make all of them async unless it is necessary.
Just looking for some general guidelines. </p>

答:
It's never absolutely necessary for a controller to be async. Calls to controller methods will eventually return.  However, it might be desirable to hand off a long-running task to a thread, so that the web server is not blocked for a long period of time.

I wouldn't bother making every controller asynchronous.  There is some overhead involved in creating new threads; making every controller asynchronous might actually slow things down.

Use asynchronous action methods for long-running, non-CPU bound
  requests. This avoids blocking the Web server from performing work
  while the request is being processed. A typical use for the
  AsyncController class is long-running Web service calls.

http://msdn.microsoft.com/en-us/library/ee728598(v=vs.100).aspx


答:
The idea behind using templates (and a template engine) is that you separate the (dynamic) content producing code from the code that is responsible for the visual appearance of the page. To make this separation successful, the application code should not be aware the fact that title and meta tags go in the HTML  element, while the rest of the content goes into the  element. In fact, the application should not even care if the templates produce HTML code or something completely different.

To facilitate the separation between application and template, the template engine should provide a mechanism where the application can provide replacement content without knowing where the placeholder for that replacement will occur in the templates. This also makes it possible to completely restructure the templates without any change to the application code.

Title: Custom PHP Template Engine

Body:
The idea behind using templates (and a template engine) is that you separate the (dynamic) content producing code from the code that is responsible for the visual appearance of the page. To make this separation successful, the application code should not be aware the fact that title and meta tags go in the HTML <head> element, while the rest of the content goes into the <body> element. In fact, the application should not even care if the templates produce HTML code or something completely different.

To facilitate the separation between application and template, the template engine should provide a mechanism where the application can provide replacement content without knowing where the placeholder for that replacement will occur in the templates. This also makes it possible to completely restructure the templates without any change to the application code.


问:
What are the best practices for rapid prototyping using exclusively HTML/CSS/JS
I'm developing a prototype of a web application. I want to only use HTML, CSS and Javascript. I prefer to use my text editor and not having to learn (or pay, for that matter) a new tool like Axure.

What would be, to your mind, the best practices? To me there are many qualities for a good prototype:

Quickly developed

Easy to improve

Fair fidelity as regards UX (this disqualifies tools like Omnigraffle or PowerPoint that are more dedicated to wireframing)

I trying to learn as quickly as possible, but I would like to know, based on your experience, on how you managed to be both quick and agile.

Reference:

http://www.boxesandarrows.com/view/prototyping-with

答:
Have you considered Twitter's Bootstrap or Yahoo's Pure?

Both are very, very easy to get up and running with, and you can make some pretty complex interfaces just with what you get "out of the box".

I've used Bootstrap for prototyping for a long time, and more often than not, the same bones of the prototype make their way in to the finished product.


问:
I have to compromise: DRY, or Command-Query-Separation?
I was recently refactoring a method that was both a command and a query method.

After separating it into a one command method and one query method, I found that there are now multiple places in the code where I am calling the command then getting the value from the query, which seems like a violation of the DRY principle.

But if I were to wrap that common code into a method, that method would be both command and a query. Is this acceptable?

答:
There are always trade offs to consider between conflicting design principles.  The way to resolve it is to look at the underlying reasons behind the principles.  In this case, being unable to run a query without running the command is problematic, but being unable to run a command without running the query is generally harmless.  As long as there's a way to run the query standalone, I see no reason not to add the query result to the command, especially if done something like this:</p>

```<code>QueryResult command()
{
   // do command stuff
   return query();
}
</code>```

Body:
There are always trade offs to consider between conflicting design principles.  The way to resolve it is to look at the underlying reasons behind the principles.  In this case, being unable to run a query without running the command is problematic, but being unable to run a command without running the query is generally harmless.  As long as there's a way to run the query standalone, I see no reason not to add the query result to the command, especially if done something like this:

QueryResult command()
{
   // do command stuff
   return query();
}


问:
Do I have to release source code because I'm using JavaFX?
I'm using JavaFX for gui of my app. Its license is GPL+Linking Exception. GPL requires me to release my source code. But what's the linking exception??  (I'm just using it as a library. Not modifying or using its source code.)</p>

答:
No. JavaFX is licensed under the same license as Java SE: JavaFX FAQ -> 10. What type of license is JavaFX available under?

JavaFX is available under the same license and business model as Java SE. This includes the ability for third party developers to distribute the runtime librairies with their application(s), subject to the terms and conditions of the license...

However, JavaFX source code is licensed differently: JavaFX FAQ -> 4. Is JavaFX open source?

At this time, the JavaFX UI Controls source code has been contributed to the OpenJFX open source project; other JavaFX components are expected to follow in multiple phases. The code is available under the GPL v2 with Classpath Exception license, similar to other projects in OpenJDK. The Oracle JavaFX runtime and SDK implementations will continue to be released under the Oracle Binary Code License for the Java SE Platform...

OwnerDisplayName: Ehsan


问:
What's the best way to manage list item sort order with Drag & Drop UI?
I have a list of Students that I should display to user on a web page in tabular format.

The items are stored in DB along with SortOrder information.

On the web page, user can rearrange the list order by dragging and dropping the items to their desired sort order, similar to this post.

Below is a screenshot of my test page.

In the above example, each row has sort order info attached to it. When I drop John Doe (Student Id 10) above the Student Id 1  row, the list order should now be: 2, 10, 1, 8, 11.

What's the optimistic (less resource hungry) way to store and update Sort Order information?

My only idea for now is, for every change in the list's sort order, every object's SortOrder value should be updated, which in my opinion is very resource hungry.

Just FYI: I might have at most 25 rows in my table.

答:
I have think of something, which can reduce your queries. Here in my example, I have added a new column for sorting named pos. So, initially without any dragging your table will be like -

Now, Lets consider that you dragged the Item 4 between Item 1 & Item 2. Now, new pos value for Item 4 will be (20 + 10) / 2, which is 15. So, You will only need to update a single row in database. And, you will get -

Here is a flowchart with the edge cases. i is the new array index of your row after dragged -

This flowchart doesn't handle ArrayOutOfBound checks. And, for edge cases you will need more than one query.

Since you have only 25 rows, you can take a very big value (e.g. 10,000) for the pos difference (I took 10 for this example). The bigger the value is, the less it will collide.


问:
What are non-programming mistakes that a programmer should avoid?
People make mistakes, even in the real life... Which should we, geeky programmers, avoid?</p>

答:
Spare normal people from any unnecessary technical details. They don't care.

And don't drool on your female coworkers.


问:
Why are most browsers developed in C++
It seems like most of common web browsers (Firefox, Chrome, Safari) are developed using C++. Whys is that so?</p>

答:
Legacy compatibility - can't throw away old code

It has nothing to do with the merits of C++ vs other languages. You can surely write a better browser from scratch in a language like Haskell; a project this important could even implement their own JVM if they needed to guarantee some performance characteristics. Like how Facebook wrote their own PHP compiler/optimizer.

A browser that breaks on non-standard markup is worse than useless. Legacy compat is so critical and so complex that a rewrite is just not an option. Lots of money and time is invested in battle-tested security etc, you can't just throw that investment away. Again, like how Facebook is still written in PHP.

Title: Why are most browsers developed in C++


问:
British royal succession algorithm
I was reading about the rules for royal succession of the British monarchy and thought the easiest way I could understand it is with code (or pseudo-code).  I came up with this (in a C# like pseudo-code):

```<code>EventHandler CurrentMonarch_Died {
    CurrentMonarch = SuccessorRootedAt(Person.Electress_Sophia_Of_Hanover);
}

enum Gender { Male, Female };  // Male must come before Female

Person SuccessorRootedAt(Person person) {
    if (person.IsAlive && IsQualified(person.Religion, person.Citizenship))
        return person;

    sortedChildren = person.Children.OrderBy(p => p.Gender).ThenBy(p => p.DateOfBirth);

    foreach (child in sortedChildren) {
        successor = SuccessorRootedAt(child);
        if (successor != null)
            return successor;
    }

    return null;
}
</code>```

Is it correct?

答:
Close, but if you analyse history, it's more like:

```<code>Person SuccessorRootedAt(Person person) {
  if(!rand%100) //Reality simulator
  {
    if (person.IsAlive && IsQualified(person.Religion, person.Citizenship))
      return person;

    sortedChildren = person.Children.OrderBy(p => p.Gender).ThenOrderBy(p => p.DateOfBirth);

    foreach (child in sortedChildren) {
      successor = SuccessorRootedAt(child);
      if (successor != null)
        return successor;
  }
  else
  {
    return rand();
  }
}
</code>```

And yes, it occasionally causes a whole mess of trouble.

Title: British royal succession algorithm

Body:
Close, but if you analyse history, it's more like:

Person SuccessorRootedAt(Person person) {
  if(!rand%100) //Reality simulator
  {
    if (person.IsAlive && IsQualified(person.Religion, person.Citizenship))
      return person;

    sortedChildren = person.Children.OrderBy(p => p.Gender).ThenOrderBy(p => p.DateOfBirth);

    foreach (child in sortedChildren) {
      successor = SuccessorRootedAt(child);
      if (successor != null)
        return successor;
  }
  else
  {
    return rand();
  }
}

And yes, it occasionally causes a whole mess of trouble.


答:
(I've been working on Firefox for about five years.)

The questioner is right that a lot of Firefox's code is C++, and in fact C++ is the majority if you count by lines of code (although that doesn't tell the whole story, since we have a lot of JavaScript, and JS is more concise than C++).

But in reality, Firefox is written in a lot of different languages:

C++

C (NSS, NSPR, various libraries we've imported)

x86 and ARM assembly

JavaScript

XUL (an HTML-like markup language) and CSS

Objective C (MacOS-only code)

Java (Android-only code)

Multiple custom interface-definition languages (XPIDL, IPDL)

WebIDL (another interface-definition language, but this one isn't custom, although the code generator is)

Python (code generators)

I sure am forgetting some.

This list is important because it hints at the incredible complexity that sits behind a web browser.

Yes, Firefox has a lot of C++ code, and yes, that has something to do with the fact that C++ was the best language for this sort of thing when Netscape was founded.  But I also contend that there exists no better language today for a lot of what we do.

No other language has as strong an ecosystem of libraries (we rely heavily on external code).  Few other languages give you full-stack control like C++ (we regularly tweak our custom heap allocator and do all sorts of memory-unsafe things to be faster or use less memory).  Few other languages let you re-implement most of the standard library in a sane way (we have our own strings and collections implementations, tuned to our needs).  Few other languages let you implement your own garbage collector.  And so on.

Although C++ is the obvious choice for a lot of what we do, the people who suggest that we could write a browser in Java and write our own JVM if necessary are on to something.  This is essentially what we do, but with JavaScript instead of Java.  Of course, much of the browser isn't written in JavaScript.  But a surprising amount is.

Title: Why are most browsers developed in C++

Body: It seems like most of common web browsers (Firefox, Chrome, Safari) are developed using C++. Whys is that so?</p>


问:
How PHP manages memory in this case?
If I have a file config.php with some configurations in some variables and in some page I include this file, each time the variables will be loaded again in the memory of the server?

I think the answer is yes, but I'm not sure, I don't know to much of the PHP lifecycle. I don't know if I made myself clear, so here is an example. Suppose, I have the config.php file as:

```<code><?php
     $databaseConfig = array();
     /* Sets the configurations inside the array */
?>
</code>```

Then my index.php page includes the file config.php. Each time the index is loaded the $databaseConfig array will be loaded into memory or just the first time and so when the page is requested again it doesn't need to load it again? I really think that since PHP is stateless it will load again each time.

答:
The file is reloaded and re-parsed at each request. (That may or may not mean it's loaded from disk.) Installing something like APC generally ensures you don't hit the disk or take the parsing hit each time.

The code is re-executed entirely with each request, even if the bytecodes are cached. So, any variable, including $databaseConfig, is rebuilt with each request. If it comes with notable overhead, you can also use something like APC to cache it in memory.

Title: How PHP manages memory in this case?


答:
I haven't heard of Command-Query-Separation(CQS) before, but it seems that it would relate to Single Responsibility Principle(SRP), which states that a function/class ideally should be responsible for doing one thing and one thing only.

If your command code is 20 lines of code and query code is another 30 lines and they are all in one function body, clearly you are violating SRP and I'd assume CQS as well and those two pieces of logic should be separated from each other.

However, going with your hypothetical example, I would most likely create a wrapper method that would combine your command and query so that DRY isn't violated in numerous places in the code.  I'd also wouldn't consider this to be SRP (and maybe CQS) violation, because the wrapper still has only one responsibility: to combine command with a query and create a higher level abstraction that is easier to consume.

I think wrapper method is perfectly acceptable solution and to illustrate that, let's take your example one step further.  What if you had to run 2 queries instead of 1 and then do a command action based on that.  So your 2 lines of code would be 6 or 8.  What if there was some data validation/checking between one and the other, so now you have 15 lines of code.  Would you think twice about creating a wrapper that does all that, rather than sprinkling those 15 lines in multiple files?

Title: I have to compromise: DRY, or Command-Query-Separation?

Body:
I was recently refactoring a method that was both a command and a query method.

After separating it into a one command method and one query method, I found that there are now multiple places in the code where I am calling the command then getting the value from the query, which seems like a violation of the DRY principle.

But if I were to wrap that common code into a method, that method would be both command and a query. Is this acceptable?