问:
MVC View Question
In my PHP web page (index.php), I have a simple script that calls a "page" class, and then builds the page from it.

Index.php executes methods within an instance of the 'page' class, such as "add_to_body("bla bla bla")". It can then call a "build()" method, where the page class will return a string with the user input and some other HTML elements pre-added in, that index.php can echo. Essentially the page class is a template of sorts.

I'm trying to have some kind of MVC hierarchy here (I'm a student learning about programming 'best practices' in my own time), my question is: would 'index.php' be a view? Or, would the instance of the page class be the view (as it constructs the page, but it doesn't actually show it, it returns a string), or: would the 'page' class be a controller?

Also, is a view 'allowed' to talk to (eg: get data from) a controller (for example: by calling a method that controller owns)?

Many thanks for your help!

答:
Also, is a view 'allowed' to talk to (eg: get data from) a controller (for example: by calling a method that controller owns)?

Best practice is no, but a controller is allowed to pass a data to the view. Check out templating engines like Mustache.

I'm trying to have some kind of MVC hierarchy here (I'm a student learning about programming 'best practices' in my own time), my question is: would 'index.php' be a view? Or, would the instance of the page class be the view (as it constructs the page, but it doesn't actually show it, it returns a string), or: would the 'page' class be a controller?

Usually index.php become the front controller, or the bootstrap.

You create some folders: library, controllers, models, and views, then you load all them from the index.php.

Then you make a Route class in your libraries folder, that should be able parse the PHP REQUEST_URI into a controller class name, method name, and an array of parameters.

In your index.php, you could instantiate a new Route with the PHP REQUEST_URI to it, then you call the Route::build method, that should be able instiate a controller then call it's method that correspond to the parsed PHP REQUEST_URI. (Learn about call_user_func_array).

The controller's method will returns a string (from a view file, or whatever), then you could just print it to the browser.

Here i'll just give you a minimum example of MVC in PHP:

core.php

```<code><?php

class Route
{
  protected $class;

  protected $method;
  protected $params = array();

  /**
   * Parse the given URI, if the URI is "site/article/10", then "site" will be
   * the controller class, "article" will be the method, and "10" will be
   * the parameter.
   */
  function __construct($uri)
  {
    $segments = explode('/', $uri);

    foreach ($segments as $segment)
    {
      if ($this->class === NULL)
      {
        $this->class = ucfirst($segment);
      }
      else if ($this->method === NULL)
      {
        $this->method = $segment;
      }
      else
      {
        $this->params[] = $segment;
      }
    }
  }

  /**
   * Instantiate a controller class then execute the method with the parameters from
   * the parsed REQUEST_URI.
   */
  function call(Database $database)
  {
    $controller = new $this->class($database);

    $response = call_user_func_array(array($controller, $this->method), $this->params);

    return $response;
  }
}

class Controller
{
  function __construct(Database $database)
  {
    $this->database = $database;
  }

  /**
   * Instantiate a model
   */
  function model($name)
  {
    $model = new $name($this->database);

    return $model;
  }
}

class View
{
  protected $data = array();
  protected $path;

  function __construct($path, array $data = array())
  {
    $this->path = $path;
    $this->data = $data;
  }

  function render()
  {
    // Extract the data so you can access all the variables in
    // the "data" array inside your included view files
    ob_start(); extract($this->data);

    try
    {
      include $this->path;
    }
    catch(\Exception $e)
    {
      ob_end_clean(); throw $e;
    }

    return ob_get_clean();
  }

  /**
   * Make it able for you to write a code like this: echo new View("home.php")
   */
  function __toString()
  {
    return $this->render();
  }
}

class Model
{
  protected $database;

  function __construct(Database $database)
  {
    $this->database = $database;
  }
}

class Database
{
  function __construct()
  {
    // Connect to the database, for example: mysql_connect($host, $user, $pass, $data)
  }

  function query($sql)
  {
    // Do some database query like usual, for example: mysql_query($sql)
  }
}
</code>```

index.php:

```<code><?php

require "core.php"

class Article extends Model
{
  function find($id)
  {
    // You execute query through $this->db->query("SELECT..."), but i'll just use an array
    // to simplify things.
    return array("title" => "Article", "body" => "Lorem Ipsum");
  }
}

class Site extends Controller
{
  function article($id)
  {
    $article_model = $this->model("Article");

    // This is how you use the view class!
    $view = new View("article.php", array("article" => $article_model->find($id)));

    return $view;
  }
}

// This is where everything starts
$route = new Route("site/article/10");
echo $route->call(new Database());
</code>```

article.php:

```<code><h1><?php echo $article['title'] ?></h1>
<p><?php echo $article['body'] ?></p>
</code>```

Put article.php, index.php, and core.php in one folder then run the index.php from your browser.

Title: MVC View Question

Body:
Also, is a view 'allowed' to talk to (eg: get data from) a controller (for example: by calling a method that controller owns)?

Best practice is no, but a controller is allowed to pass a data to the view. Check out templating engines like Mustache.

I'm trying to have some kind of MVC hierarchy here (I'm a student learning about programming 'best practices' in my own time), my question is: would 'index.php' be a view? Or, would the instance of the page class be the view (as it constructs the page, but it doesn't actually show it, it returns a string), or: would the 'page' class be a controller?

Usually index.php become the front controller, or the bootstrap.

You create some folders: library, controllers, models, and views, then you load all them from the index.php.

Then you make a Route class in your libraries folder, that should be able parse the PHP REQUEST_URI into a controller class name, method name, and an array of parameters.

In your index.php, you could instantiate a new Route with the PHP REQUEST_URI to it, then you call the Route::build method, that should be able instiate a controller then call it's method that correspond to the parsed PHP REQUEST_URI. (Learn about call_user_func_array).

The controller's method will returns a string (from a view file, or whatever), then you could just print it to the browser.

Here i'll just give you a minimum example of MVC in PHP:

core.php

<?php

class Route
{
  protected $class;

  protected $method;
  protected $params = array();

  /**
   * Parse the given URI, if the URI is "site/article/10", then "site" will be
   * the controller class, "article" will be the method, and "10" will be
   * the parameter.
   */
  function __construct($uri)
  {
    $segments = explode('/', $uri);

    foreach ($segments as $segment)
    {
      if ($this->class === NULL)
      {
        $this->class = ucfirst($segment);
      }
      else if ($this->method === NULL)
      {
        $this->method = $segment;
      }
      else
      {
        $this->params[] = $segment;
      }
    }
  }

  /**
   * Instantiate a controller class then execute the method with the parameters from
   * the parsed REQUEST_URI.
   */
  function call(Database $database)
  {
    $controller = new $this->class($database);

    $response = call_user_func_array(array($controller, $this->method), $this->params);

    return $response;
  }
}

class Controller
{
  function __construct(Database $database)
  {
    $this->database = $database;
  }

  /**
   * Instantiate a model
   */
  function model($name)
  {
    $model = new $name($this->database);

    return $model;
  }
}

class View
{
  protected $data = array();
  protected $path;

  function __construct($path, array $data = array())
  {
    $this->path = $path;
    $this->data = $data;
  }

  function render()
  {
    // Extract the data so you can access all the variables in
    // the "data" array inside your included view files
    ob_start(); extract($this->data);

    try
    {
      include $this->path;
    }
    catch(\Exception $e)
    {
      ob_end_clean(); throw $e;
    }

    return ob_get_clean();
  }

  /**
   * Make it able for you to write a code like this: echo new View("home.php")
   */
  function __toString()
  {
    return $this->render();
  }
}

class Model
{
  protected $database;

  function __construct(Database $database)
  {
    $this->database = $database;
  }
}

class Database
{
  function __construct()
  {
    // Connect to the database, for example: mysql_connect($host, $user, $pass, $data)
  }

  function query($sql)
  {
    // Do some database query like usual, for example: mysql_query($sql)
  }
}

index.php:

<?php

require "core.php"

class Article extends Model
{
  function find($id)
  {
    // You execute query through $this->db->query("SELECT..."), but i'll just use an array
    // to simplify things.
    return array("title" => "Article", "body" => "Lorem Ipsum");
  }
}

class Site extends Controller
{
  function article($id)
  {
    $article_model = $this->model("Article");

    // This is how you use the view class!
    $view = new View("article.php", array("article" => $article_model->find($id)));

    return $view;
  }
}

// This is where everything starts
$route = new Route("site/article/10");
echo $route->call(new Database());

article.php:

<h1><?php echo $article['title'] ?></h1>
<p><?php echo $article['body'] ?></p>

Put article.php, index.php, and core.php in one folder then run the index.php from your browser.


问:
VPS vs Web Hosting: Which one is good for java web services
I have some questions about VPS and web hosting.

As far as I understand, VPS is a virtual machine on which we can do anything as we can do with our local machine. Install software, change settings etc.

Web hosting is where we have only a folder in which we place our web site in.

However, most of the provider currently advertise their service as "VPS web hosting". This confuses me, does that mean they are selling VPS service which can only host web sites?

I need a virtual machine which host one RESTful Java service using Tomcat and Jersey and MYSQL at the backend. My plan was to hire a VPS machine, install Tomcat 7 and MySQL on that machine. Is this the right way to go?

Many thanks.

答: I recommend you rent a VPS with root access. They're really cheap and you can easily make changes to the systems if your requirements ever change. Most companies provide pre-configured VPS running Linux distributions (Ubuntu, Debian or CentOS are most common) or Windows Server. Just make sure there's root access and you're fine.</p>

ContentLicense: CC BY-SA 3.0


问:
Do Windows Installers for internal business applications make sense?
I'm trying to build a general understanding for what's common in this situation so that I can decide if it makes sense to pursue it further.

Are installers welcome in a typical corporate environment with the following?

Change control process

Dev/QA/Production environments

Designated deploy teams for various areas (firewall, database, windows, etc.).

Is there a "litmus test" that could be applied to an application to see if it is a good candidate for creating an installer? *

Are installers simple enough that every application should have one?

Are installers even the right tool?

Is it reasonable to expect developers to learn something like WiX to support installers?

Maintainability in general is a concern, i.e., is creating an installer a niche skill?

*

For example, I have a set of winform applications that are in a shared directory on a production server.  Specific groups can run the applications from this directory but only system admins can modify the executables.  The current deploy process involves having an admin copy/paste the executables and libraries to the shared directory.

Since the applications are not installed on the individual users' machine, does it make sense to create an installer for deploying new versions of these applications to the shared directory?

Edit--

I felt that the answers here gave some solid advice so I wanted to share what I came up with for my current project where I needed to build a large number of applications and deploy them to individual folders.

I found a NuGet package called _PublishedApplications that mimics the behavior of _PublishedWebsites for web projects.  The idea is you install the NuGet package to your projects and it adds a target that will copy the build artifacts to a _PublishedApplications directory in the output path.  This behavior is activated by running MSBuild from the command line and specifying an outdir property:

```<code>msbuild /p:Configuration=Release /p:outdir=C:\path\to\outdir MySolution.sln
</code>```

This will give you a directory structure similar to the following:

C:\path\to\outdir

_PublishedApplications\

Project1\

dlls, exes, etc.

Project2\

...

From there, creating a zip that can be extracted in the various environments is fairly painless.

答:
Windows Installer applications are widely used to install internal business applications in environments using Windows.  You should also ask yourself whether over the application's life it will likely ever need to be updated, patched, repaired, or cleanly removed from user's systems.  In many cases the answer is "yes" - in which case having a properly written installer can reduce the total cost of maintaining the application over time. There are other services and features designed to work with Windows Installer, such as Restart Manager and WMI and product and patch inventory functions. If your application can benefit from these, then that's another reason for including an installer.

The upfront costs to develop a useful installer for your application may pay off in the long term, and the costs of development can be mitigated by selecting an appropriate Windows Installer authoring tool, such as WiX or InstallShield or another.


问:
Prevent anomalies caused by signal propagation time
In electrical engineering class we learned that signal lines are not ideal, so it takes time for the signal to reach the other end of the cable, and if we doesn't take this into account, it can lead to crazy phenomenons like:

Imagine we have a tank game, where tank1 (played from Europe) shots tank2 (controlled from the USA). In tank1's monitor he sees that tank2 is destroyed, but it takes some (very small but not negligible) time for the signal to reach tank2's monitor. So while the signal travels, he can fire his virtual cannon too, destroying tank1. The signal of this act starts his journey to tank1, before the data that tells to tank2 that he is dead, arrives. This causes the weird phenomenon, that tank1 destroyed tank2, but tank2 still can destroy player1 (despite that tank2 doesn't even exists).

They told us, that we cant solve this problem in the hardware way, we have to prevent this in the software side, but they didn't tell us how should we do this, but I am courious, so how do we/they solve this problem?

The problem is not about the time that elapse while the bullet flies in the air, it is about that the first tank should be destroyed, so it shouldn't be able to shot (or be able to do anything), but in our problem it is able, because the information that he destroyed doesn't arrived yet. In this case we should interpret the word shot as: the bullet impacted and it destroyed the tank. So the actual signal that is going to be sent to the other client is that he is destroyed. Not the event that the enemy tank fired its cannon.

答:
Actually, you CAN'T prevent this, and you shouldn't.  Double kills can and do occasionally happen in reality.

Think of this as simulating time-of-flight of the projectiles.

You got a shot off.  SO DID HE.  You didn't see his muzzle flash, because you were blinded by the flash and smoke from your own shot.  You see your round hit him, and destroy him.  At that moment, you are already dead, from his incoming round, but you just haven't gotten the memo yet.


问:
What is the name of this relationship between objects?
Different types of dependencies have particular names, such as linear dependency, circular dependency, self-referencing object, etc.

What is the name of the dependency where those rules are true?

A has zero or more B,

B has zero or more C, and:

A has zero or more C.

If there is no particular name for such relationship, do you have any suggestions?

答:
Since there were no answers for a while, I suppose that there is no well-known, widely used name for this relationship. Therefore, my own suggestion is to use:

pass-through dependency : the dependency where C is linked to A at the same time directly and through B,

pass-through inconsistent dependency : the specific case where C1 is linked to A1, while being linked to B1 which in turn is linked to C2.

multi-path dependency : another possible term, which may be more explicit when the dependency is more complex; for example, C may be linked to A directly (C → A), through B (C → B → A), and through D+E (C → D → E → A).


问:
Use client to access database or server to access database
I' creating a client server application in which I need to update a particular database. I'm using python with MySQL. There are two options:

I use a client.py and server.py, the client.py can send data packed into JSON to the server, the server.py will handle the database and send query data back in the form of JSON.

The second option is that there is no server.py file, instead the client accesses databases and queries directly with the MySQL server.

Is there any benefits to using one method to another?

EDIT:

There can be atmost about 100 clients and they will be sending data throught the day with a delay of about about 20 seconds.

答:
What you are asking about here is the classic 2-tier vs 3-tier (or n-tier) decision.

First off, there's no inherently correct answer.  Which you go with really depends on what your goals are.

In a client-server setup, you connect directly to the database from the client.  The benefit of this is it is a simple setup.  The downside is you are essentially giving direct access to the database to anyone running the client (which includes database connection info).  You also potentially may need to make sure all the proper database drivers are installed on the machines running the client (this may not be an issue for python/mysql programs).

In a 3-tier system, the clients communcate with an application server, and that application server is the only program that will interact with the database server.  One benefit is security - the database can be safely out of reach of the clients.  And you dont have to worry about configuring database drivers on each client.  You then also have the application server functionality if you expand to web and mobile applications.  The downside of course is that its more work to set up - you need to make/implement the application server (which can, btw, just be a web server).

tl/dr... read up on 2-tier vs 3-tier designs.


问:
How to document a project which is already developed?
I would like to know what options are available for documenting a project which has already been developed, as the developers who worked on didn't write even a single page of documentation.

The project has no other details other than many pages of scripts with functions written and modified by developers who worked on this project from the past 2 years. All I have is the database schema and project files. I would like to know if there is any way to organize this project and document it so that it could be helpful for the developers who will be working on this project in the future.

The project was developed with PHP and MySQL. The functions are poorly commented so I can't get good results when I run it with doxygen.

答: The previous suggestions are all good ones, but I would also consider researching if your community of users have created any ad-hoc documentation themselves. Your question did not specify whether any version of your 'product' (existing for two years) has ever been released to users.  If it has been in use, and there is no official documentation, then either no documentation has been necessary, or there is somewhere 'unofficial' documentation which may be rudimentary, but also probably perceived as essential by users. Try searching the web for artifacts likely to represent critical APIs, search forums, ask power-users, and search question and answer sites. If possible, try to write documentation that is fulfilling a technical or business need.  </p>


问:
Is there a better way of handling access control logic instead of it being in the UI?
Through most of my dev experience, I've never had to deal with much variety of access control architectures.

They've all been pretty straight forward:

```<code>Group [Create, Update, Delete]
    - User 1
    - User 2

Group [Update, Delete]
    - User 2
</code>```

Which, for all intents and purposes, works well. The problem I have is the actual implementation of it. All the solutions I've worked on either grant/deny the visibility of a menu link, or disable a button etc. This is all controlled via the top-most layer of the app, whether it be a WebApp or WinForms UI.

I'm in the early stages of designing a rather large WinForms system so I'd like to get the security architecture right from the beginning.

Although I don't see myself getting away from visually limiting the user from performing certain actions (by disabling restricted controls etc), I'm sure there are better solutions available then doing most of the work in the UI.

As I understand it (and these might be limited by my ignorance), these are my options:

Put the logic to return and verify user rights in the business layer

On the form_load event, get these rules and enable/disabled UI elements

Leave the UI elements in tact and halt the operation from within the business layer if the user doesn't have permission for the action (dirty!)

Surely there must be more elegant solutions than this.
Could someone please provide me with alternatives or improvements to the aforementioned ideas?

Am I thinking about it incorrectly? Should I re-evaluate my database design while I'm at it?

答: I think you're looking for the Model View Controller pattern, or some slight variation of it. As far as security goes, there is more information here: https://stackoverflow.com/questions/2543639/design-patterns-for-security-and-data-access-control</p>

OwnerDisplayName: drminnaar


答:
WPF strongly encourages using the Command pattern, which encapsulates the logic for a given button press or menu item into an ICommand object, rather than as a code-behind event handler. The interesting part of these objects is that, in addition to the standard Execute method, also has a standard CanExecute method, which determines whether the button is enabled or not. This method can be used both by validation logic and by the permissions layer to determine whether the UI element is active.

This allows the permission logic to be "server-side", as part of the business logic, and have the UI element's visibility, "enabled-ness" and functionality linked to it using data binding, rather than manually going over the UI elements and enabling/disabling them.

This fits in with WPF's general philosphy of using the MVVM pattern, using data-bindings between the UI and the back-end view models to hide all that ugly "check the permission level and set the button's property accordingly" boilerplate logic.

Title: Is there a better way of handling access control logic instead of it being in the UI?

Body:
Through most of my dev experience, I've never had to deal with much variety of access control architectures.

They've all been pretty straight forward:

```<code>Group [Create, Update, Delete]
    - User 1
    - User 2

Group [Update, Delete]
    - User 2
</code>```

Which, for all intents and purposes, works well. The problem I have is the actual implementation of it. All the solutions I've worked on either grant/deny the visibility of a menu link, or disable a button etc. This is all controlled via the top-most layer of the app, whether it be a WebApp or WinForms UI.

I'm in the early stages of designing a rather large WinForms system so I'd like to get the security architecture right from the beginning.

Although I don't see myself getting away from visually limiting the user from performing certain actions (by disabling restricted controls etc), I'm sure there are better solutions available then doing most of the work in the UI.

As I understand it (and these might be limited by my ignorance), these are my options:

Put the logic to return and verify user rights in the business layer

On the form_load event, get these rules and enable/disabled UI elements

Leave the UI elements in tact and halt the operation from within the business layer if the user doesn't have permission for the action (dirty!)

Surely there must be more elegant solutions than this.
Could someone please provide me with alternatives or improvements to the aforementioned ideas?

Am I thinking about it incorrectly? Should I re-evaluate my database design while I'm at it?


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

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

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

Error highlighting with no need to
recompile project.

Code assist.

Refactoring.

Opening call hiearchy/Opening
declaration.

Fully integrated with source control.

Debugger is included.

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

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

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

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

答:
Personally, I like Vim because it's extremely good at editing text, i.e. very ergonomic (the keybindings don't strain my hands so much and I don't need to use the mouse so much) and efficient to use once you get the hang of it (which will of course take time and patience, since it's not the most intuitive editor for beginners).

I would however prefer Eclipse for large-scale Java development due to the many features that are readily available. Of course, there are some plugins that can make Eclipse a bit more tolerable.

ContentLicense: CC BY-SA 2.5


问:
Why would you want to use an array, or hash as hash key in ruby?
i'm using Ruby 1.9.3

I figured out that you can use an array, or a hash as hash key in ruby:

```<code>h = Hash.new

h[Array.new] = "Why?"
h[Array.new] # Output: "Why?"

h[Hash.new] = "It doesn't make sense"
h[Hash.new] # Output: "It doesn't make sense"
</code>```

But an object works differently...

```<code>h[Object.new] = "LOL"
h[Object.new] # Output: "nil"
</code>```

But this one works as expected:

```<code>o = Object.new

h[o] = "LMAO"
h[o] # Output: "LMAO"
</code>```

Tried this:

```<code>o = Object.new           # Output: #<Object:0x2c78c10>
h["#<Object:0x2c78c10>"] # Output: nil
</code>```

Tried it in Python and PHP and it throws an error.

I'm just curious about how it works, and why would you want to use an array, or a hash as hash key in ruby?

Thanks.

答:
Well, you probably know this much already; but for starters, I'd say that's probably very bad practice. Still, it's an interesting functionality question, so I'll give it a shot...

From what I understand, Ruby maintains its empty arrays and hashes all as one singleton object, just as Nil is a single object in the entire program. If you declare 5 arrays with nothing in them, they're all the same reference - just like if you made 5 similar strings in C#, Javascript (and if I remember right, Ruby). They likely become seperate instances once values are added to them.

However, there are valid reasons to maintain Object.new's as seperate instances - the most common use I would know of is as multithreading tokens; times when you want to maintain something by hash map, but since it's so code-internal, a string isn't the most logical key.

The root of my answer, as I understand it, is that those classes work in kinda-exceptional ways within the language that you may not see with other types. I haven't used Ruby in a while, so I may need to get this verified by others.


问:
How to make big chunk of hardcoded menuitems in a programmable way
So in the javascript app, we have a lot of repeated chunk of menu items with the specific settings: URL, Name, Title, etc etc (these settings sometimes can be optional). Here is the gist of the menuItem and we have tons of them.

The client pushes new changes every month or twice per month on these items, either the menu item should be named differently or the url is outdated or whatever.

Instead of going and changing each URL everytime, I thought about:

Creating a web-service, with a complete CRUD on menuitems, whatever comes in there, goes dirrectly via JSON, to the app

Well, I would like to hear if you have some thoughts on this idea of configuring the application rather than hardcoding the app each time when the CR comes.

Here is the gist of the menuItem and we have tons of them.

All help will be appreciated

答:
i will concur -- making an app to handle changing navigation menus on a website is so much more difficult then it sounds!  i am dealing with having to do complicated inventory lookups - to determine if a product category - should be in the nav menu. i was semi-obsessed with trying to write it to a file because obviously do not want to go through all the inventory for every single page view just to show a nav bar. </p>

<p>anyway i could ramble on but - make a database table to hold the nav structure. have a script that runs once a day or whatever you need to update the navigation table. having it in a db immediately opens up easy ways to add and maintain. and you aren't doing a complicated search on the database every time you want to show the nav bar. and with cacheing you could even minimize the db strain. </p>

Body:
i will concur -- making an app to handle changing navigation menus on a website is so much more difficult then it sounds!  i am dealing with having to do complicated inventory lookups - to determine if a product category - should be in the nav menu. i was semi-obsessed with trying to write it to a file because obviously do not want to go through all the inventory for every single page view just to show a nav bar.

anyway i could ramble on but - make a database table to hold the nav structure. have a script that runs once a day or whatever you need to update the navigation table. having it in a db immediately opens up easy ways to add and maintain. and you aren't doing a complicated search on the database every time you want to show the nav bar. and with cacheing you could even minimize the db strain.


答:
I have been using emacs for 5+ years. I can no longer tell you the key combinations I'm using, my fingers just remembers them and have to look at the keyboard just to see what my hands are typing.

A few years ago I started using Eclipse, and there is no chance I'm going back to emacs freely. Sorry muscle memory, even though you are missing ye old C-x r SPC 1, Eclipse makes me a lot more productive and that is what counts.

No, I don't think you should switch, but you should dedicate a couple of hours to learn the basics of vim so you don't have to look it up anymore.

Title: I use an IDE (Eclipse) to develop software.  Why should I switch to vim or emacs?

Body:
My day job is  java/web developer. I have been using eclipse for ~5years. I think its excellent and I also use Webstorm for javascript and html/jsp.

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

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

Error highlighting with no need to
recompile project.

Code assist.

Refactoring.

Opening call hiearchy/Opening
declaration.

Fully integrated with source control.

Debugger is included.

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

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

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

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


问:
How to find local maxima in matrices?
I need to develop an algorithm for finding all the local maxima in a two-dimensional array: how to search for local maxima in the the most efficient way? Are there algorithms about it?

Moreover, the algorithm should be able to handle even the "flat" peaks, that is it should find the central coordinates of each peak. Here's an example with a one-dimensional array: some consecutive elements have the same peak value, so the algorithm should return the central location.

```<code>                       |       flat peak       |
                       |-----------------------|
array = [...  0.8  0.9  1.0  1.0  1.0  1.0  1.0  0.9  0.8  ...]
                                   |
                            desired result
</code>```

How to handle the problem of the flat peaks in a two-dimensional array? In the flat peaks, the neighbor elements are equal to each other and form a single local maximum, so I would like to get the central coordinates of this neighborhood.

答:
If you want to lump together neighbors with equal values, you can use a disjoint-set (aka union-find) datastructure to efficiently categorize sets of equivalent neighbors.

However, if your matrix values are floating point (as in your example), you should note that comparing floating point data for exact equality is almost always the wrong thing to do.

Finally, finding the "central coordinates" of a "flat peak" can be more complicated in a 2-dimensional array than in a 1-dimensional one.  For example, the geometric center-of-mass of a C-shaped "flat peak" may not be near any of its actual members.  Now, that may be what you want for a particular application -- or it may not.

Title: How to find local maxima in matrices?


答:
Why limit the keys by a limited set of types?  As long as it responds to hash, which is how hashes keep track of the key.  Both Proc and lambda respond to hash and so can be used.  As well as any other object, unless you explicitly remove that method from the object.

```<code>my_proc = Proc.new { "Hello World #{Time.now}!"}
my_hash = { my_proc => 'a proc', my_proc.call => "a proc that was called at #{Time.now}" , [3, 2, 1] => 'My 3, 2, 1 array'}
my_hash.default = "There is no key with this value"
puts my_hash[my_proc]
puts my_hash[my_proc.call].inspect
sleep(1)
puts my_hash[my_proc.call].inspect
puts my_hash[[3, 1, 2].sort.reverse]
puts my_hash
</code>```

Title: Why would you want to use an array, or hash as hash key in ruby?

Body:
i'm using Ruby 1.9.3

I figured out that you can use an array, or a hash as hash key in ruby:

```<code>h = Hash.new

h[Array.new] = "Why?"
h[Array.new] # Output: "Why?"

h[Hash.new] = "It doesn't make sense"
h[Hash.new] # Output: "It doesn't make sense"
</code>```

But an object works differently...

```<code>h[Object.new] = "LOL"
h[Object.new] # Output: "nil"
</code>```

But this one works as expected:

```<code>o = Object.new

h[o] = "LMAO"
h[o] # Output: "LMAO"
</code>```

Tried this:

```<code>o = Object.new           # Output: #<Object:0x2c78c10>
h["#<Object:0x2c78c10>"] # Output: nil
</code>```

Tried it in Python and PHP and it throws an error.

I'm just curious about how it works, and why would you want to use an array, or a hash as hash key in ruby?

Thanks.

Body:
Why limit the keys by a limited set of types?  As long as it responds to hash, which is how hashes keep track of the key.  Both Proc and lambda respond to hash and so can be used.  As well as any other object, unless you explicitly remove that method from the object.

my_proc = Proc.new { "Hello World #{Time.now}!"}
my_hash = { my_proc => 'a proc', my_proc.call => "a proc that was called at #{Time.now}" , [3, 2, 1] => 'My 3, 2, 1 array'}
my_hash.default = "There is no key with this value"
puts my_hash[my_proc]
puts my_hash[my_proc.call].inspect
sleep(1)
puts my_hash[my_proc.call].inspect
puts my_hash[[3, 1, 2].sort.reverse]
puts my_hash


答:
What you've described is pretty much what you'll need to use.  (Sorry)

Consider treating each major section of your UI as modules / separate forms.  Then have a parent form that can be used to control whether or not particular children forms will be loaded based upon your business logic.

This would allow you to keep the access control logic within the business logic layers and only minimally rely upon code-behind.  This layer of authorization checking could be limited to coarse grained show | disable | no-show type decisions.

As the winform app will run on a system outside of your control, you'll need to have additional degrees of checks within your business logic that provides an interface to your database layer.  This is where you would apply finer grained authorization checks.

Finally, consider using WPF instead of Winforms, if you can.  WPF is better structured to facilitate your presentation pattern of choice (MVC, MVVM, MVP, etc...) than what winforms natively provides.  You can still write a secure app with winforms, it just takes a bit more effort.


答: Why wouldn't you? You can use any object as a Hash key in Ruby. (Well, any object that responds to hash and eql?, but since there are definitions of those in Object, that's pretty much all objects.) It would be strange and inconsistent if you would arbitrarily exclude two classes from that.


