答:
Well, there are instructions that don't access the data cache, but it's impossible to access the data cache without using an instruction, so by definition the instruction cache is used more often.

If you're talking about which one has fewer cache misses, that's going to be highly program specific.  A tight loop that accesses a gigabyte of memory will have zero instruction misses and a ton of data misses.  A large program consisting entirely of register operations will have a ton of instruction misses and no data misses.

Title: Instruction vs data cache usage

Body:
Say I've got a cache memory where instruction and data have different cache memories ("Harvard architecture"). Which cache, instruction or data, is used most often? I mean "most often" as in time, not amount of data since data memory might be used "more" in terms of amount of data while instruction cache might be used "more often" especially depending on the program.

Are there different answers a) in general and b) for a specific program?


问:
Is there any way to test how will the site perform under load
I have made an Asp.net MVC website and hosted it on a shared hosting provider. Since my website surrounds a very generic idea, it might have number of concurrent users sometime in future.

So, I was thinking of a way to test my website for on-load performance. Like how will the site perform when 100 or 1000 users are online at the same time and surfing the website. This will also make me understand whether my LINQ queries are well written or not.

答:
An Autohotkey (AHK) script can simulate a human user. Let it run all day long.

You can let it run on several boxes to simulate a few users. The nice thing is the testing style is completely under your control. You can have 1 AHK script spamming a report feature, and see if it affects the users of other features.

Although I'm not familiar with AHK's threading abilities so simulating thousands of users could be difficult. You may be bound by the number of computers you have.

ContentLicense: CC BY-SA 3.0


问:
What are the advantages and disadvantages of having a subdomain for each user account?
I notice two types of design used in web applications, some with a particular subdomain for users contents, and some with same URL structure for all the accounts.

Ex: unique.domain.com and another_unique.domain.com for subdomains for sites like blogspot, wordpress, basecamp etc.

while in the other approach domain.com/action1 and domain.com/action2 the content is shown according to the user logged in, but the URL is same for every user.

What are main differences between both of these kind of design?

答:
The server-side differences vary quite a bit from platform to platform.

In most cases, however, it is easier to write an application that assumes it runs in the root (at least in PHP and ASP.NET it is) and then set up separate sites/virtual directories for each.

From a user's perspective, telling them to go to mysite.example.com is typically easier to remember than www.example.com/mysite. There is no reason this must be so, but most people have it more or less ingrained to ignore everything after the / or, for that matter, before the main domain. As a more esoteric example, if you were to tell end users to go to ww2.host.example.com/mysite what most people will actually remember is example.com, their minds discarding the "trash".

The downside is, of course, that provisioning subdomains is kind of manual out of the box. You can script it up, of course, but in IIS or Apache, as well as most domain registrars it tends to be done by hand. So, you have to go to the effort of automating that (though I am sure there are some extant tools that do the trick).


问:
What's a nice explanation for pointers?
In your own studies (on your own, or for a class) did you have an "ah ha" moment when you finally, really understood pointers? Do you have an explanation you use for beginner programmers that seems particularly effective?

For example, when beginners first encounter pointers in C, they might just add &s and *s until it compiles (as I myself once did). Maybe it was a picture, or a really well motivated example, that made pointers "click" for you or your student. What was it, and what did you try before that didn't seem to work? Were any topics prerequisites (e.g. structs, or arrays)?

In other words, what was necessary to understand the meaning of &s and *, when you could use them with confidence? Learning the syntax and terminology or the use cases isn't enough, at some point the idea needs to be internalized.

Update: I really like the answers so far; please keep them coming. There are a lot of great perspectives here, but I think many are good explanations/slogans for ourselves after we've internalized the concept. I'm looking for the detailed contexts and circumstances when it dawned on you.

For example:

I only somewhat understood pointers
  syntactically in C. I heard two of my
  friends explaining pointers to another
  friend, who asked why a struct was
  passed with a pointer. The first
  friend talked about how it needed to
  be referenced and modified, but it was
  just a short comment from the other
  friend where it hit me: "It's also
  more efficient." Passing 4 bytes
  instead of 16 bytes was the final
  conceptual shift I needed.

答:
I found that diagrams were very helpful. Example:

This sort of diagram helped me see that pointers were their own variable, but contained a value that was the location of another object, i.e. array or string. Also, when done in pencil, I could use it to trace my program on paper, or on a chalkboard/whiteboard.

ContentLicense: CC BY-SA 2.5

Title: What's a nice explanation for pointers?


问:
What is interaction oriented programming?
There is this new kid on the block called Interaction Oriented Programming (IOP).

Can somebody explain how it works? How does it compare to object oriented programming? Will this replace object oriented programming or will it just be a niche thing?

What exactly is it and what is its intended purpose?

答:
This answer is out of my context:

OOP

is currently programmed with classes. If you program an object you look inside the object and model the reactions to the outside. You do not look outside the object. It is more like class-oriented programming.

Interaction-oriented

you model the interactions (such as use-cases) between the objects.
I think of it like writing a theater play with scenes. Each object acts along with the script. All interactions between the objects are visible.

Maybe this is related to the method-object-pattern where you perform one special task and you can look at what is done in this one object. It may solve that your interactions are scattered all over many classes.

DCI

to get an update on this have a look at the Data-Context-Interaction-Paradigm.
It uses classes to model the domain.
In every context you assign roles to the objects. What an object can do is defined in the role it plays. (like a theater scene)
The interaction then evolves between the roles.


问:
What are abstract classes and abstract methods?
I got several explanations but so far I'm not able to understand that what are the abstract classes and methods in Java.
Some said it has to do something with the security of the program, other said it isn't anything like that.
Even from the Dietel & Dietel's book I don't get it's purpose.
When, where and why do we use it?</p>

答:
An abstract class is a class that cannot be instantiated (i.e. new myAbstractClass()).  It is used as a template for other classes to inherit.

An abstract method is a method in an abstract class that can be overridden (i.e. implemented) in a derived class.

The difference between an interface and an abstract class is that you can put functionality in an abstract class (i.e. ordinary or virtual methods) that can be utilized in the derived class, whereas an interface is just an empty template.


答:
With abstract classes you can have some kind of skeleton for other classes to extend.

You can't instantiate them but you can put some common implementation which you can use in the classes that extend them.

Title: What are abstract classes and abstract methods?

Body:
I got several explanations but so far I'm not able to understand that what are the abstract classes and methods in Java.
Some said it has to do something with the security of the program, other said it isn't anything like that.
Even from the Dietel & Dietel's book I don't get it's purpose.
When, where and why do we use it?</p>


答: A real life example of an abstract class would be Human for example. But would you intantiate a Human object? No! You would further derive classes from the Human abstract class like Infant, Child, Adult, Man, Woman, etc. And you will extend/retrict the original behaviour in these derived classes down in the heirarchy.


问:
Does some code inherit GNU GPL if it just links to a GPL library?
Suppose there is a library xxx under GNU GPL, that provides a function yyy. Suppose my code links to the library and uses this function. Does my code inherit GPL license?

IANAL, but my thoughts are conflicting:

On one hand, my code is derivative from the library, so it should inherit GPL.

On other hand, my code just uses link to the xxx. Maybe there are other libraries, that have the same interface (particularly, they provide yyy function with same functionality, but different implementation). My code may link to any. My code really isn't directly derived from xxx, it just uses its interface. So, my code shouldn't inherit GPL.

I'm confused.

Note: The question is absolutely abstract. I don't mean any concrete GPL library.

答: Generally speaking, if you're using a library that is GPL'd, your application must also be GPL'd.  There are few exceptions, and they most likely do not apply to you.  </p>


答:
Obviously, this is something that technically can only be answered by a lawyer.

The longer answer is that the ambiguity is somewhat long-running, which means it would have to be decided in a court case.

To avoid any issues, many developers turn to the LGPL in order to avoid the difficulty. Even this doesn't always clear things up if you use a dynamic image-based language like Lisp or SmallTalk. In these cases, some developers include a preamble to further define the boundaries (See Franz's site for example).

Title: Does some code inherit GNU GPL if it just links to a GPL library?

Body:
Suppose there is a library xxx under GNU GPL, that provides a function yyy. Suppose my code links to the library and uses this function. Does my code inherit GPL license?

IANAL, but my thoughts are conflicting:

On one hand, my code is derivative from the library, so it should inherit GPL.

On other hand, my code just uses link to the xxx. Maybe there are other libraries, that have the same interface (particularly, they provide yyy function with same functionality, but different implementation). My code may link to any. My code really isn't directly derived from xxx, it just uses its interface. So, my code shouldn't inherit GPL.

I'm confused.

Note: The question is absolutely abstract. I don't mean any concrete GPL library.


答:
An abstract class is a class that implements some common functionality used by one or more concrete (not abstract) classes.

A good example of this would be the AbstractList class in java.  This class is extended by ArrayList (a concrete class) and AbstractSequentialList (an abstract class which is in turn extended by LinkedList).

One would never instantiate an AbstractList (which one do you want? ArrayList? Vector? LinkedList?) and thus it is made abstract to prevent this.  However, it implements some internals that are necessary for the functioning of a list (modification count for fail fast).

An abstract method is a method that is not implemented in an abstract class or interface, but must be implemented in the concrete class.

The core reason why one would want to have a method be abstract is to be part of a public API.  If you the compareTo method in Comparable is abstract - only the concrete class knows how to implement this correctly for other classes to call.


问:
OO PHP static keyword, should I use it?
I'm writing script for fb and I have 3 objects that I'll be using through all classes. I'm wondering if there is any advantage in using the static keyword except I don't have to create an instance every time I need to use a method/object? Which way should I go, with static or without it?

I know this is basic, but I'm new to OOP and I want to learn to use it in a proper manner.

答:
In short: No. Static methods are generally considered bad practice. They introduce a lot of potential issues. They are a way of shoehorning procedural code into OOP.

They introduce hidden dependencies. Code which arbitrarily calls foo::bar() has a dependency on foo and cannot run without foo being defined. In this instance, the object using foo::bar() will construct correctly but won't be usable if foo is not defined. It will only break at the point foo::bar() is called. If a $foo instance was passed into the object's constructor then the object could never even construct without it's dependencies. This creates far more robust code.

Statics are globals. Global state is very bad, anything can change the code and its state is unknown. You sacrifice the power and control achieved by OOP encapsulation by using static methods.

It's impossible to substitute the functions for a different version. In the foo::bar() example, you sacrifice all the power polymorphism enables you in OOP by using static methods.

It makes unit testing impossible. For unit testing, you need to be able to substitute dependencies for mocks. Using static methods makes this far more difficult.

Are you sure you only want a single instance? Imagine if you had a class that created an FTP connection and allowed a simple API for creating files. Just calling FTP::upload($file); would be quite clean wouldn't it? The problem is, once the requirements change to "can the file now be uploaded to the backup server as well." then you have a problem: there's no way to connect to two different servers at once.

Static methods should be avoided as a matter of course. From an OOP perspective, there is no reason they should ever be chosen over an object with a method.

Title: OO PHP static keyword, should I use it?


问:
UML Class diagrams with Java packages?
I am trying to model in UML 2.0 a Java servlet application that has three classes

Servlet class; essentially a main class that acts as the controller

DatabaseLogic; contains methods for database operations

XMLBuilder; builds an XML from a query result string

The classes use a variety of packages from the Java library. I am unsure how to model this in UML

Do I have to create a package and show which libraries are used for each individual class or can I just have one large package in the diagram with all the libraries showing which classes have dependencies on which.

As per this diagram

This is my first time working with java properly (im a C++ guy)

Apart from being a bit messy , is this a correct UML representation of the system I described?

Does a Package in UML mean the same as a Package in Java?

答:
It looks like you've roughly got it right! A package in a UML class diagram does equate to a package in Java. The JVM/Java's APIs are so large that often its treated as one black box in these diagrams (or not shown at all).

Going forwards I'd worry less about the formal UML notation and more about 'does my colleague grok this'.  Java class diagrams can get very complex beyond a certain size.

OwnerDisplayName: loosebruce

Title: UML Class diagrams with Java packages?


问:
Date calculation algorithm
I'm working on a project to schedule a machine shop, basically I've got everything covered BUT date calculations, I've got a method called schedule (working on PHP here):

```<code>public function schedule($start_date, $duration_in_minutes)
</code>```

Now my problem is, currently I'm calculating end time manually because time calculations have the following rules:

During weekdays, work with business hours (7:00 AM to 5:00 PM)

Work on Saturdays from 7:00 AM to 2:00 PM

Ignore holidays (in Colombia we have A LOT of holidays)

I already have a lookup table for holidays, I also have a Java version of this algorithm that I wrote for a previous version of the project, but that one's also manual.

Is there any way to calculate an end time from a start time given duration?, my problem is that I have to consider the above rules, I'm looking for a (maybe?) math based solution, however I currently don't have the mind to devise such a solution myself.

I'll be happy to provide code samples if necessary.

答:
Sounds like a table to list holidays, and check the date against that table, then check the day of week for that date ($dw = date( "w", $timestamp);)..  Have a table for the hours for each day of the week (this makes this configurable).  Then subtract out hours from the start date until you have no more hours to subtract out..

pseudocode:

```<code>while $durationhours > 0
{
  $hoursinday = $hours["dayoftheweek"];
  if( $hoursinday > $durationhours )
  {
     $endtime = $durationhours+$day["starttime"];
  }
  else
  {
     $durationhours = $durationhours = $hoursinday;
  }
}
</code>```

Does that work?

Title: Date calculation algorithm

Body:
Sounds like a table to list holidays, and check the date against that table, then check the day of week for that date ($dw = date( "w", $timestamp);)..  Have a table for the hours for each day of the week (this makes this configurable).  Then subtract out hours from the start date until you have no more hours to subtract out..

pseudocode:

while $durationhours > 0
{
  $hoursinday = $hours["dayoftheweek"];
  if( $hoursinday > $durationhours )
  {
     $endtime = $durationhours+$day["starttime"];
  }
  else
  {
     $durationhours = $durationhours = $hoursinday;
  }
}

Does that work?


答:
First of all, the examples will be in C#. But I think you'll have no problem understanding it. So...

You CANNOT instantiate objects of an abstract class. You must have a subclass that derives from the class, if you want to instantiate it. But this probably won't help you since you may have come across that before.

So let's try an example.

Suppose you want to lose weight and your nutritionist asks you to track your food intake. When you go to her again, you can't tell her that you ate a "food". Although it's not wrong, since all food has calories, it is too "abstract" for her. So you need to tell her WHICH food.

So, if she were to code that... She'd have an abstract class Food.

```<code>abstract class Food
{
    public int CaloriesPerPound { get; set; }
    //...
}
</code>```

Why? Because that wouldn't allow you to say "I ate a food".

```<code>{
    Food fries = new Food(); //This won't even compile
}
</code>```

So you need concrete classes:

```<code>class Fruit : Food
{
 //Other stuff related only to fruits
}

class Bread : Food
{
 //Other stuff related only to Bread
}
</code>```

So you'll have to tell exactly which food it is.

```<code>{
   Apple desert = new Apple(); //Now we are talking
}
</code>```

But she still needs the food class, it is still interesting to her:

```<code>class Meal
{
    public List<Food> Foods { get; set; }
    //Other meal related stuff
    public int TotalCalories()
    {
        int calories = 0;
        foreach (Food food in Foods)
        {
            calories = calories + food.CaloriesPerPound * FoodQuantity;
        }
        return calories;
    }
}
</code>```

That's an example of when you need an abstract class. When you want to have a base class, but you don't want anyone creating an object of your class.

An abstract CAN have abstract methods. It doesn't need to. Is totally ok to have an abstract class without abstract methods. Speaking of which...

Abstract method is something that it's too broad. There's no similarities on how things work, so the classes that derive from your class that has an abstract method won't be able to call the super class implementation. And you're also forcing all the sub classes to implement their version of that method.

Let's try another example? An Animal Band Simulator. You'd have animals, and each one of them would make a sound. But those are very different "implementations", they have nothing in common A dog differs from a cat, a cat from an elephant, an elephant from a cricket. So you'd have an abstract method MakeSound.

```<code>class Animal
{
    public abstract void MakeSound();
}
</code>```

But, if you have an abstract method in your class, that makes the whole class abstract!

```<code>abstract class Animal
{
    public abstract void MakeSound();
}
</code>```

So the rest of the code might be:

```<code>class Dog : Animal
{
    public void MakeSound()
    {
        //bark at the moon
    }
}

class Cat : Animal
{
    public void MakeSound()
    {
        //meowing for food
    }
}
</code>```

And the BAND!

```<code>class AnimalBand
{
    public List<Animal> Animals { get; set; }
    public void RockOn()
    {
        foreach (Animal animal in Animals)
        {
            animal.MakeSound();
        }
    }
}
</code>```

So this is an example of when you use an abstract method.

I guess this is the essence. It may be a little forced/convoluted, but I think it gets the point across. Go back to the examples that didn't help you before and see if they make sense now.

I'm go out on a limb and say you're a beginner. This stuff may seem strange to you, and you may not see any benefit in using abstract classes.

It's ok. It's strange for almost all of us when we start. But in time, you'll learn to appreciate it.

Body:
First of all, the examples will be in C#. But I think you'll have no problem understanding it. So...

You CANNOT instantiate objects of an abstract class. You must have a subclass that derives from the class, if you want to instantiate it. But this probably won't help you since you may have come across that before.

So let's try an example.

Suppose you want to lose weight and your nutritionist asks you to track your food intake. When you go to her again, you can't tell her that you ate a "food". Although it's not wrong, since all food has calories, it is too "abstract" for her. So you need to tell her WHICH food.

So, if she were to code that... She'd have an abstract class Food.

abstract class Food
{
    public int CaloriesPerPound { get; set; }
    //...
}

Why? Because that wouldn't allow you to say "I ate a food".

{
    Food fries = new Food(); //This won't even compile
}

So you need concrete classes:

class Fruit : Food
{
 //Other stuff related only to fruits
}

class Bread : Food
{
 //Other stuff related only to Bread
}

So you'll have to tell exactly which food it is.

{
   Apple desert = new Apple(); //Now we are talking
}

But she still needs the food class, it is still interesting to her:

class Meal
{
    public List<Food> Foods { get; set; }
    //Other meal related stuff
    public int TotalCalories()
    {
        int calories = 0;
        foreach (Food food in Foods)
        {
            calories = calories + food.CaloriesPerPound * FoodQuantity;
        }
        return calories;
    }
}