问:
Is test coverage an adequate measure of code quality?
If I have some code that has 80% test coverage (all tests pass), is it fair to say that it's of higher quality than code with no test coverage?

Or is it fair to say it's more maintainable?

答:
I would call it more-refactorable. Refactoring gets extremely easy if code is covered with lot of tests.

It would be fair to call it more maintainable.


问:
Worst coding standard you've ever had to follow?
Have you ever had to work to coding standards that:

Greatly decreased your productivity?

Were originally included for good reasons but were kept long after the original concern became irrelevant?

Were in a list so long that it was impossible to remember them all?

Made you think the author was just trying to leave their mark rather than encouraging good coding practice?

You had no idea why they were included?

If so, what is your least favorite rule and why?

Some examples here

答:
Some of the places I've worked with insisted on commenting out unused or deprecated code instead of deleting it.  Instead of trusting the VCS for history, etc. it was painfully maintained in the files through commented out code.  </p>

<p>The big problem I found with this is that you often had no idea why the code was commented out.  Was it because some dev was actively making changes and wanted to keep it around for reference or was it no longer needed?  </p>

Body:
Some of the places I've worked with insisted on commenting out unused or deprecated code instead of deleting it.  Instead of trusting the VCS for history, etc. it was painfully maintained in the files through commented out code.