That's an example of when you need an abstract class. When you want to have a base class, but you don't want anyone creating an object of your class.

An abstract CAN have abstract methods. It doesn't need to. Is totally ok to have an abstract class without abstract methods. Speaking of which...

Abstract method is something that it's too broad. There's no similarities on how things work, so the classes that derive from your class that has an abstract method won't be able to call the super class implementation. And you're also forcing all the sub classes to implement their version of that method.

Let's try another example? An Animal Band Simulator. You'd have animals, and each one of them would make a sound. But those are very different "implementations", they have nothing in common A dog differs from a cat, a cat from an elephant, an elephant from a cricket. So you'd have an abstract method MakeSound.

class Animal
{
    public abstract void MakeSound();
}

But, if you have an abstract method in your class, that makes the whole class abstract!

abstract class Animal
{
    public abstract void MakeSound();
}

So the rest of the code might be:

class Dog : Animal
{
    public void MakeSound()
    {
        //bark at the moon
    }
}

class Cat : Animal
{
    public void MakeSound()
    {
        //meowing for food
    }
}

And the BAND!

class AnimalBand
{
    public List<Animal> Animals { get; set; }
    public void RockOn()
    {
        foreach (Animal animal in Animals)
        {
            animal.MakeSound();
        }
    }
}

So this is an example of when you use an abstract method.

I guess this is the essence. It may be a little forced/convoluted, but I think it gets the point across. Go back to the examples that didn't help you before and see if they make sense now.

I'm go out on a limb and say you're a beginner. This stuff may seem strange to you, and you may not see any benefit in using abstract classes.

It's ok. It's strange for almost all of us when we start. But in time, you'll learn to appreciate it.


答:
I think this might help you:

https://bitbucket.org/ant512/workingweek/wiki/Home

It's a C# implementation of everything in your algorithm except for holidays (which you should be able to figure out given the rest of the code).

You start off by modeling a working week (Monday-Friday, 8am-5pm, for example, with an hour a day for lunch).  Then you can ask it questions like "if I have a task that takes 15 hours and I start at 9:22 on Tuesday, when will I finish?"

If you've done some Java before hopefully you'll be able to read the C#.  Alternatively, there's a JavaScript port here:

https://bitbucket.org/ant512/workingweekjs/wiki/Home

Title: Date calculation algorithm

Body:
I'm working on a project to schedule a machine shop, basically I've got everything covered BUT date calculations, I've got a method called schedule (working on PHP here):

```<code>public function schedule($start_date, $duration_in_minutes)
</code>```

Now my problem is, currently I'm calculating end time manually because time calculations have the following rules:

During weekdays, work with business hours (7:00 AM to 5:00 PM)

Work on Saturdays from 7:00 AM to 2:00 PM

Ignore holidays (in Colombia we have A LOT of holidays)

I already have a lookup table for holidays, I also have a Java version of this algorithm that I wrote for a previous version of the project, but that one's also manual.

Is there any way to calculate an end time from a start time given duration?, my problem is that I have to consider the above rules, I'm looking for a (maybe?) math based solution, however I currently don't have the mind to devise such a solution myself.

I'll be happy to provide code samples if necessary.


答:
First, I am not a lawyer.

Said that, my understanding of GPL is: if you do anything to a GPL'ed code, you got "infected" like it was an biological virus.

So yes, linking to GPL'ed lib will make you work GPL'ed.

For this reason, you must look for an lib with an license like LGPL (or a even more permissive license, if possible).

This is not legal advice....


答:
An abstract class/method is, conceptually, a "starting point" for a concrete implementation.

An abstract method or other member cannot have any code; it is quite literally a placeholder for a member that must be implemented by classes deriving from the abstract base. It's similar to a method declaration in an interface, but an abstract class can define abstract members of any inheritable visibility, not just public. That abstract member can be used in any code in the abstract class.  The purpose is usually to allow the deriving class to specify some implementation-specific logic or behavior, whose extraction from the surrounding code makes that remaining code implementation-independent.

An abstract class cannot be instantiated; it exists to be derived from and to be used as a common type for members and parameters, similar to an interface in this respect. Classes with any abstract members must themselves be marked abstract, but a class with no abstract members can also be marked abstract. Thus, abstract classes can have code in non-abstract members, which is the primary difference from an interface (the other key difference being the ability to define abstract members less visible than "public"). This is a common tactic to share (and thus re-use) code that is common between implementations of the abstract class.

As far as when to use them, succinctly, use an abstract class whenever you would normally use an interface, but when you also wish to define code that can be shared among derived implementations of the base.

There are differing best practices between Java and C# regarding whether to combine interfaces and abstracts in the same inheritance hierarchy. It's been my experience that an interface directly implemented by a single abstract class is redundant in Java due to naming conventions (interface names are supposed to look like class names so coders don't have to care what they're using). In C#, the pattern's still considered a bit "deep" but is more acceptable because the interface, by convention, would be prefaced with "I-". Either way, the arrangement allows even the abstract class to be refactored or replaced without affecting dependent classes; not only can any implementation of an abstract DoerBase be used, but any Doer (or IDoer) including an implementation of a new BetterDoerBase, or a concrete class inheriting directly from the interface.


问:
C# Algorithms for * Operator
I was reading up on Algorithms and came across the Karatsuba multiplication algorithm and a little wiki-ing led to the Schonhage-Strassen and Furer algorithms for multiplication.

I was wondering what algorithms are used on the * operator in C#? While multiplying a pair of integers or doubles, does it use a combination of algorithms with some kind of strategy based on the size of the numbers? How could I find out the implementation details for C#?

答:
As with all implementation details, it's specific to the implementation (duh), but this is something that's practically universal: If the CPU supports the number type and operation (reasonably recent processors do, for floats, doubles, and the fixed-width integers), you just use that. There may be many layers in between, such as an interpreter, a JIT compiler for the IL, or something entirely else, but that's just wrappers and the actual operation is delegated to the hardware.

You'll have a very hard time beating a good hardware implementation in software, regardless of the choice of algorithm -- with one "common" exception: A slow FPU can sometimes be beaten by sacrificing some features, but that's a very low-level optimization. But that's not something language implementations usually do.

For arbitrary precision integers/numbers (such as BigInt and BigDecimal), you can't (entirely) rely on the hardware operations, as they are too constrained in word size. In such cases, algorithms start to matter, but again it's implementation specific and I can't give any generalizations. Note that the base is usually much greater than 10, to get the most out of the fixed-precision operations. I know that more than one highly used arbitrary precision arithmetic package (specifically, CPython's and PyPy's long type, and the relevant piece of Mathematica) use, or at least consider, Karatsuba's algorithm.

Title: C# Algorithms for * Operator


问:
How can I make a case for "dependency management"?
I'm currently trying to make a case for adopting dependency management for builds (ala Maven, Ivy, NuGet) and creating an internal repository for shared modules, of which we have over a dozen enterprise wide.  What are the primary selling points of this build technique?  The ones I have so far:

Eases the process of distributing and importing shared modules, especially version upgrades.

Requires the dependencies of shared modules to be precisely documented.

Removes shared modules from source control, speeding and simplifying checkouts/check ins (when you have applications with 20+ libraries this is a real factor).

Allows more control or awareness of what third party libs are used in your organization.

Are there any selling points that I'm missing?  Are there any studies or articles giving improvement metrics?

答:
Take a look at The Twelve Factor App

In particular read about what they have to say about dependencies. You will notice that good design provides a declarative mechanism for locating dependencies, in Java this is often realised through Maven. Ivy and NuGet work fine, but Maven is currently the leader in the field and Ivy is decidedly hard work.

If you adhere to the Maven release process (develop snapshots until a formal release is ready, never try to overwrite a previous release, use a proper repository manager like Nexus or Artifactory) then you should have a build process that hums along nicely.

Once you have a solid declarative build process in place, it opens the door to other good practices such as Continuous Integration with Jenkins, Continuous Code Analysis with Sonar and you'll find yourself looking for a better version control branching strategy using git.

Each of the above builds on the core that is Maven. These days, it is pretty much a no-brainer decision.


问:
Use of versioned objects/data to handle program version compatibility?
Is there a common name for the practice of keeping a version number on your data, so that different versions of your program can identify, for example, "current", "legacy", and "too-old-to-deal-with" versions of the same type of object?

As discussed here: Strategy for backwards compatibility of persistent storage.

答:
Since version control systems handle continuously changing versions of document objects, perhaps their nomenclature is appropriate.

Subversion: revision

Git: changeset (or perhaps commit)

In both cases this is metadata associated with the underlying object, and is usually a pointer to a linked list of other pointers representing the history.

So, it would seem that the term you're looking for is the name given to the "collection of revision history pointers" which would be "revision history".


问:
Representing complex object dependencies
I have several classes with a reasonably complex (but acyclic) dependency graph. All the dependencies are of the form: class X instance contains an attribute of class Y. All such attributes are set during initialization and never changed again.

Each class' constructor has just a couple parameters, and each object knows the proper parameters to pass to the constructors of the objects it contains. class Outer is at the top of the dependency hierarchy, i.e., no class depends on it.

Currently, the UI layer only creates an Outer instance; the parameters for Outer constructor are derived from the user input. Of course, Outer in the process of initialization, creates the objects it needs, which in turn create the objects they need, and so on.

The new development is that the a user who knows the dependency graph may want to reach deep into it, and set the values of some of the arguments passed to constructors of the inner classes (essentially overriding the values used currently). How should I change the design to support this?

I could keep the current approach where all the inner classes are created by the classes that need them. In this case, the information about "user overrides" would need to be passed to Outer class' constructor in some complex user_overrides structure. Perhaps user_overrides could be the full logical representation of the dependency graph, with the overrides attached to the appropriate edges. Outer class would pass user_overrides to every object it creates, and they would do the same. Each object, before initializing lower level objects, will find its location in that graph and check if the user requested an override to any of the constructor arguments.

Alternatively, I could rewrite all the objects' constructors to take as parameters the full objects they require. Thus, the creation of all the inner objects would be moved outside the whole hierarchy, into a new controller layer that lies between Outer and UI layer. The controller layer would essentially traverse the dependency graph from the bottom, creating all the objects as it goes. The controller layer would have to ask the higher-level objects for parameter values for the lower-level objects whenever the relevant parameter isn't provided by the user.

Neither approach looks terribly simple. Is there any other approach? Has this problem come up enough in the past to have a pattern that I can read about? I'm using Python, but I don't think it matters much at the design level.

答:
You should look at all of the common object creation patterns and make an assessment based upon the state of your logic, time you have to implement the change, and so forth. Also, rather than have the participating objects know how to construct each other, you should consider Inversion of Control.

Its hard to be specific without more info, but given that you are talking about a complex graph I would think that Abstract Factory or Builder would be more useful here than just a simple Factory depending on how different each of your scenarios is.

If you have some initial decisions to make that influence creation of the graph but the differences are nuances, look at Builder...particularly if there are some structural differences between the "products" (such as, some participating objects are optional or in some scenarios participating objects drag in another set of collaborators).

If the differences between the scenarios are more distinct / elaborate and take the form of "families" of objects that should be used together, look at Abstract Factory with a few different factory implementations.

If you actually just have a few specific flavors of this graph and want to pick and choose between them dynamically, you might be able to just go with Prototype; treat your current implementation as a prototype, code up your alternate implementation(s) as another prototype, and just clone the appropriate prototype as needed.


答:
MSIL aka CIL, into which C# source code is digested, has opcodes for three variations on "multiply"; "mul", "mul.ovf", and "mul.ovf.un". These are used for most built-in value types, from byte to double. They translate pretty directly down to similar native commands.

The first code is general-purpose; value1 and value2 are pushed onto the evaluation stack, then "mul" is called; value1 and value2 are popped, multiplied, and the result is pushed to the evaluation stack. The two variations are for integer multiplication only, and define "checked" overflow behavior; "mul.ovf" asserts that the signed result value will fit into the determined result type without overflow, while "mul.ovf.un" asserts that the unsigned value will fit into the result type.

The "mul" command, like most opcodes, produces a result of a type based on the specifications; the basic rules are that the operation is defined for two inputs, both of which must be the same type and one of the following: int32, uint32, int64, uint64, float, or double. For multiplication of differing types, or types not in the list such as byte, sbyte and short, a widening conversion is performed on the value of the smaller size or precision to that of the larger (or to the minimum). This happens pretty much by default for smaller integer types; the CPU won't deal with anything smaller than a word (16-bit), and some won't even deal with less than a dword at once anymore, so the CLR implementation will simply feed smaller values to the CPU as dwords.

Down at the native level, there are two basic commands in 80x86 assembler to perform multiplication on the same basic types: "MUL" will multiply any two integers (using word, dword or word64 lengths), putting the result in some length-dependent variant of the AX register, while FMUL and FMULP perform the equivalent operation on floating-point types using the chip's FPU, optionally popping the result off of the FPU's eval stack into the AX register.

As far as exactly which binary algorithm is used to arrive at the answer produced by the commands, you really shouldn't care; whatever's used, you can be sure it's much more performant than anything you could do in managed source code.

Now, for larger structural types, like Decimal and BigInteger, built-in native multiplication operations don't exist, and those types do rely on multiplication algorithms. Here's the code for BigInteger, implemented in a hidden helper BigIntegerBuilder: http://typedescriptor.net/name/types/8FF4E74C7553501B0863FF102EC0C5B1-System.Numerics.BigIntegerBuilder. Decimal uses a call to FCallMultiply; unfortunately that's an extern method tying into the MFCs so I can't find source code.

Title: C# Algorithms for * Operator

Body:
I was reading up on Algorithms and came across the Karatsuba multiplication algorithm and a little wiki-ing led to the Schonhage-Strassen and Furer algorithms for multiplication.

I was wondering what algorithms are used on the * operator in C#? While multiplying a pair of integers or doubles, does it use a combination of algorithms with some kind of strategy based on the size of the numbers? How could I find out the implementation details for C#?


问:
What are the conditions to convert BSD-licensed code to another language?
I'm in the process of writing a library in PHP, based on a Java package that comes with a BSD license.

The code will obviously not be the same as the original, but most class/method names, and the in-line documentation, will be the same.

Is a link the original Java library in the code documentation enough?

Can I then release my code with an MIT license?

答: You will have to include the original copyright notice (assuming that your code is close enough to be considered a derivative work), but you are allowed to append your own copyright notice using the MIT license. However, the terms of the two licenses are nearly identical; it might be easier just to leave it under a BSD license.</p>


问:
Is there a modified LGPL license that allows static linking?
LGPL requires that it if a program uses LGPL-ed library, users must be able to re-link the program with a different version of the library:

...

d) Do one of the following:

0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.

1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.

...

However in some cases, this can pose considerable difficulties. In particular, Haskell programs are almost always statically compiled. Moreover, the compiler does cross-module optimizations so its not possible to take a part of the code out and replace it with another. So it's very hard to satisfy this condition. (See this link at Haskell Wiki.)

Dynamic linking would be a solution, but in many cases, this isn't possible. For example:

Some platforms may not have dynamic linking at all.

Some languages don't have the possibility of dynamic linking. Or, it's not possible to make modules multi-platform.

In some cases dynamic linking would prevent important optimizations. While I'd say this is rarely a serious problem, in languages like Haskell the performance loss could be considerable.

Therefore, I'm looking for a standard LGPL-like license that wouldn't require the possibility of re-linking (and I understand that that removes a bit of freedom given to users). Some projects use their own modification of LGPL, for example wxWidgets. But I'd rather use some standard license that is somewhat more official, perhaps checked by some law experts, and (L)GPL compatible. Is there some like that?