The big problem I found with this is that you often had no idea why the code was commented out.  Was it because some dev was actively making changes and wanted to keep it around for reference or was it no longer needed?


答:
Basically, read this(PDF) to see why Emacs is powerful. Once you know Lisp, it is almost trivially easy to write extensions for it (I have several source control workflows and deployments scripted through an add-on I wrote for myself called employer-mode). As far as what you list above;

Error highlighting with no need to recompile project. Doesn't make sense for all languages. You can easily integrate REPLs of many languages into it. Right now, I have ruby, python, haskell, common lisp, scheme and erlang all hooked into emacs. Incidentally, the JavaScript addon js2-mode has full incremental "compilation" so it highlights things like syntax errors for you, so it's certainly possible, but not the norm

Code assist. there's an addon for that called autocomplete.el, I believe, check the Emacs wiki

Refactoring. I assume you mean "automated refactoring", which doesn't make sense in all languages. Probably exists for some, but I don't know.

Opening call hiearchy/Opening declaration.

Fully integrated with source control. It has a git-mode built in as of Emacs 22.3, not sure about other source control

Debugger is included. Language-by-language basis here. Generally, if it has REPL integration, it has an Emacs debugger too, but it's not universal

availablity of 3rd party plugins - eg findbugs/checkstyle. don't know about those specific ones, but there's plenty of addons for it, from the why-isn't-this-in-the-base-package-useful, to the utterly frivolous