(Also I'd be interested to know if are there some unforeseen consequences of such a modification of LGPL.)

答:
I found one with Google: OpenScales license

OpenScales is released under version 3 of the GNU Lesser Public License (LGPL, available here), with an exeption related to static linking exception (see below)...

In addition to the LGPL license text, the exception to the LGPL conditions apply to OpenScales:

As a special exception to the GNU Lesser General Public License version 3, you may convey to a third party an executable file from a Combined Work that links, statically or dynamically, portions of this Library in the executable file, conveying the Minimal Corresponding Source but without the need to convey the Corresponding Application Code under section 4d0 of the GNU Lesser General Public License, so long as you are using an unmodified publicly distributed version of the Library. This exception does not invalidate any other reasons why the executable file might be covered by the GNU Lesser General Public License or the GNU General Public License.

It's not standard though, and I don't know if one exists.


答:
When you link your application to a library, you are making a derivative work of that library. Therefore, under the terms of the GPL (under which the library is licensed), you must distribute the application source code with the application (if you distribute it). And it is a derivative work whether you just link to it or if you alter the source code as well.

Where this gets fuzzy is with dynamically linked libraries. If your software can dynamically link a GPL'ed library (e.g. .dll or .so), but could also run without that library, then you could distribute your software without the library, but then tell the distributee how to run the software with the library. Because the software can run without the library, you can distribute working software without the GPL'ed library and without the application source code, and still  not be violating the GPL. But it is still fuzzy.

One trick I saw a big company use a few years ago was to put a shim between the proprietary application and the GPLed library. The shim was a functionally equivalent wrapper around the GPLed library, and it was itself implemented as a dynamic library (.so). The shim was licensed with LGPLv2, so if the application linked to the shim, the application source code didn't have to be distributed. The source code of the shim "worked" without the GPLed library too, so it could be distributed under any license, so they were able to choose LGPLv2 instead of GPL. Still fuzzy.

Aparently, dynamic loading is how the one can get proprietary drivers to work on Linux.

The key in all of this is that if the entity who received the working application is able to reassemble a working application to use a GPLed library he acquired himself, then the copyright owner of the working application does not have to distribute the source code because the derivative work was made after the distribution of the application, and not before.

Still fuzzy... but I have given you more ways to look at the problem.


问:
How, when, and why do developers use custom data structures in python?
Python's lack of pointers makes data-structure construction intuitively more challenging, and has so much built in functionality that, as an amateur, I can't see when, why, or how you would create something beyond what's already there.

When have you built your own, and why did you do it? E.g. special types of trees, etc.

答:
To make data structures in Python you'd use a class. References in Python (and other reference based languages) act like pointers and so there is no restriction to being able to implement a data structure.

Python does have many data structures builtin. But then so do various other languages. See the STL for C++ or Java's standard library. In both C++ and Java you also rarely need to implement your own data structure because most of the basic structures already exist.

But sometimes, there is a data structure you need that Python doesn't have builtin. For example, python doesn't have any builtin tree-based structures, or linked lists, etc. You don't need these all that often, but when you need them, you need them.


答:
Well, that kind of depends on what you are willing to call a "data structure." According to Wikipdia, a data structure is simply a "particular way of storing and organizing data in a computer so that it can be used efficiently." So, therefore, classes would be a form of data structure, and classes are very widely used in Python. But, for the sake of this answer, I will assume you are more interested in what you might learn about in a data structures and algorithms class (e.g. trees, linked lists, queues, hashes, etc...).

Now, because of Python's pseudo-code-like syntax it can be a very useful language for implementing data structures in. If for no other purpose than just to aid in understanding these basic concepts. For example, when I first learned about linked list I decided to implement them in Python:

```<code>class node:
    def __init__(self, data = None, is_header = False):
        self.data = data
        self.next = None
    def __str__(self):
        return "|{0}| --> {1}".format(str(self.data), str(self.next))

class linked_list:
    def __init__(self):
        self.header = node("!Header!", True)

    def add_node(self, add_me):
        current_node = self.header
        while 1:
            if current_node.next == None:
            current_node.next = add_me
            break
            else:
            current_node = current_node.next

    def print(self):
        print (str(self.header))
</code>```

Now, this isn't a perfect example, nor is it even a totally proper implementation of a linked list, but it goes to illustrate something:

Python's simple syntax can be helpful in understanding data structures

Another example would be a priority queue that I built back in the day:

```<code>class priority_queue:
    def __init__(self):
        self.element = []
        self.priority = []

    def enqueue_with_priority(self, me, priority):
        where = 0
        for i in range(len(self.element)):
            if not priority < self.priority[i]:
            where = i
            break

        self.element.insert(where, me)
        self.priority.insert(where, priority)

    def dequeue_highest(self):
        return self.element.pop(0)

    def print(self):
        for i in self.element:
            print i
</code>```

Again, not a perfect implementation but it illustrates another benefit of coding a data structure in Python:

Python is useful in prototyping data structures to optimize them for lower-level programming languages

Looking back on this code I see flaws in my implementation. The Python code, however, tends to be short and sweet. So if I wanted to implement a data structures in a lower-level language (such as a c-style language) I could first generate a quick Python prototype and then optimize later.

Finally, I think Python can help in the development of data structures, because:

In Python, development is quick, mistakes are allowed and you can try things out.

Imagine you are building a hash-table-like data structure, in a strongly-typed, compiled language you would usually try things out in an IDE, then have to compile and run it. In Python, you can just pull up IDLE, iPython or the Python interpreter and just try things out! No need to recompile for each little change to the hash function you want to try -- just plug it into the interpreter.

So, in conclusion, I guess what I'm saying is that I agree with you: there's not a lot of practicality in building your own data structures (since most anything you may want has already been implemented and optimized). However, for me, there is a lot of educational benefit (because of Python's ease of syntax), as well as a lot of creative and developmental freedom (due to Python's low-constraint, EAFP design).

It is important to note that although python (through its wide-reaching library) provides many standard data structures, a "data structure" (by definition) can be almost anything. So, in Python as well as any other language we may use to solve non-trivial problems, we are going to need to define new data structures. Therefore, it is quite arguable that serious Python developers create custom data structures just as much as serious developers in other languages do.

Title: How, when, and why do developers use custom data structures in python?

Body:
Python's lack of pointers makes data-structure construction intuitively more challenging, and has so much built in functionality that, as an amateur, I can't see when, why, or how you would create something beyond what's already there.

When have you built your own, and why did you do it? E.g. special types of trees, etc.

Body:
Well, that kind of depends on what you are willing to call a "data structure." According to Wikipdia, a data structure is simply a "particular way of storing and organizing data in a computer so that it can be used efficiently." So, therefore, classes would be a form of data structure, and classes are very widely used in Python. But, for the sake of this answer, I will assume you are more interested in what you might learn about in a data structures and algorithms class (e.g. trees, linked lists, queues, hashes, etc...).

Now, because of Python's pseudo-code-like syntax it can be a very useful language for implementing data structures in. If for no other purpose than just to aid in understanding these basic concepts. For example, when I first learned about linked list I decided to implement them in Python:

class node:
    def __init__(self, data = None, is_header = False):
        self.data = data
        self.next = None
    def __str__(self):
        return "|{0}| --> {1}".format(str(self.data), str(self.next))

class linked_list:
    def __init__(self):
        self.header = node("!Header!", True)

    def add_node(self, add_me):
        current_node = self.header
        while 1:
            if current_node.next == None:
            current_node.next = add_me
            break
            else:
            current_node = current_node.next

    def print(self):
        print (str(self.header))

Now, this isn't a perfect example, nor is it even a totally proper implementation of a linked list, but it goes to illustrate something:

Python's simple syntax can be helpful in understanding data structures

Another example would be a priority queue that I built back in the day:

class priority_queue:
    def __init__(self):
        self.element = []
        self.priority = []

    def enqueue_with_priority(self, me, priority):
        where = 0
        for i in range(len(self.element)):
            if not priority < self.priority[i]:
            where = i
            break

        self.element.insert(where, me)
        self.priority.insert(where, priority)

    def dequeue_highest(self):
        return self.element.pop(0)

    def print(self):
        for i in self.element:
            print i

Again, not a perfect implementation but it illustrates another benefit of coding a data structure in Python:

Python is useful in prototyping data structures to optimize them for lower-level programming languages

Looking back on this code I see flaws in my implementation. The Python code, however, tends to be short and sweet. So if I wanted to implement a data structures in a lower-level language (such as a c-style language) I could first generate a quick Python prototype and then optimize later.

Finally, I think Python can help in the development of data structures, because:

In Python, development is quick, mistakes are allowed and you can try things out.

Imagine you are building a hash-table-like data structure, in a strongly-typed, compiled language you would usually try things out in an IDE, then have to compile and run it. In Python, you can just pull up IDLE, iPython or the Python interpreter and just try things out! No need to recompile for each little change to the hash function you want to try -- just plug it into the interpreter.

So, in conclusion, I guess what I'm saying is that I agree with you: there's not a lot of practicality in building your own data structures (since most anything you may want has already been implemented and optimized). However, for me, there is a lot of educational benefit (because of Python's ease of syntax), as well as a lot of creative and developmental freedom (due to Python's low-constraint, EAFP design).

It is important to note that although python (through its wide-reaching library) provides many standard data structures, a "data structure" (by definition) can be almost anything. So, in Python as well as any other language we may use to solve non-trivial problems, we are going to need to define new data structures. Therefore, it is quite arguable that serious Python developers create custom data structures just as much as serious developers in other languages do.


问:
Instruction vs data cache usage
Say I've got a cache memory where instruction and data have different cache memories ("Harvard architecture"). Which cache, instruction or data, is used most often? I mean "most often" as in time, not amount of data since data memory might be used "more" in terms of amount of data while instruction cache might be used "more often" especially depending on the program.

Are there different answers a) in general and b) for a specific program?

答: Kind of depends on how you define "used most often".  In today's modern multi-core architectures, cache coherence requires the data cache to watch the address bus and see if any other cores are modifying the same data and, if so, update their copies.  So data caches may be updated (used) even if the core to which they're attached is idle.</p>

Title: Instruction vs data cache usage


答: How would you continue to guaranty user freedom? I believe the "correct" answer is to statically link a shim that dynamically loads the library.</p>

Title: Is there a modified LGPL license that allows static linking?

Body:
LGPL requires that it if a program uses LGPL-ed library, users must be able to re-link the program with a different version of the library:

...

d) Do one of the following:

0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.

1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version.

...

However in some cases, this can pose considerable difficulties. In particular, Haskell programs are almost always statically compiled. Moreover, the compiler does cross-module optimizations so its not possible to take a part of the code out and replace it with another. So it's very hard to satisfy this condition. (See this link at Haskell Wiki.)

Dynamic linking would be a solution, but in many cases, this isn't possible. For example:

Some platforms may not have dynamic linking at all.

Some languages don't have the possibility of dynamic linking. Or, it's not possible to make modules multi-platform.

In some cases dynamic linking would prevent important optimizations. While I'd say this is rarely a serious problem, in languages like Haskell the performance loss could be considerable.

Therefore, I'm looking for a standard LGPL-like license that wouldn't require the possibility of re-linking (and I understand that that removes a bit of freedom given to users). Some projects use their own modification of LGPL, for example wxWidgets. But I'd rather use some standard license that is somewhat more official, perhaps checked by some law experts, and (L)GPL compatible. Is there some like that?

(Also I'd be interested to know if are there some unforeseen consequences of such a modification of LGPL.)


问:
What are your thoughts on Periods/Full Stops in code comments?
I saw this asked in the SO Tavern, so I'm posting the question here. I thought it an interesting question. (Of course it doesn't belong on SO, but I think it's OK here.)

Do you add periods (or, as the OP wrote, "full stops") in your code comments?

To keep it relevant, why?

答:
I will always properly capitalize and punctuate when creating XML comments that I expect to be seen in IntelliSense and in our generated documentation.  These are much more formal constructs and should be treated as such.

Comments just seen in the body of a code block, however, should simply be as clear as possible.  It's up to the programmer how they achieve that.


问:
What's so great about Clojure?
I've been taking a look at Clojure lately and I stumbled upon this post on Stackoverflow that indicates some projects following best practices, and overall good Clojure code. I wanted to get my head around the language after reading some basic tutorials so I took a look at some "real-world" projects.

After looking at ClojureScript and Compojure (two the the aforementioned "good" projects), I just feel like Clojure is a joke. I don't understand why someone would pick Clojure over say, Ruby or Python, two languages that I love and have such a clean syntax and are very easy to pick up whereas Clojure uses so much parenthesis and symbols everywhere that it ruins the readability for me.

I think that Ruby and Python are beautiful, readable and elegant. They are easy to read even for someone who does not know the language inside out. However, Clojure is opaque to me and I feel like I must know every tiny detail about the language implementation in order to be able to understand any code.

So please, enlighten me!

What is so good about Clojure?

What is the absolute minimum that I should know about the language in order to appreciate it?

答:
Lisp dialects have a unique niche due to their simple syntax.  This simple syntax makes meta programming through the use of macros very simple.  This allows you to model the language to suit your problem domain instead of modeling to fit your problem domain into your language.  It's really cool once you get your head around it, and it lets you do a lot of things easily that is very difficult in other languages.

The downside, is that since every Lisp program essentially defines its own language, you really need a solid grasp on things to understand what is going on.

Now, to answer your questions...

Clojure is a modern Lisp dialect that runs in the JVM/CLR.  This makes it easy to take advantage of the power of Lisp in an existing infrastructure.

It is essential to understand how to use macros to build Lisp to your problem domain to appreciate its usage.  I really only understood this after implementing a Lisp runtime, when I found that much of the core language features can easily be implemented in Lisp itself.  It takes a fair sized project to get this.

Its pluses aside, although it is fun to program in, I personally don't have many cases where I would turn to it for daily problems.  It is a very good tool to learn for mind expansion, and after learning Lisp properly, it became much more natural to take advantage of meta programming facilities in other languages.

The simple syntax makes it easy for computers to interpret (allowing such easy powerful macros), but it makes it very difficult for a human to parse complex expressions quickly.

Title: What's so great about Clojure?

ContentLicense: CC BY-SA 4.0


答:
The strengths of Clojure have been highlighted many times, and, sure enough, make for a very powerful language, so I won't repeat them again here.

I always loved lisp, since the uni days and  I was really excited when I discovered Clojure (perhaps the chance of using lisp outside of academia at last!). However as I started learning an uneasy feeling has begun to creep in, though I cannot pinpoint exactly what it is that I don't like. First of all I would say that coding in Common lisp was easy and fun for me but Clojure has a steeper learning curve. Clisp had a certain beauty and elegance to it. I'm not sure I'll get the same feeling from Clojure. I'm wondering if that feeling will go away as I get more experience.

I have another guess for my mysterious slight repulsion. I think it might be its great flexibility. For instance you can have structures that are half vector and half map and with a few characters of code you can accept them as parameters, take them apart and process them correctly. Yes, it removes all the boilerplate, but somehow it doesn't feel right. Is like you never know very well the rules under all those parenthesis, colons, brakets, etc are operating.

For me, I still love the language for all its advantages (primarily, running in the JVM and simplifying concurrency, while being much more powerful, and concise than Java and with less obvious design flaws) but the jury is still out as to whether something could have been improved.

Title: What's so great about Clojure?

Body:
I've been taking a look at Clojure lately and I stumbled upon this post on Stackoverflow that indicates some projects following best practices, and overall good Clojure code. I wanted to get my head around the language after reading some basic tutorials so I took a look at some "real-world" projects.

After looking at ClojureScript and Compojure (two the the aforementioned "good" projects), I just feel like Clojure is a joke. I don't understand why someone would pick Clojure over say, Ruby or Python, two languages that I love and have such a clean syntax and are very easy to pick up whereas Clojure uses so much parenthesis and symbols everywhere that it ruins the readability for me.

I think that Ruby and Python are beautiful, readable and elegant. They are easy to read even for someone who does not know the language inside out. However, Clojure is opaque to me and I feel like I must know every tiny detail about the language implementation in order to be able to understand any code.

So please, enlighten me!

What is so good about Clojure?

What is the absolute minimum that I should know about the language in order to appreciate it?


答:
Your question is a little vague so I'll try my best.

There's one good question to ask when you're trying to choose between creating a static or an instance method.

Do you need to persistent state between method calls?

Static methods are no different than traditional procedural functions. You give it an input and it should consistently product an output based on the input that is completely side-effect free.

Basically, you could use a traditional function declaration in it's place with no difference. The only benefit is that static methods are attached to a namespace where traditional functions are defined in the global namespace.

They don't matter so much in PHP because the language mixes both procedural and OOP styles but in languages that are pure OOP (ex C#/Java) there is no way to define functions so static methods are used in their place.

Static methods are perfectly acceptable to use when you're defining helper methods that act in a stateless manner. If you need data persistence between calls and/or find yourself relying on global variables, don't; use objects/instances instead.

Update:

Tom B made a very good point about unit testing. That static methods (like procedural functions) are inherently decoupled from the classes that they're attached to. So, if a static method fails, it may also cause any other instance method it's called in to also fail. It's a classic example of a side-effect.

That explains why I have encountered so many people parroting 'static methods are bad, mmmkay' in the TDD community. They have a completely valid point.

There are ways this could be improved. In the language, throwing an implicit exception when static methods fail. Technically, it wouldn't be any messier than doing type conversions. Assume it's going to break something if it fails. Of course, that assumes a higher degree of understanding to implement.

Either way, it comes down to the simple question.

Do you limit the language you use, or limit the ability to test your code's consistency?

My personal bias is toward expressiveness, the TDD school of thought's bias is toward consistency. YMMV.

I look forward to many years of religious wars over this topic.

Title: OO PHP static keyword, should I use it?

Body:
I'm writing script for fb and I have 3 objects that I'll be using through all classes. I'm wondering if there is any advantage in using the static keyword except I don't have to create an instance every time I need to use a method/object? Which way should I go, with static or without it?

I know this is basic, but I'm new to OOP and I want to learn to use it in a proper manner.


答:
wxwidgets is licensed under essentially = LGPL + static linking

...essentially the L-GPL (Library General Public Licence), with an exception stating that derived works in binary form may be distributed on the user's own terms. This is a solution that satisfies those who wish to produce GPL'ed software using wxWidgets, and also those producing proprietary software.

wxWidgets is Certified Open Source Software Participants in the discussion that led to this decision include the folk from Abisource, Robert Roebling, Julian Smart, Markus Fleck, Karsten Ballueder, and some advice from Richard Stallman. Richard has confirmed that the new licence is compatible with GPL'ed applications. However, there are no significant restrictions on proprietary applications.

The wxWindows Licence has been approved by the Open Source Initiative, and you can find the licence on their site here...


问:
Identifying elements from data feeds generated by affiliate sites
I am working with data feeds from affiliate sites. The basic idea is to provide an interface where the user can paste a link to an XML datafeed (these are huge btw, around 60 mb) that would then be streamed, parsed into small chunks, and mined for the required data which would then be stored in the database.

The problem is that different affiliate sites have different Schemas for their XML's. It is a little hard mapping the elements in an XML to your database attributes when you don't actually know which element contains what.

My Solution: Use XPath to traverse through the first set of parent and it's descendent's, fetch the elements as well as the data and and ask the user to map this data to the attributes in the database by selecting from a set of radio buttons that represent the attributes from the database. This will be done just once for each new Feed, once the system know's what's what it will automatically upload the data from the XML to the database.

Does this sound viable? Is there a better solution? I realize this leaves an uncomfortable opening for human error..

Thanks.

答:
Does this sound viable?

It is completely viable. XML data can be fetched by cURL through PHP and parsed as XML data.

For example, YouTube video data can be fetched as XML by:

1) cURL the XML data. YouTube follows the link format of:

http://gdata.youtube.com/feeds/videos/YOUTUBEID

2) XML Parser Create the object

3) XML Parse Into Struct the fetched content. You may need to write some custom functions to traverse the data to extract what you want. I usually write custom generic functions such as "getXMLvalueByAttribute", "getXMLvalueByTag", and "getTagStringData" to easily do this.

4) XML Parser Free the object once you are done storing it.

You did not specify exactly what kind of XML data, so I gave you the YouTube example above.

Is there a better solution?

I would definately check if the service/website has an API available. This normally will save you time and energy if one is available.

OwnerDisplayName: SPI


问:
What do you optimize for?
Generally speaking, what type of optimizations do you typically slant yourself towards when designing software?

Are you the type that prefers to optimize your design for

Development time (i.e., quick to write and/or easier to maintain)?

Processing time

Storage (either RAM, DB, Disc, etc) space

Of course this is highly subjective to the type of problems being solved, and the deadlines involved, so I'd like to hear about the reasons that would make you choose one form of optimization over another.

答:
It depends on the need of your program.

Most of what I do is constrained heavily by processing capability and memory, but does not go through very many, if any, significant changes in the average year.

I have in the past worked on projects where the code is changed frequently so the maintainability becomes more important in those cases.

I have also worked on systems in the past where the amount of the data is the most significant issue, even on disk for storage, but more commonly the size becomes an issue when you have to move the data a whole lot, or over a slow link.

Title: What do you optimize for?