That said, if you don't like Lisp, and you don't intend to learn it, I can't honestly recommend Emacs. The win you get out of it is learning about tool-crafting and applying those principles to increase your own productivity, not getting a bunch of off-the-shelf mods and stringing them together.


问:
How should I behave as a developer in a project that's headed for failure?
I am a developer in a 5-member team and I believe our project is headed for disaster. I'll describe why in a moment, but my question is: how should I behave?

The deadline is in 1.5 months, and I feel no matter what we do, this project will fail. I'm of the opinion that we should just terminate the project and stop wasting our time, but politically I think it's impossible for our manager to do that.

What should I do in this case? Should I put in extra effort, or should I just take it easy? And what should I say to the manager?

Reasons this project is headed for failure:

With deadline approaching many of the must-have features are not finished

Application is unstable and very difficult to use

System is very convoluted, code very hard to understand, very difficult to change - Data model is too driven by a complex relational database (100+ tables)

Unclear leadership; the manager responds to new information with major changes

Almost no automated tests or unit test

Heavily depends on other systems, but no integration tests yet

In fact, we actually just inherited this project (along with the mess) around 1-2 months ago from another dev team under the same manager, who has worked on it for a few months.

答:
I participated in three projects that were clear failure. These were quite painful but looking back, two of three did not have negative consequences on my career, and even third one wasn't the end of the world.

Here are some observations I recall.

Developers at junior positions ("code per spec", "fix the bug", stuff like that) don't get affected much, unless they slack off due to lowered morale in the team. At positions like these, a sensible and even sometimes successful survival strategy could be just doing the best you could.

For example, one of the failures I experienced has been overcome by plain, methodical fixing of more than hundred known bugs which (coupled with particularly smart approach of promoting this progress by tech lead) eventually led upper management to decision to recover the project and give it yet another chance with a new release, which in turn made a reasonable success.

Programmers at more senior, influential positions would better be prepared to share the negative consequences of project failure. An architect, tech lead, senior developer are typically expected to make an impact big enough to be considered responsible for project success or failure.

At senior position, one would better be prepared to gain from failure "indirectly", by analyzing what went wrong and what could have been done better.

These bits of knowledge, post-mortem lessons may be invaluable if learned right, the very successful career at senior positions may depend on how well these are learned, as explained in this brilliant answer at WP:

Judgement comes not from success, but from failures. Most companies want to hire people that have had their failures paid for by previous companies...

On a more practical note, one can consider "next / update release" approach as a possible way out of the failure. Coincidentally or not (I think not), but both of the failures that didn't damage my career went by very similar scenarios: release N was a total disaster,  release N+1 was tolerable, releases N+2 and later were plain success.

Walking in your shoes, I would most likely put some effort in preparing / promoting the idea of "next release". Make (and communicate!) something like a tentative list of known issues that you would want to fix after planned release. Draft an informal, rough road map for next release(s).

Think of how you could communicate these ideas to people around you, how you could influence management to consider this plan. If the project has someone with good marketing skills, try to involve them into amortizing the failure damage by wrapping up coming release into smoother terms, like "early access", "beta", "customer preview", "introductory release", stuff like that.

Think of a backup plan in case if higher ups will appear deaf to this idea. Remember above story about "fixing of more than hundred known bugs"? there is a chance for things to change, really.

Management may appear deaf to next-release ideas now, but there is a good chance for them to reconsider in the face of strong convincing evidence of project quality progress.

It is quite likely that there will be rather long time between freezing code for planned release and management decision to drop it completely. That time is your chance: if you focus effort on fixing known issues and properly "evangelizing" the progress, this could make a difference (as it once made to me).


问:
Map of functions vs switch statement
I'm working on a project that processes requests, and there are two components to the request: the command and the parameters. The handler for each command is very simple (< 10 lines, often < 5). There are at least 20 commands, and likely will have more than 50.

I've come up with a couple of solutions:

one big switch/if-else on commands

map of commands to functions

map of commands to static classes/singletons

Each command does a little error checking, and the only bit that can be abstracted out is checking for the number of parameters, which is defined for each command.

What would be the best solution to this problem, and why? I'm also open to any design patterns I may have missed.

I've come up with the following pro/con list for each:

switch

pros

keeps all commands in one function; since they're simple, this makes it a visual lookup table

don't need to clutter up source with tons of small functions/classes that will only get used in one place

cons

very long

hard to add commands programmatically (need to chain using default case)

map commands -> function

pros

small, bite-size chunks

can add/remove commands programmatically

cons

if done in-line, same visually as switch

if not done in-line, lots of functions only used in one place

map commands -> static class/singleton

pros

can use polymorphism to handle simple error checking (only like 3 lines, but still)

similar benefits to map -> function solution

cons

lots of very small classes will clutter project

implementation not all in the same place, so it's not as easy to scan implementations

Extra notes:

I'm writing this in Go, but I don't think the solution is language-specific. I'm looking for a more general solution because I may need to do something very similar in other languages.

A command is a string, but I can easily map this to a number if convenient. The function signature is something like:

```<code>Reply Command(List<String> params)
</code>```

Go has top-level functions, and other platforms I'm considering also have top-level functions, hence the difference between the second and third options.

答:
I have no idea how Go works, but an architecture I have used in ActionScript is to have a Doubly Linked List that acts as a Chain of Responsibility. Each link has a determineResponsibility function (which I implemented as a callback, but you could write each link separately if that works better for what you're trying to do). If a link determined it had responsibility, it would call meetResponsibility (again, a callback), and that would terminate the chain. If it didn't have responsibility, it would pass the request to the next link in the chain.

Different use cases could be easily added and removed simply by adding a new link between the links of (or at the end of) the existing chain.

This is similar to, but subtly different from, your idea of a map of functions. The nice thing is that you just pass in the request and it does its thing without your having to do anything else. The down side is that it doesn't work well if you need to return a value.

Title: Map of functions vs switch statement


问:
Interaction between programs
I am writing an interactive program in which it takes speech input from the user for a specific list of commands.

The list of commands will be stored locally in a graph and based on the usage their weight will be modified.

The speech input is taken and processed into text and then it's executed by bash scripts.

I am thinking what I should use to interact (synchronize) between the speech recognition engine and then the list and the bash program.

I am using C++ and Bash on a Unix system.

I thought of mutex but the problem is what if the user gives multiple inputs then I'll have to buffer it and then process it sequentially and that will make the system slower.

The bash script is used to call the system utility commands as requested by the user.
Should I only use C++ or Bash too?

I am thinking of storing the graph in a binary format. Is this the best way to store the graph?

Please suggest alternatives.

答:
I hope I'm understanding the problem correctly, but one solution I've seen is to have the receiving program implemented as a local server, listening on a specific port (for security, have it only accept localhost connections). I don't think there would be much in the way of performance lag. This leaves the idea that someone might send voice commands from their smartphone (though, in all likelihood, this will stay on the local machine)
The local-port system was one way that one of my college professors had several students work on individual parts of a problem using different languages of their choice (and certain parts could be run on different machines)</p>

Title: Interaction between programs


问:
Why do people consider Python a weak language?
I've been using Python for a little while now and I am enjoying it, but a few of my friends are telling me to start using a language like C# or Java instead and give these reasons:

Python is a scripting language

Python apps don't port well to people who don't have Python

It's hard to make good GUIs in Python since it's a scripting language

I like the batteries included approach to Python and the ability to download and upload pre-built modules from PyPI is really useful to me. Is there any specific reason why Python is considered a weak language?

答:
Because people readily dismiss things they don't know much about with pseudo-intelligent rationalizations? I'm not much of a python fan, but those criticisms are bogus.

Python is a general purpose programming language that happens to be good for scripting tasks. It's not a weakness.

If you want to package software written in python with an all-in-one installer, there's almost nothing stopping you from including Python. It's not hard; you'd have to have a platform-specific installer, but this would be true for most multi-platform apps you could build. There are even tools to make that process pretty painless; see, for example http://hackerboss.com/how-to-distribute-commercial-python-applications/

There are plenty of good GUI solutions for Python, and any other scripting languages. For a long list of options, see http://wiki.python.org/moin/GuiProgramming

There are fair criticisms of Python that reasonable people can make, but there's no reason to completely dismiss it based on the fact that it isn't C# or Java. For many people, that's a good reason TO use Python.


答:
Python is a scripting language

Just because a language is scripted does not immediately make it worse. It just depends on what you want to acheive with your program. If you want fast execution speed, then Python probably isn't the right choice, but neither is Java. If you want simplicity with the ease of allowing your customers to change your source code  and don't care about speed then Python is a good choice.

Python apps don't port well to people who don't have Python

Java and C# certaintly aren't any better at this. C# requires the Microsoft .Net Framework or Mono, and Java requires the Java Runtime Environment. If you want a language that doesn't require dependencies, then start writing in Assembly, or C/C++ (even in C/C++ it's going to depend on the compiler and the options you use).

It's hard to make good GUIs in Python since it's a scripting language

This is not completely true. Python has many GUI frameworks including Gtk, Qt, and many others. Wikipedia even has a whole page listing graphical applications built with or using Python including BitTorrent clients, games, and even ERP software. Granted it probably is easier to develop graphical applications in C# if you are using Visual Studio or an equivilant IDE. I can't speak for Java since I personally despise it, but my understanding is that even Java requires using a widget toolkit, the most popular of which appears to be Swing.

Title: Why do people consider Python a weak language?

Body:
I've been using Python for a little while now and I am enjoying it, but a few of my friends are telling me to start using a language like C# or Java instead and give these reasons:

Python is a scripting language

Python apps don't port well to people who don't have Python

It's hard to make good GUIs in Python since it's a scripting language

I like the batteries included approach to Python and the ability to download and upload pre-built modules from PyPI is really useful to me. Is there any specific reason why Python is considered a weak language?


问:
What are standard directory layouts for storing database scripts in TFS?
I recently took over the maintenance of 10-15 SQL Server databases and to my surprise found out that the team does not store the code scripts anywhere.  They currently deploy changes to each environment without any paper/code trail.

The code for applications that use these databases are all stored in TFS and I need to implement a directory structure for storing the scripts - tables, views, stored procedures - in TFS.

On our Oracle side of the house we use a two directory structure:

ddl

sql

But I think there could be improvement in storing the scripts on the SQL Server side.   I was thinking of using something similar to the way SSMS stores objects:

tables

views

stored procedures/functions

Is there a standard structure or best practice that is used to store SQL scripts?

答:
Storing them in a similar structure to what you see in SSMS is a good way to do it.

Do you have visual studio licenses with your TFS licenses? The "Database Project" features in Visual Studio are fantastic for organising database projects. It can import the schema from a live database, and then it stores all the schema objects as scripts, under a folder structure that is analogous to what you would see in SSMS. There are also pre and post deployment script locations as well.

The benefit of this approach is that you can include the database project within solutions, and have builds which deploy the database etc (quite useful when dev'ing on a local machine).

You can also then get visual studio to create scripts to take a given schema (ie production schema extracted as a dbschema file), and bring it into line with the schema in TFS. Very handy for deployment scripts.


问:
How to apologize when you have broken the nightly build
My first commit in my project resulted in the nightly build being broken and people are all over me as we are nearing the release. I want to send an apology email that should sound sincere
and at the same time hinting that this was my first commit and this would not be repeated any more.

Being a non-native English speaker, I have difficulties coming up with correct words. Can someone please help?

答:
If you are working on an open source project,

just say "Sorry, I broke the build. May be I was too sleepy!"

and add it as a github comment.

It is because many open source developers write code during midnight.


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

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

then write the below code

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

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

答:
If you rename the enum member in a DLL, the caller code needs to be modified and recompiled.

This may break binary compatibility. You need to ensure the caller code is possible to be modified.

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


问:
Why not use a RTOS with microkernel architecture for highly concurrent web servers?
Why not use a RTOS with microkernel architecture for web servers? The scheduler is deterministic and all requests will be handled quickly leading to faster response time? It's easy to extend an OS based on microkernel architecture, since everything is like a client-server communication via message passing. Also, the server will be very light weight and requires less resources. Say that you are developing the web service using C++. I am thinking about QNX for the OS. Is it a bad idea, or it does not matter?</p>

答:
Because it will not make much difference!

Modern *nix and windows server OSes were designed to handle large concurrent workloads, and, anyway web serving is done by specialist applications such as Apache, ISS etc. which make very few demands on the OS apart from threading, network IO and file IO.

Its hard to see what a micro-kernal OS would bring, the scheduling algorithms are different, RTOS is optimized towards the predictable response times required by a real time systems, *nixes and windows are optimized for overall throughput, which, would seem an altogether better bet for a web server.

Add in the years of experience, tooling and tuning that have gone into web servers running on the mainstream OSes and its hard to see what gains you would make.


答:
I see two options here:

Use Nano instead - This is exactly like Notepad in Windows for Linux. Requiring no hotkey combinations, you just type nano somefile.conf and you have a nice editor. You can even add syntax highlighting

Keep the program locally and sync over SCP to the server - I do this when I need to work on a small website but don't have enough resources to run apache locally. I simply bring up WinSCP, bring up the directories I want, and use "Keep remote files up to date". Changes are usually reflected in seconds

Use a plugin in your editor/IDE to work "directly" with the remote file - Before I cared about revision control, I simply fired up Notepad++ (my prefered editor) and used NppFTP to work on the files. NppFTP is faster than the WinSCP option since Npp tells it immediately when a file is  saved, which gets immediately uploaded. However as I said you loose revision control. I'm sure there's a plugin for Eclipse you can use

Hope this helps


答:
The scheduler is deterministic and all requests will be handled quickly leading to faster response time?

Deterministic does not imply faster. An RTOS schedules guarantees that all requests will be served in some given time T, but a best effort scheduler may provide better average performance with the downside that some requests take a lot longer than T to serve.

Title: Why not use a RTOS with microkernel architecture for highly concurrent web servers?

Body: Why not use a RTOS with microkernel architecture for web servers? The scheduler is deterministic and all requests will be handled quickly leading to faster response time? It's easy to extend an OS based on microkernel architecture, since everything is like a client-server communication via message passing. Also, the server will be very light weight and requires less resources. Say that you are developing the web service using C++. I am thinking about QNX for the OS. Is it a bad idea, or it does not matter?</p>


答:
A direct answer to your question: it doesn't matter. Most RTOS come with libraries that implement web servers.

But I guess a misconception in your question:

Realtime does not mean faster.

Realtime means that the time of the outcome is as much important as its value.

For example, a video decoder must deliver video frames at the exact time they are expected. It is better for the user experience not to deliver a late frame than delaying the whole movie (and desynchronizing image and sound).

As a side note, you may notice that many realtime problems are solved with high performance instead of realtime OSes.


问:
Single codebase for client and server with Node.js
There are a few claimed benefits to Node.js that I typically hear. Some (many?) I agree with. There is one that I completely do not understand, which is the one language argument: "You can now use one language on both the client side and the server side."

This does not make sense to me on many levels:

most people already know more than one language, and learning a second is anyway not that big of a deal.

JavaScript is not that great of a language; if people had any choice they'd probably choose something else on the client side, but they're locked in.

the beauty of the server side is you can choose ANY language (so it makes sense to choose the best, most capable language, with the least baggage).

The only reasonable argument I've heard is "if I'm using backbone I can re-use my models". Since I haven't used backbone myself I'm not sure how much that actually amounts too however.

Can someone shed some light?

答:
Let's start with your points:

Most people don't want to work in several languages in the same day.

Javascript works. It may not be the pinnacle of language design, but it is incredibly flexible. The perceived quality of the language rests a lot on the programmer, which is pretty unique.

There are some bad parts, but every language has those

The bad parts are very well documented and can be easily avoided

It's actually quite fun to write in. I can't say that for any OO language.

Some people choose Javascript for the server, and Node.js's popularity highlights that. In fact, a lot of the Node.js community came from Ruby, which is considered a very fun language to write in.

Now for my points:

Fantastic community with incredible energy

Massive portability (includes code reuse)

Decent package manager

I find Javascript a fun language to write in. When I'm working in other languages, I often miss features that they done have, such as first-order functions, Array methods, stupid-simple closures, and prototypal inheritance (it's fun when you get to know it).

Javascript is not my favorite language, but it's definitely not the worst. I've since left the Node.js bandwagon, but I still keep it in my toolbox. It's a lot more interesting than languages like Java or C++.


问:
Websocket protocol server development
I am interested in building a custom Websocket server for college project. I have a good familiarity about HTTP 1.1 and knows quite well of how it works. I am asking this question assuming that Websocket clients (browsers) have their protocol specification since Websocket clients connects to Websocket server through URL begins with ws://. In addition, can Websocket server implemented without single threaded and event based environment feature of language?

Thank you.

答:
Websocket servers can be implemented without single-threaded and event based environments. More than that, even such environments (like nodejs) can run multiple threads.

However, I would approach this problem using nodejs. In specific, you can use something like Sails.js.

It lets you develop the sort of standard APIs you know how to develop from frameworks like Ruby on Rails, ASP.NET MVC, Python Django or whatever you're coming from only you're serving directly to WebSockets (can also serve to HTTP).

Also, socket.io is really nice and lets you do a lot of nifty stuff on the client-side and on the server-side. That site has plenty of nice examples.

Title: Websocket protocol server development


问:
Prevent anomalies caused by signal propagation time
In electrical engineering class we learned that signal lines are not ideal, so it takes time for the signal to reach the other end of the cable, and if we doesn't take this into account, it can lead to crazy phenomenons like:

Imagine we have a tank game, where tank1 (played from Europe) shots tank2 (controlled from the USA). In tank1's monitor he sees that tank2 is destroyed, but it takes some (very small but not negligible) time for the signal to reach tank2's monitor. So while the signal travels, he can fire his virtual cannon too, destroying tank1. The signal of this act starts his journey to tank1, before the data that tells to tank2 that he is dead, arrives. This causes the weird phenomenon, that tank1 destroyed tank2, but tank2 still can destroy player1 (despite that tank2 doesn't even exists).

They told us, that we cant solve this problem in the hardware way, we have to prevent this in the software side, but they didn't tell us how should we do this, but I am courious, so how do we/they solve this problem?

The problem is not about the time that elapse while the bullet flies in the air, it is about that the first tank should be destroyed, so it shouldn't be able to shot (or be able to do anything), but in our problem it is able, because the information that he destroyed doesn't arrived yet. In this case we should interpret the word shot as: the bullet impacted and it destroyed the tank. So the actual signal that is going to be sent to the other client is that he is destroyed. Not the event that the enemy tank fired its cannon.

答:
You can't program the delays away. They are a fact of nature.

But, you can incorporate the delays in the game in various ways:

The easiest is that the delay represents the time-of-flight for the projectiles and for the player to register the results. In this case, the player fires, but does not see the enemy tank destroyed until a message is received back confirming its destruction. As there now is a (slight) delay between firing and destruction, it is no longer impossible to be hit by the tank you just fired upon.

Another way to factor the delays in is to use larger time-steps, where everything happening between t0 and t1 is regarded as having happened at t0. If the step is large enough to cover the delay, then the two shots are considered to have been fired at exactly the same time.

If there is a central server, the delays could also be factored in at the controls side. The player is not inside the tank, but at a central control location remotely operating a tank.


问:
Order collisions in ecommerce
Suppose I have a web app where sellers add their products and set them as available for sale. Then I show a list of products in my mobile app, where I get products via my REST API.
My problem: suppose two clients view the same product(and there's only 1 item available from the seller) and they make simultaneous order. How do I resolve such collision?

My technology stack: RoR, PostgreSQL, heroku.

答:
There's no such thing a simultaneous order. Your server is going to have to process one of the basket add actions first. At the point that happens the product should be locked, and any subsequent basket add actions should return an out-of-stock message. If the customer doesn't checkout within a fixed time (often one hour) it's normal to remove the lock on the product and return it to sale. This can be supplemented with messaging on the basket page explaining that the item in their bag is only going to be available for a fixed time due to low stock.

The critical thing from the user's perspective is that whichever one of them tries to add the item to their basket second should receive a message indicating the item is out of stock immediately after trying to add it to their basket. It's terrible UX to let them get into the checkout thinking they've got an item and then reject the sale later.

In general ecommerce websites get around this problem by automatically marking items as out of stock when they get down to low but non-zero product levels. This allows the merchandisers to restock the items without ever having taken an order that they're unable to fulfil; though that might not be possible in your case if the sellers are selling unique items.

Title: Order collisions in ecommerce


问:
Why are constructors not inherited?
I am confused as to what the problems could be if a constructor was inherited from a base class. Cpp Primer Plus says,

Constructors are different from other class methods in that they
  create new objects, whereas other methods are invoked by existing
  objects. This is one reason constructors aren’t inherited. Inheritance
  means a derived object can use a base-class method, but, in the case
  of constructors, the object doesn’t exist until after the
  constructor has done its work.

I understand  the constructor is called before object construction is completed.

How can it lead to problems if a child class inherits (By inheriting I mean the child class is able to override the parent class method etc. Not just accessing the parent class method) the parent constructor?

I understand there is no necessity of explicitly calling a constructor from within a code[not that I am aware of as yet.] except while creating objects. Even then you can do so using some mechanism to invoke the parent constuctor [ In cpp, using :: or using member initialiser list, In java using super]. In Java there is an enforcement to call it in the 1st line, I understand that is to ensure the parent object is created first and then the child object construction proceeds.

It can overrride it. But, I can't come up with situations where this can pose a problem. If the child does inherit the parent constructor what can go wrong?

So is this just to keep away from inheriting unecessary functions. Or is there more to it?

答:
Why are constructors not inherited: the answer is surprisingly simple:
The constructor of the base class "builds" the base class and the constructor of the inherited class "builds" the inherited class.
If the inherited class would inherit the constructer, the constructor would try to build an object of type base class and you wouldn't be able to "build" an object of type inherited class.

Which kind of defeats the purpose of inhereting a class.

Title: Why are constructors not inherited?


答:
"You can now use one language on both the client side and the server side" doesn't require that said language be JavaScript. There are a number of other languages which can be compiled into JavaScript, avoiding some of its pitfalls. Some are designed specifically for the purpose (e.g. CoffeeScript), and others have a large pool of experienced programmers (e.g. Java).

On the one hand it might seem crazy to compile Java to JavaScript and run it with Node instead of compiling it to a war and using a J2EE application server. On the other hand, compiling whichever source language you use to JS for both the client and the server avoids issues which could potentially arise due to translation gotchas.

Title: Single codebase for client and server with Node.js

Body:
There are a few claimed benefits to Node.js that I typically hear. Some (many?) I agree with. There is one that I completely do not understand, which is the one language argument: "You can now use one language on both the client side and the server side."

This does not make sense to me on many levels:

most people already know more than one language, and learning a second is anyway not that big of a deal.

JavaScript is not that great of a language; if people had any choice they'd probably choose something else on the client side, but they're locked in.

the beauty of the server side is you can choose ANY language (so it makes sense to choose the best, most capable language, with the least baggage).

The only reasonable argument I've heard is "if I'm using backbone I can re-use my models". Since I haven't used backbone myself I'm not sure how much that actually amounts too however.

Can someone shed some light?


问:
Reading from a file and inserting into a database, a good practice
I am making an Android application which reads several JSON files and inserts the read information into tables in my database.
For instance, there are three files:

countries.json

```<code>{
    "countries": [
        {
            "name": "United States",
            "org_ids": [
                {
                    "id": 1
                },
                {
                    "id": 2
                },
                {
                    "id": 3
                }
            ]
        },
        {
            "name": "China",
            "org_ids": [
                {
                    "id": 1
                },
                {
                    "id": 2
                }
            ]
        },
        {
            "name": "Hong Kong",
            "org_ids": [
                {
                    "id": 3
                },
                {
                    "id": 4
                },
                {
                    "id": 5
                }
            ]
        }
    ]
}
</code>```

orgs.json

```<code>{
    "orgs": [
        {
            "id": 1,
            "name": "UNO"
        },
        {
            "id": 2,
            "name": "Organization of American States"
        },
        {
            "id": 3,
            "name": "INTERPOL"
        },
        {
            "id": 4,
            "name": "European Union"
        },
        {
            "id": 5,
            "name": "The Commonwealth of Nations"
        }
    ]
}
</code>```

continents.json

```<code>{
    "continents": [
        {
            "id": 1,
            "name": "Africa"
        },
        {
            "id": 2,
            "name": "North America"
        },
        {
            "id": 3,
            "name": "South America"
        },
        {
            "id": 4,
            "name": "Asia"
        },
        {
            "id": 5,
            "name": "Europe"
        },
        {
            "id": 6,
            "name": "Australia"
        }
    ]
}
</code>```

Please don't pay attention to the contents of my JSONs, they don't contain real members of the listed international organizations. It's just an example.

I see two ways.

THE FORMER WAY.

Store each country with its data to a class instance and define a SparseArray contains a country ID as a key and a CountryInfo object as a value.

```<code>/** Each item contains country's ID (key) and respective data (value) */
    private SparseArray<CountryInfo> mCountriesInfo = new SparseArray<JsonParser.CountryInfo>();
</code>```

After reading everything from the files, the data from the SparseArray will be inserted into the database.

```<code>    private class CountryInfo {

    String mCountryName;
    int continentId;
    String mContinentName;
    /** Contains IDs (keys) and names (values) of organizations */
    SparseArray<String> mOrgNames = new SparseArray<String>();

}
</code>```

Drawbacks.

The more JSONS (or the more complex JSONs) the more complex the class
for storing.

Data duplication.

Benefits

Reading and inserting does not depend on each other.

THE LATTER WAY.

Read and insert without preliminary saving.

Drawbacks.

Database logic and reading logic are mixed.

Benefits.

No any additional classes.

No data duplication.

Which way is a better practice?

答:
(This is a Java question, I guess?)

I am sure you can write a JSON reader which takes an arbitrary processing function and applies that function to every record.  The "processing function" may be passed in a functional way, or if you have only older Java versions available, in form of an interface. This gives you reading logic without any database logic. Then, you provide a specific processing function / interface implementation containing the "database insert" logic.

As a result, you get separated database and reading logic without the drawbacks from your first approach.

This is also known as Visitor pattern.


问:
Which design pattern would be best for this case?
I have a class, called PolicyProvider, at present with the following (abridged) interface:

```<code>public interface IPolicyProvider
{
    List<Policy> GetRenewalPolicies(Client client, int financialYear);
}
</code>```

The purpose is quite obvious - every year, the insurance renews for the client, and they will get a number of new policies.

The thing is, the policies change year by year.  Therefore, a concrete implementation of the class needs to be changed every year (or amended with lots of ugly little "if's" evaluating the financial year).  I can see that over time this will become horrendous.

In this case, what design pattern is most appropriate?

答:
Following nulliusinverba's suggestion, I'm creating an answer out of my original comment.

I see it as a scenario for a factory pattern, with your core PolicyFactory (or provider) creating policies for any given client.

You could then in turn have a PolicyFactoryFactory class, a factory of factories, that is (nevermind the awkward naming), capable of creating a PolicyFactory for particular year (be it PolicyFactory2012 or PolicyFactory2013 etc.).

Obviously, this metafactory could still be able to parse external files and build policies out of their contents (as Florian suggested).


问:
What should I know before starting a software company?
Seeing that so many of my friends are unemployed, some of my frinds and I are planning to create a small software company.

What are the basic things we should know and do? Are there things specific to running a software company that we'd need to be aware of?

答:
One very important point that many software startups seem to miss is this:

Find a problem, and solve it. Don't build a solution and find problems that could fit, and don't solve problems that are solved already.

This seems obvious, but there are many examples of companies whose products failed (or who went under entirely) because they couldn't convince people that they actually needed the thing.

For example, don't make a to-do list app. Don't build a social networking anything; if I had a penny for every "I'm going to make the next Facebook" claim from projects that failed completely, I'd have enough cash to buy Facebook. I'd probably avoid music-discovery apps as well; Grooveshark, Pandora, Spotify, Last.fm and the rest have that market covered. As a general rule, when you get an idea, Google about a bit and see what already exists. Consider testing out whatever solutions you find. If you can't see anything wrong or lacking with them, then you probably won't be able to break into that market unless you've found some shiny new way of doing things that makes it better (or you can match their functionality for greatly reduced prices, perhaps).

I once heard someone say that you should be able to tell a stranger what your product is for without saying "it's like [other product]", and I think that's pretty good advice. If it's like some other product, that might be ok, but don't focus on that. For example, you're not building "something like Mint", you're building "an app to track and manage your finances by doing X, Y and Z". The difference is that you're focusing on the features that you want, and not the features that your competitors have. Of course, you'll want to look at your competitors to work out what features the market wants, but you don't want to fall into the trap of being a copy of an existing product. If you're the same as an older product, then people who use that product might as well stay there, and people who don't might as well choose that product over yours because it's more mature and has all the advantages that brings - they've had longer to fix it, to build up a support base, etc.


答:
The most obvious problem with allowing the derived class to override the base class constructor is that the developer of the derived class is now responsible for knowing how to construct its base class(es). What happens when the derived class doesn't construct the base class properly?

Also, the Liskov-Substitution principle would no longer apply as you no longer can count on your collection of base class objects to be compatible with each other, because there's no guarantee that the base class was constructed properly or compatibly with the other derived types.

It is further complicated when more than 1 level of inheritance is added. Now your derived class needs to know how to construct all the base classes up the chain.

Then what happens if you add a new base class to the top of the inheritance hierarchy? You'd have to update all of the derived class constructors.

Title: Why are constructors not inherited?

Body:
I am confused as to what the problems could be if a constructor was inherited from a base class. Cpp Primer Plus says,

Constructors are different from other class methods in that they
  create new objects, whereas other methods are invoked by existing
  objects. This is one reason constructors aren’t inherited. Inheritance
  means a derived object can use a base-class method, but, in the case
  of constructors, the object doesn’t exist until after the
  constructor has done its work.

I understand  the constructor is called before object construction is completed.

How can it lead to problems if a child class inherits (By inheriting I mean the child class is able to override the parent class method etc. Not just accessing the parent class method) the parent constructor?

I understand there is no necessity of explicitly calling a constructor from within a code[not that I am aware of as yet.] except while creating objects. Even then you can do so using some mechanism to invoke the parent constuctor [ In cpp, using :: or using member initialiser list, In java using super]. In Java there is an enforcement to call it in the 1st line, I understand that is to ensure the parent object is created first and then the child object construction proceeds.

It can overrride it. But, I can't come up with situations where this can pose a problem. If the child does inherit the parent constructor what can go wrong?

So is this just to keep away from inheriting unecessary functions. Or is there more to it?


问:
What algorithms are there for picking colors for plot lines on graphs?
I'm interested in what algorithms or rules I can programmatically implement to generate RGB or HSV colors for plotlines to keep them visually distinct from the neighbors.

I know that in professional mapmaking, there are algorithms or rules that make sure that no two adjacent countries on a map are the same color. I can also think of Microsoft office Excel as picking good tints/shades for plot lines (red, then blue, then purple/orange).

Here's an example of what I'm talking about - I need to generate colors for 12 lines on a black background. The colors here I've hardcoded by hand using web-safe RGB color codes. The problem arises when these lines overlap - it's hard to tell if one is looking at purple, slighly darker purple or violet. I'm looking for a better algorithm to produce colors for plotlines like these.

Here's an example using Flot plotting library for jQuery, it has nice succession of colors for graphs:

答:
I recommend using the HSV or HSL color spaces, not the RGB color space, because HSV and HSL are better structured for generating colors that look different to humans.  You'll have more work in RGB (though conversions back and forth exist, should you need them).

This is what HSV / HSL look like:

When using the HSV or HSL color space you can assume (very roughly) that the difference between the H (hue) components of two colors are a good approximation of the perceptual distance between the colors - i.e. the bigger the change in hue, the more different the colors will look to humans.  You can try playing with S (saturation) and L/V (lightness/value) as well to eke out a few more very different colors, but they will not look as different for the same value change as varying the hue.

Depending on the number of distinct colors that you need, you can divide the hue-space into that number of different colors.  If for example you have a hue-range of 256 values and you require 16 distinct colors, then your first color might be (0, 128, 128), your second (16, 128, 128) and so on.  I somewhat arbitrarily picked S/L values smack in the middle here as that will usually be light and saturated enough to clearly see the color differences.  This system is simple, and assumes you need to know nothing about adjacency of colors in your graph/map.

If you do not know in advance how many distinct colors you need but you know the upper limit, and dividing the hue range into colors with that upper limit in mind as above still gives you good perceptually different colors then you can use the same system with the upper limit.

If you (could) need very many distinct colors, you could still get away with using very similar or even the same colors, as long as they do not appear near the other elements of the graph that have the similar color.  This requires knowing your adjacency situation in the graph you're rendering and may not always be straightforward, and even then it may not be a good idea as Dukeling points out in the comments: it may be confusing to viewers that the same color is used twice in the graph for two different concepts.

So finally in the most complex situation your graph is complex enough that you do not have enough color space to ensure you do not end up with distinct elements with colors that are too similar using the above system.  In this case you need to build up an adjacency graph of elements of your visualization graph.  Adjacency here is a fuzzy concept - you will have to define it correctly for your actual situation.  For example in your second example the data on July 12 has a choke point where every color is adjacent to every other one.  One approach that can help you if you can build up the adjacency graph is the graph coloring problem - there are libraries that may help you - for example boost::graph in C++.


问:
Moving to Python (SciPy and NumPy) for Scientific Computing
Just read a presentation about using Python for Scientific Computing. I am currently using MATLAB (student license FTW, which will expire when I graduate soon).

So I was wondering how matured SciPy and NumPy are with respect to relying on them for all the Scientific Computing I need to do. The advantage is that it's free. I am mainly focused on Signal Processing, Audio, Acoustics kind of computing.

I can imagine that the NumPy and SciPy projects are evolving with respect to the support for more complex techniques. So, how fast are they evolving, are there large communities behind them?

Finally, are there other solutions?

答:
In short: Python is a much better language than Matlab, and has more complete general-language features, but Matlab has a more complete set of scientific computing tools than Python.

Octave also has more complete scientific tools than Python, and is a closer language to Matlab if you're already familiar with it, but also shares the language's flaws.  Octave and SciPy are free, Matlab is very not free.

I am mainly focused on Signal Processing, Audio, Acoustics kind of computing.

Me too, and I've found SciPy lacking. Some examples:

Documentation is poor or non-existent for many functions

<s>Filter design tools convert to transfer function representation internally, so higher-order filters suffer from numerical error problems.</s> (fixed)

Other functions like freqs only accept tf representation, which, again, causes numerical error problems.

Doesn't support filters in second-order-sections representation

FFTs are not as fast

Lots of functions from Octave/Matlab don't exist yet in SciPy, and can't be directly translated from Octave because of GPL vs BSD licensing

...

But I still prefer SciPy, because the language is much nicer to use, and does most of what I need.  It's free and open-source, and actively developed, and you can contribute easily just by pushing "Edit" on Github.  Since I'm primarily using this to learn and practice signal processing, I don't consider it a problem that I have to contribute documentation (old vs new) or improvements myself.  That's the sort of thing I want to learn anyway.

10 Reasons Python Rocks for Research (And a Few Reasons it Doesn’t)

Python vs Matlab for scientific computing

Also, while in the process of trying to fix some of these things, I've uncovered some flaws in Matlab's filter design tools: 1 2  So open-source development with lots of test cases has its advantages, too.


问:
Migration to embedded systems
My company has so far been developing a medical device, which is connected via USB to a desktop system (running x64 Windows 7) to run the image analysis and do everything GUI related.

I am familiar with both Windows and Linux programming, C, C++, C++11 and C#, but now our new project coming from management would be a handheld, embedded system, and since I am the only software engineer, I have absolutely no idea how embedded systems work.

Is it totally different from the "normal" programming job, should I recommend hiring someone with embedded experience, are there good ressources for introduction to embedded computing?

I am at a loss here, since I do not know what exactly to expect (it'll be in theory the same as with the desktop systems, a sensor acquiring an image, and the software doing analysis).

Can someone help me get an idea what I would have to expect for this?

Edit: there is no framework, as to what hardware to use. We can use whatever we want, as long as it is small enough to be handheld. We will be using a third party sensor (either photo-sensor, or acoustic sensor, thats not been established yet), but again, we are pretty much free to decide, so my guess will be that it will have a well established API. I don't even really know what embedded systems are, I have experimented privately with an Arduino, does that count as embedded already?

答:
The hardware designers need to pick the candidate hardware options that can do the job. Then the team should do a trade study to select the best option from those candidates for your specific product.

Some Software Specific Categories of that trade study are:

OS Hardware Driver support

Programmer Background

Identification of "special" requirements that will impact OS/hardware selection. e.g. Do you need multithreading, scheduling, mutex's, disk support etc.

Do you already have code for a particular OS

Any other factor that you can come up with that impacts your OS or language selection.

You don't pick your OS first. You pick your hardware first, but that hardware selection has to consider software impacts. e.g. You don't want to pick hardware that requires all custom driver code when an equivalent piece of hardware with a simple to use API is readily available.

As for what you should expect after that, it all depends on your selections from the trade study. If you are lucky enough to be able to use Windows Embedded compatible hardware with windows compatible drivers then your learning curve will be fairly small. It'll be very similar to desktop development (at least until you begin integrating with the hardware devices, then some hardware knowledge may come into play).

If the intent is to build extremely low cost hardware then you may have to write code that tweaks individual bits in registers and be required to write all the interrupt handlers for the attached devices. If you don't have a much of a hardware background then this would not be for your team. You can't write reliable driver software if you don't understand how the hardware needs to work.

I would say that if you have the full-blown windows embedded OS system then you may be able to do the job without hiring anyone. Linux would probably take someone with some experience, but if you have a little slack time you could try it on your own for a few weeks to determine if you think there's a need. Any OS selection with less than either of the above will probably require someone with experience, even if it is to just get you going. If you pick a board package/OS that requires a custom Board Support Package then definitely find someone who has specific experience developing BSPs for that particular OS. That's a very niche skill that can have huge impacts on the product when done wrong.

Title: Migration to embedded systems


问:
Is context-driven testing suitable for all projects?
One thing I cannot find anywhere is: is this approach limited to non-critical software? Because in critical (or just when customer wants us to follow his rules) we have no freedom in testing and just follow the procedures.
Am I right?</p>

答:
It depends on what you mean by "freedom."

Testing isn't necessarily about "freedom." Testing is about finding out if the software does what it is supposed to do.  In most "contexts," that means determining if the software meets the customer's requirements.  So any testing that occurs will be "driven" by that goal, and any testing that doesn't advance that goal is a waste of time.  This is true regardless of the testing methodology used.

In some testing methodologies like TDD, the tests themselves are part of the requirements.  Each test identifies a requirement, and the passing of that test verifies that the requirement  is fulfilled.

So let's look specifically at some of the things that Context-Driven Testing advocates:

Testing is done on behalf of stakeholders in the service of developing, qualifying, debugging, investigating, or selling a product.

Test artifacts are worthwhile [only] to the degree that they satisfy their stakeholders’ relevant requirements.

The value of any [testing] practice depends on its context.

Consider two projects:

One is developing the control software for an airplane. What “correct
behavior” means is a highly technical and mathematical subject. FAA
regulations must be followed. Anything you do — or don’t do — would be
evidence in a lawsuit 20 years from now. The development staff share
an engineering culture that values caution, precision, repeatability,
and double-checking everyone’s work.

Another project is developing a word processor that is to be used over
the web. “Correct behavior” is whatever woos a vast and inarticulate
audience of Microsoft Word users over to your software. There are no
regulatory requirements that matter (other than those governing public
stock offerings). Time to market matters — 20 months from now, it will
all be over, for good or ill. The development staff decidedly do not
come from an engineering culture, and attempts to talk in a way normal
for the first culture will cause them to refer to you as “damage to be
routed around”.

Testing practices appropriate to the first project will fail in the
second.

Practices appropriate to the second project would be criminally
negligent in the first.

As you can see, Context-Driven Testing adapts itself to the project, not the other way around.  But this should really come as no surprise, since all software testing is (or should be) about proving that customer expectations are met, not about conforming oneself to some arbitrary methodology just because.

Context-Driven Testing is less about a methodology, and more about some guidelines and principles that drive all of testing.  It basically says that your testing methodologies, your rigor, your testing culture, are all based on the nature, character and culture of the software project and its participants.

In that sense, consider it the "freedom" philosophy.  You are free to adapt your testing methods to best fit the needs of the software project under test.