问:
Best method to organize/manage dependencies in the VCS within a large solution
A simple scenario:

2 projects are in version control

The application

The test(s)

A significant number of checkins are made to the application daily.

CI builds and runs all of the automation nightly.

In order to write and/or run tests you need to have built the application (to reference/load instrumented assemblies). Now, consider the application to be massive, such that building it is prohibitive in time (an entire day to compile). The obvious side effect here, is that once you've performed a build locally, it is immediately inconsistent with latest.

For instance:

If I were to sync with latest, and open up one of the test projects, it would not locally build until I built the application. This is the same when syncing to another branch/build/tag. So, in order to even start working, I need to wait a day to build the application locally, so that the assemblies could be loaded - and then those assemblies wouldn't be latest.

How do you organize the repository or (ideally) your development environment such that you can continually develop tests against whatever the current build is, or a given specific build, while minimizing building the application as much as possible?

答: Package repositories like Artifactory and package management systems like Ivy and NuGet are good answers to this sort of problem.  Build the packages you want to build, download the rest through a local-hard-drive cache of current versions, and you're good to go.</p>


答:
For the background you gave, if I may paraphrase:

You're familiar with Ruby/Python.

You don't see the advantages of Clojure yet.

You don't find either Lisp or Clojure syntax clear.

...I think the best answer is to read the book Clojure Programming by Emerick, Carper and Grand.  The book has numerous explicit code comparisons with Python, Ruby, and Java, and has text explanations addressing coders from those languages.  Personally, I came to Clojure after building good-sized projects w/ Python, and having some Lisp experience; reading that book helped convince me to start using Clojure not just in side-projects but for professional ends.

To address your two questions directly:

What's so good about Clojure? Plenty of answers on this site and elsewhere, e.g. see https://www.quora.com/Why-would-someone-learn-Clojure

What is the absolute minimum that I should know about the language in order to appreciate it?  I'd suggest knowing the big ideas behind Clojure's design, as articulated in both Clojure Programming and The Joy of Clojure books-wise, and in Rich Hickey's talks, esp. the talk Simple Made Easy.  Once you know the what/why you can then start understanding the how when reading Clojure code, esp. how to change your thinking from classes, objects, state/mutation to "just functions and data" (higher-order functions, maps/sets/sequences, types).

Additional suggestions: Lisp's elegance and power is partly from its minimalist and utterly consistent syntax.  It's much easier to appreciate that with a good editor, e.g. Emacs with clojure-mode and ParEdit.  As you get more familiar with it, the syntax fades away and you'll "see" semantics, intentions, and concise abstractions.  Secondly, don't start by reading the source for ClojureScript or Compojure, those are too-much-at-once; try some 4clojure.org problems, and compare solutions with the top coders there.  If you see 4-6 other solutions, invariably someone will have written a truly idiomatic, succinct FP-style solution which you can compare with a clumsy, verbose, and needlessly complicated imperative-style solution.

Title: What's so great about Clojure?


问:
How can I tell whether my computer is Harvard or von Neumann architecture?
I understand the difference between the two architectures is the separation of instructions from data in the Harvard architecture. But how do I know which type of system I'm on? Is it possible to write a program such that the program determines whether the system is von Neumann or Harvard? Could there be another architecture or are these architectures the only ones known?</p>

答: Your computer is a von Neumann machine.  All general purpose computers are.  The only exceptions are specialized co-processors like GPUs.  It's not that you can't have a Harvard machine (or any other architecture).  It's just that nobody builds them, especially not for sale (modulo co-processors, of course).


问:
Computer vision algorithms (how is this possible?)
I recently stumbled across a company that has created what appears to be a computer vision technology that is capable of detecting shoplifting automatically and alert its users.

LINK

Watching some of the videos and examples provided by the company has left me completely baffled and amazed as to how on earth they may have achieved this functionality.

I understand that no-one here will be able to tell me exactly how this may have been achieved but is anyone aware - and could point me to - research in this field or alternatively perhaps provide details as to how something like this could be implemented or guidance of where one might start?

My understanding was the computer vision algorithms were many years away from being this  sophisticated. Is this sort of application really possible? Anyone willing to hazard a guess at how they achieved this?

答:
You're misinformed about the state of the art.  Several years ago I worked for a company that built such systems for a variety of purposes.  One was an extremely successful airport egress-control system, which could easily tell the difference between a person walking the wrong way down the exit hallway and things like balls in motion or people headed the right way.  Recognizing objects in a scene in real-time isn't easy, but we were doing it on embedded CPUs, not on supercomputers.

I didn't see anything there that wasn't believable a few years ago.


答:
And the #1 item on our top 10 list is ...

(drum roll)

Every developer builds with exactly the same versions of all the dependencies, so you never have to wonder what to deploy into production.

Title: How can I make a case for "dependency management"?

Body:
I'm currently trying to make a case for adopting dependency management for builds (ala Maven, Ivy, NuGet) and creating an internal repository for shared modules, of which we have over a dozen enterprise wide.  What are the primary selling points of this build technique?  The ones I have so far:

Eases the process of distributing and importing shared modules, especially version upgrades.

Requires the dependencies of shared modules to be precisely documented.

Removes shared modules from source control, speeding and simplifying checkouts/check ins (when you have applications with 20+ libraries this is a real factor).

Allows more control or awareness of what third party libs are used in your organization.

Are there any selling points that I'm missing?  Are there any studies or articles giving improvement metrics?


问:
Which language is more suitable heavy file tasks?
I need to write a script (based on basic functions) to process /image/audio/video files. The process is mainly filesystem tasks and converts. The database of files has been stored by mysql. The script is simple but cause heavy tasks on the system; for example renaming/converting/copying thousands of file in a run. The script does not read the content of files into memory, it just manage the commands for sub-processes. The main weight is on the communication with filesystem. The script will be used regularly for new files. My concern is about performance. I am thinking of

Shell script

a complied language like C

Please advise which programming language is more suitable for this purpose and why?

UPDATE: An example is to scan a folder for images, convert them with ImageMagick, move files to destination folder, get file info, then update the database. As you can see, the process has no room for optimization, and most of languages have similar APIs for popular programs like ImageMagick, MySQL, etc. Thus, it can be written in any language. I just wish to reduce resource usage by speeding up the long loop.

NOTE: I know that questions about comparing languages are not favorable, but I really had problem to choose, because the problems can appear in action.

答:
If you are going to be using this script/program 100x more than the time it takes to write then I would write some simple test in both ways and run some timing test.

Way back when I used VB 6, I could do file I/O using VB, but I could also call the system routines directly in the DLL from VB 6 and sometimes get better than 100x performance. It's not really the language, but how well you can wield it effectively.

If the shell is eaiser to use and can make direct use of the low-level system functions then use that, otherwise go with the C program and use the low-level system functions. The point is the low-level system functions should out run any language trying to do the same thing by a noticeable to signifigant amout. You give up the safety of the script/language for the speed.

EDIT

Based on your update, I would focus on getting ImageMagick to use multiple threads.

See: Multi-threaded operations? which suggest

If you add --enable-openmp to your configure script command line and
  build ImageMagick, convolution operations run in multiple threads
  (e.g. blur, sharpen, unsharp mask, edge, etc).

I would do this in whatever language is easiest as it appears the best performance gain cannot be had in the language you choose but configuring the apps.


答:
I'd consider python or any other high-level, dynamic, interpreted language for these reasons:

Relatively easy to pick up

Mangling filenames, string slicing, etc. is easy

DB access is similarly pretty straightforward using a built-in module

Using the threading module gives quick, simple, easy to understand concurrency, and is effective so long as the python program is I/O bound (waiting on FS copy, for example)

Title: Which language is more suitable heavy file tasks?

Body:
I need to write a script (based on basic functions) to process /image/audio/video files. The process is mainly filesystem tasks and converts. The database of files has been stored by mysql. The script is simple but cause heavy tasks on the system; for example renaming/converting/copying thousands of file in a run. The script does not read the content of files into memory, it just manage the commands for sub-processes. The main weight is on the communication with filesystem. The script will be used regularly for new files. My concern is about performance. I am thinking of

Shell script

a complied language like C

Please advise which programming language is more suitable for this purpose and why?

UPDATE: An example is to scan a folder for images, convert them with ImageMagick, move files to destination folder, get file info, then update the database. As you can see, the process has no room for optimization, and most of languages have similar APIs for popular programs like ImageMagick, MySQL, etc. Thus, it can be written in any language. I just wish to reduce resource usage by speeding up the long loop.

NOTE: I know that questions about comparing languages are not favorable, but I really had problem to choose, because the problems can appear in action.


答: Harvard Architecture is typically only used in embedded microprocessors where the program is stored in on-board eeprom memory. The only one you are likely to see is an Atmel AVR as used in the Arduino</p>

Title: How can I tell whether my computer is Harvard or von Neumann architecture?

Body: I understand the difference between the two architectures is the separation of instructions from data in the Harvard architecture. But how do I know which type of system I'm on? Is it possible to write a program such that the program determines whether the system is von Neumann or Harvard? Could there be another architecture or are these architectures the only ones known?</p>


答:
It sounds to me like you will simply be handing these files to another piece of software to actually read them in. If that's the case, use python or ruby or whatever easy to use high level language you have on hand because this program isn't actually IO intensive.

Now, if you are actually reading the contents of files in yourself to process on your own then I would say if the language you normally use doesn't have any interoperability for making OS level calls, don't use that language.

Ideally in this case you'd want a high level language with low level facilities.

C# for instance does this well in allowing high level handling of the simple stuff like processing the user input from command line and organizing the steps of your task or whatever else, but then allowing OS calls and direct memory management for highest possible performance (if necessary!). Java may do similarly? Not certain. Haskell is very high level as well as having facilities for direct memory manipulation, though Haskell has an extremely high barrier for learning if you don't already know it. C++ is probably the most commonly used language for this type of task for this exact purpose, it is a high level language and with C in it's roots it has complete low level facilities available.

That said, beware of premature optimization. Writing a program in a language that isn't your strongest language will likely under perform the one you could write in your native language as you wouldn't be aware of available optimizations or be using the language appropriately. Further the only way to know if the quickest most robust route of using your main language won't work is by giving it a go which would be far quicker than going all in on a language you don't know. So prototype something and see how it performs, if you don't think it does well enough then whip up a quick prototype in other languages and compare.

Prototyping as a part of your technical solution analysis is an ever important skill for all programmers, so take advantage of this task to practice it. In the scientific method we don't try to prove our hypothesis as that leads to bias, rather we try to disprove them. Your hypothesis is your normal language won't perform well enough for this task, so start by trying to disprove that.

Edit:
Based on your edit, your program is absolutely not IO intensive, so write it in the language you are most comfortable with


答:
Most current general purpose CPUs use Modified Harvard Architecture. The CPU cores can access program and data independently in their separate L1 caches. At the outside, there are no separate program and data memories (nor the other cache levels are separated).

Could there be another architecture or are these architectures the only ones known?

All the other architectures are rather restricted in their use. Because of the extreme complexity and costs associated with processor development, I don't think anybody would try it seriously again.

However, while modern CPUs are basically von Neumann, they incorporate a lot of ideas like Dataflow Architecture internally.


问:
Should the 12-String be in its own class and why?
This question is regarding a homework project in my first Java programming class (online program).

The assignment is to create a "stringed instrument" class using (among other things) an array of String names representing instrument string names ("A", "E", etc).  The idea for the 12-string is beyond the scope of the assignment (it doesn't have to be included at all) but now that I've thought of it, I want to figure out how to make it work.

Part of me feels like the 12-String should have its own class, but another part of me feels that it should be in the guitar class because it's a guitar.  I suppose this will become clear as I progress but I thought I would see what kind of response I get here.

Also, why would they ask for a String[] for the instrument string names?  Seems like a char[] makes more sense.

Thank you for any insight.

Here's my code so far (it's a work in progress):

```<code>public class Guitar {

private int numberOfStrings = 6;
private static int numberOfGuitars = 0;
private String[] stringNotes = {"E", "A", "D", "G", "B", "A"};
private boolean tuned = false;
private boolean playing = false;

public Guitar(){
    numberOfGuitars++;
}

public Guitar(boolean twelveString){
    if(twelveString){
        stringNotes[0] = "E, E";
        stringNotes[1] = "A, A";
        stringNotes[2] = "D, D";
        stringNotes[3] = "G, G";
        stringNotes[4] = "B, B";
        stringNotes[5] = "E, E";
        numberOfStrings = 12;
    }
}

public int getNumberOfStrings() {
    return numberOfStrings;
}

public void setNumberOfStrings(int strings) {
    if(strings == 12 || strings == 6) {
        if(strings == 12){
            stringNotes[0] = "E, E";
            stringNotes[1] = "A, A";
            stringNotes[2] = "D, D";
            stringNotes[3] = "G, G";
            stringNotes[4] = "B, B";
            stringNotes[5] = "E, E";
            numberOfStrings = strings;
        }
        if(strings == 6)
            numberOfStrings = strings;
    }//if
    else
        System.out.println("***ERROR***Guitar can only have 6 or 12 strings***ERROR***");
}

public void getStringNotes() {
        for(int i = 0; i < stringNotes.length; i++){
            if(i == stringNotes.length - 1)
                System.out.println(stringNotes[i]);
            else
                System.out.print(stringNotes[i] + ", ");
        }//for
}
</code>```

答:
The design decisions such as the one you mention should be driven by the requirements. Since it seems purely a modelling exercise, you shouldn't worry too much.

As a general rule for less future headaches, favour inmutable classes, so I would get rid of that setter.

I'd also use enums instead of char arrays.

Finally try not repeating chunks of code. That's just increasing the likelihood of bugs and makes it harder to understand the code.

Ah, and don't forget to document your code: what does a method do, preconditions, postconditions, exceptions.


问:
Why do .Net books talk about stack vs heap memory allocation?
It seems like every .net book talks about value types vs reference types and makes it a point to (often incorrectly) state where each type is stored - the heap or the stack.  Usually it's in the first few chapters and presented as some all-important fact.  I think it's even covered on certification exams. Why does stack vs heap even matter to (beginner) .Net developers?  You allocate stuff and it just works, right?</p>

答:
It seems like every .NET book talks about value types vs reference types and makes it a point to (often incorrectly) state where each type is stored - the heap or the stack. Usually it's in the first few chapters and presented as some all-important fact.

I agree completely; I see this all the time.

Why do .NET books talk about stack vs heap memory allocation?

One part of the reason is because many people came to C# (or other .NET languages) from a C or C++ background. Since those languages do not enforce for you the rules about storage lifetime, you are required to know those rules and implement your program carefully to follow them.

Now, knowing those rules and following them in C does not require that you understand "the heap" and "the stack". But if you do understand how the data structures work then it is often easier to understand and follow the rules.

When writing a beginner book it is natural for an author to explain the concepts in the same order that they learned them. That's not necessarily the order that makes sense for the user. I was recently technical editor for Scott Dorman's C# 4 beginner book, and one of the things I liked about it was that Scott chose a pretty sensible ordering for the topics, rather than starting in on what really are quite advanced topics in memory management.

Another part of the reason is that some pages in the MSDN documentation strongly emphasize storage considerations. Particularly older MSDN documentation that is still hanging around from the early days. Much of that documentation has subtle errors that have never been excised, and you have to remember that it was written at particular time in history and for a particular audience.

Why does stack vs heap even matter to (beginner) .NET developers?

In my opinion, it doesn't. What is much more important to understand is stuff like:

What is the difference in copy semantics between a reference type and a value type?

How does a "ref int x" parameter behave?

Why should value types be immutable?

And so on.

You allocate stuff and it just works, right?

That's the ideal.

Now, there are situations in which it does matter. Garbage collection is awesome and relatively inexpensive, but it is not free. Copying small structures around is relatively inexpensive, but is not free. There are realistic performance scenarios in which you have to balance the cost of collection pressure against the cost of excessive copying. In those cases it is very helpful to have a strong understanding of the size, location, and actual lifetime of all relevant memory.

Similarly, there are realistic interop scenarios in which it is necessary to know what is on the stack and what is on the heap, and what the garbage collector could be moving around. That's why C# has features like "fixed", "stackalloc" and so on.

But those are all advanced scenarios. Ideally a beginner programmer need worry about none of this stuff.


答:
IANAL, but I have been led to believe, that one solution is to provide object files for non-LGPL parts. That way user can re-link the program and so is free to change the LGPL part, fulfilling requirements of LGPL.

In other words, you need to have source package, with LGPL sources and compiled object files of non-LGPL code. Obviously you then need to provide object files for every different architecture you release the binaries for, but I don't think this is much of an issue.

From development point of view, simplest might be to just have the build system also build the source package at the same time, when building the binary for distribution.


问:
.Net search engine architecture and technology choice
I am in the process of designing a search engine for an asp.net site. The site currently uses Microsoft Indexing Server to index and search content which range from simple text files to MS documents to PDFs. MIS is also used to crawl File servers. MIS in tandem with Index Server Companion crawls for content from external sites. I intend to replace MIS with the indexer/crawler I am trying to build.

The motivation for going away from MIS is

1.MSFT would be discontinuing MIS support in their upcoming Server 2012 releases.

2.Major PaaS providers do not support MIS.

Since my platform is completely on the Microsoft stack, I cant afford(due to deployment/maintenance issues than cost issues) to have a Java application server. Thus, Solr, and effectively, SolrNet is ruled out.

With this being the context, I have couple of questions.

1.Technology choice

I had done my initial investigation and looked at Lucene.Net. There seemed to be 2 issues in using Lucene.Net. First being, it cant crawl external content. There doesn't seem to be a direct port of Nutch in .Net. Second, since it is just an indexer, it cant parse various document types. The parsing is left to the developer.

So, what would be best technology choice on the .Net platform to achieve indexing & crawling? Are there any .Net open source libraries available for document parsing?

2.Architectural pattern

Is there any general architectural pattern or best practice that needs to be followed in designing such a search engine?

答:
This link might give you some answers on how to parse various file formats, especially the link that shows how to use Tika from .net with IKVM.

I am developing applications using the Microsoft stack and I can tell you that running a Tomcat server with a Solr instance is affordable. The only reason not to use Solr that would seem valid to me is that the hosting company cannot offer this kind of services, but even then, there is nothing preventing me from having another server running Tomcat on a different machine. I would prefer to spend money on this alternative rather than investing in developing yet another search engine. If you still want to go with developing your own search engine, I would recommend starting with the Solr documentation. There are tons of useful things there.