问:
Seeds distribution algorithm with complexity better than O(n^3)?
I have included my approach and solution. My solution works fine, however, is unoptimized with O(n^3) complexity

An NGO is running seed distribution program. It has limited quantity of varied quality seeds. In order to get seeds, farmer needs to request number of seeds. Seed distribution happens only on Sunday with goal that maximum farmers gets best quality seeds of same type.

Consider, NGO has following seeds and count (Ordered by quality - Top is highest):

```<code>|Quality|Fruit1|Fruit2|Fruit3|
|-------|------|------|------|
|Highest|     3|     3|     1|
|Medium |     2|     0|     0|
|Low    |     4|     0|     0|
</code>```

Required Seeds:

Farmer 1: 2

Farmer 2: 3

Farmer 3: 1

Farmer 4: 2

Farmer 5: 3

Output: Goal is to assign highest quality seeds to maximum farmers.

Farmer 1: Highest Fruit1

Farmer 2: Highest - Fruit2

Farmer 3: Highest - Fruit1

Farmer 4: Medium - Fruit1

Farmer 5: Low - Fruit1

Here, farmer 1 and 3 in combination requested for 3 seeds, hence, in combination got highest fruit1.

My approach (Pseudocode)

I have a following domain classes - Farmer, , QualityType, FruitType, Seeds

QualityType has list of FruitType which has list of seeds.

To obtain result, I am doing following:

Iterate from highest Quality type to lowest.

nested iterate to fruit type and seeds.

For any seeds, check if we have farmer1 asking for same number of seeds - either alone or in combination with any one else.

If not move to farmer two.

This works however isn't optimized as it has 3 nested loops.

Can you please suggest any algorithm that can simplify it?

答:
The best way is to divide the problem space first, so you only have to consider how many farmers want how many seeds of a particular fruit type and quality. You can do this in a single iteration. You need to know how many of each fruit and seed type is being requested.

Then divide the number of seeds of each quality by the desired number, rounding down, and assigning the remainder by giving 1 to the limited number of farmers. You can optimise this by determining the remainder as a fraction and giving the extra seed to that fraction of farmers (eg 7 seeds, 4 farmers = 1 1/3 seed each, meaning a farmer gets 1 less than what they asked for plus an extra 1 if the farmer counter <= 7 % 4. (although this breaks down if the fraction is less than 1 eg 4 seeds, 7 requested, in which case every farmer gets 0 seeds initially, the remainder is still allocated as before)

This makes it 2 iterations: 1 to build the set of farmers's requirements and another to fulfill them.


问:
C++ using shared_ptr with API
I'm building a library that generates a couple of types of objects that can be used by user code and the library. To keep track of these objects, I'd like to use shared_ptr's, so I can build in some run-time clean up. Since these are consumed by user code, I was curious if it would be worth typedefing the shared_ptr type to simplify the user code. So instead of std::shared_ptr<Foo>, user code could use FooPtr or something.

Would that be a reasonable thing to do, or is the risk of unclear code too much?

答:
One of the benefits of the C++ smart pointers is that their names document ownership semantic information and memory management information.

For example:

A std::shared_ptr<Foo> clearly suggests that this instance of Foo is intended for shared usage.

Similarly, std::unique_ptr<Foo> clearly suggests that this instance is uniquely owned and exists only for the lifetime of the unique_ptr.

By hiding which pointer type you are using behind a typedef such as FooPtr you are hiding that information from your users.

Ultimately, I would say in this case hiding the information is not desirable because now your users cannot be sure who is responsible for destroying the FooPtr without referring to a comment or other documentation that you provide about FooPtr usage.

Instead, leaving it as std::shared_ptr<Foo> or std::unique_ptr<Foo> makes it clear that memory management for the Foo is handled by the ptr object itself.

ContentLicense: CC BY-SA 3.0

Title: C++ using shared_ptr with API


问:
OODesign: Data Structure which calls algorithm on insert
I have a data structure which has an add function.
When the user instantiates a new data structure object, she can specify an algorithm which will be executed each time the add function is called and alters the newly inserted value based on the previous values in the data structure. The algorithm needs to have access to all the data in the data structure.

Thus the data structure needs to store an algorithm object (since this is called each time the add is executed). On the other hand the algorithm needs access the data structure, and thus needs to store the data structure object.

I think situations where class A has an instance of class B and class B has an instance of class A are usually undesirable.

Does anybody have an idea how to solve this recurrence here?

答:
Classes A and B should not have-a instance of each other; that way lies madness.

You make no mention of what the post-add algorithms do, but since they must have access to the instance of A, they need to be methods of A, ignoring troublesome constructions like friend functions.

```<code>class A:
  member x
  member y

  constructor(x, y, post_add_func(pointer or reference or name)

  method add()
      do_add_stuff
      call_post_add_func

  method post_add_1()
  method post_add_2()
</code>```

This allows an "algorithm" to be bound to an instance of A, thus giving it full access to the members and methods of A.

I don't understand what the expected purpose of class B is, I suspect it was just a container for "algorithms" and will add unnecessary complexity. B probably doesn't need to exist.

Body:
Classes A and B should not have-a instance of each other; that way lies madness.

You make no mention of what the post-add algorithms do, but since they must have access to the instance of A, they need to be methods of A, ignoring troublesome constructions like friend functions.

class A:
  member x
  member y

  constructor(x, y, post_add_func(pointer or reference or name)

  method add()
      do_add_stuff
      call_post_add_func

  method post_add_1()
  method post_add_2()

This allows an "algorithm" to be bound to an instance of A, thus giving it full access to the members and methods of A.

I don't understand what the expected purpose of class B is, I suspect it was just a container for "algorithms" and will add unnecessary complexity. B probably doesn't need to exist.


问:
Should instance of Employee contain a reference to instance of Office, or should Office contain an array of Employee?
Title is an abstraction of what I am actually doing, but in essence the same.

The main entity I will be dealing with are the Employees themselves; "Send package to employee John Doe". In order to work with a given Employee, I need to use the IOffice they belong to, and each office has a different way of delivering that package to that Employee. I am not really interested in how the package is delivered, just that it gets there.

In the first way mentioned in the title, it would look something like this:

```<code>public class Employee
{
    private IOffice _office;

    public Name { get; set; }

    public void Send(Package package)
    {
        _office.Send(package, this)
    }
}

public class SomeOffice : IOffice
{
    public void Send(Package package, Employee employee)
    {
        // Implementation of how this office gets the package to employee
    }
}
</code>```

Doing it this way, I can simply have a list of all employees, and employees in the same office can share the same IOffice object.

The second approach like so:

```<code>public class Employee
{
    public Name { get; set; }
}

public class SomeOffice : IOffice
{
    public List<Employee> Employees { get; set; }

    public void Send(Package package, Employee employee)
    {
        // Implementation of how this office gets the package to employee
    }
}
</code>```

This makes it harder to have instance of Employee and send a package to it. You must get the instance you want from the Employees-collection, and pass it into the office's Send-method. However, it keeps the Employee-class simpler, and makes the IOffice take care of everything.

There are probably other ways to go about this also. How would you do it?

Edit:
For concrete example, replace IOffice with a CommunicationInterface, such as SerialPort, UdpClient, TcpClient etc.

At the end of each endpoint there are different Devices (Employees). These devices all behave similarly, but how to send them a request (Package) and get a response back differs.

From my program, I want to have a list of all available devices, across all CommunicationInterfaces, and send requests to them, and get responses back.

答:
The send function is a red herring, because it is unrelated to the basic question, which is whether you should have each employee know their office, or whether you should have each office know which employees are in it.  The send function does not affect, nor is it affected by, the answer to the basic question.  It probably should not be a function of either Office or Employee; it is an application concern, so it probably belongs to your application logic.  (Some Application object perhaps.)

Now, you seem to understand that the two approaches are equivalent: you can have each employee know their office, or you can have each office know which employees are in it.

Personally, I would go with the first approach, because it more readily maps to a relational database model, and this has specific advantages.  In a database, this kind of relationship would always be implemented by including in each employee row the id of the office row that the employee belongs to.  The fact that this is how it is done in relational databases should, in and by itself, be sufficient reason to choose this approach, but if you want specific examples of why it would be better, consider this:

There is a possibility of error.  Two offices may, by mistake, contain the same employee, in which case you have invalid data.  As a matter of fact, in relational databases this is called a many-to-many relationship, where it is in fact permissible for many entities of one kind to be related to many entities of another kind; but your situation does not call for a many-to-many relationship, therefore it should not be implemented as if it was a many-to-many relationship.

Suppose you want to delete an employee.  If each office has its own list of employees, then in addition to deleting the employee object, you now have to visit all of your office objects, see if any one of them contains that employee, and if so, remove the employee from the list of employees of that office.


问:
Design approach to outsourcing a socket in an own thread
I want to extend an existing server written in C++ to be able to communicate with an other server over websockets (e.g. logging or user authorisation purposes). All examples (including the very well written Beej's Guide) I've found have an infinite loop (e.g. for, or while) to handle the socket's send and receive methods. The main problem with these examples (e.g. chat server/clients) is, that the servers are focussed on the sockets, which means that a server blocks during the send and receive process and is not available for any other operation.

Well therefore I thought that I may outsource the whole socket communication in an own thread and only call the send method from the main program, while the whole process of sending the request and wait for the answer is done inside the thread. When an answer from the other server arrives, the threads sends the information back to the main program, which validates and process the information. Because of my experience with node.js I would like to have a kind of a callback to process the answer in the main program (wouldn't that be easy?).

Besides my leak of knowledge how I can exchange data between the parent process and the threads (which was started already) I'm struggling to find an example, how you can avoid a socket to block the whole program, while the parent program can focus on other tasks and can use the socket in an "asynchronous" way. I'm sure that this is not an unusual problem and I would be glad if someone has an hint or idea.

My actuall idea is to use fork() for creating a child which handles all the I/O with sockets (then I dont care if it blocks) and use a pipe to async read and write between the parent and the child. But I'm still looking for a usefull example.

答:
The blocking read is antiquated; modern servers use a asynchronous read where the program passes a buffer to the API where the data should end up in and gets a token representing the operation. No extra threads necessary.

Several token can be waited for at the same time so the server can dispatch a several reads and writes and then wait on all tokens until any finished and when one does use the token that woke up the thread to identify which operation succeeded and continue the work needed for that socket. (this is what node.js does behind the scenes).

Though your problem with the thread communicating is a producer/consumer problem, the main thread writing to each socket is a producer and each thread writing is a consumer. Each thread reading from the socket is a producer and the main thread waiting on the reads is a consumer.


答:
The data structure should contain a link to the algorithm, since it has exactly one algorithm.  Right?  (as I understand the requirements)

But the same algorithm, say, "normalize to the average" could work on many different instances of the data structure.  So it should not contain/store an instance of the data structure.  Instead, its method should take the datastructure as an additional argument.  e.g.

```<code>calculate(newValue, existingDataStructure);
</code>```

Then, your datastructure's add() method calls

```<code>tweakedValue = this.algorithm.calculate(newValue, this);
this.add(tweakedValue);
</code>```

Title: OODesign: Data Structure which calls algorithm on insert

Body:
I have a data structure which has an add function.
When the user instantiates a new data structure object, she can specify an algorithm which will be executed each time the add function is called and alters the newly inserted value based on the previous values in the data structure. The algorithm needs to have access to all the data in the data structure.

Thus the data structure needs to store an algorithm object (since this is called each time the add is executed). On the other hand the algorithm needs access the data structure, and thus needs to store the data structure object.

I think situations where class A has an instance of class B and class B has an instance of class A are usually undesirable.

Does anybody have an idea how to solve this recurrence here?

Body:
The data structure should contain a link to the algorithm, since it has exactly one algorithm.  Right?  (as I understand the requirements)

But the same algorithm, say, "normalize to the average" could work on many different instances of the data structure.  So it should not contain/store an instance of the data structure.  Instead, its method should take the datastructure as an additional argument.  e.g.

calculate(newValue, existingDataStructure);

Then, your datastructure's add() method calls

tweakedValue = this.algorithm.calculate(newValue, this);
this.add(tweakedValue);


问:
Algorithm to maintain a blog sign up page
I have a functional sign up page for a blog that updates a database with a users name, email, profile picture and a short bio. The General information page and the profile picture upload/bio page are two separate pages and I have a problem with users being able to go back into their profile pic page and re-entering their information again for their bio and user which then screws the entire database up. While incorporating php $_SESSION, I want to be able to track a users progress with the form and if attempting to update the same form page, have the user sent to their current page that has yet to be completed. I'm in search of an algorithm suitable for this and yet have not been able to implement one that works properly. The first page of my form looks to see if step01(general info form) has been completed.

```<code>    session_start();
if(!isset($_SESSION['step01']))
{
    if($_SESSION['step01']=='complete')
    {
        echo "<script>window.location.assign('localhost:8888/knoxville_programmers/blog-signup-propic.php');</script>";
    }
    else
    {
        $_SESSION['step01'] ='incomplete';
    }
}
</code>```

Upon completion of the first form the second form for uploading a user picture and bio checks if 1.) the first form is completed and 2.) that the current form hasn't already been completed. If it has then the user is redirected to their user page.

```<code>    session_start();
if(!$_SESSION['step01']=='complete')
{
    echo "<script>window.location.assign('localhost:8888/knoxville_programmers/blog-signup.php');</script>";
    #echo "<script>window.location.assign('localhost/knoxville_programmers/blog-signup.php');</script>";
}
elseif($_SESSION['step01']=='complete')
{
    if(!isset($_SESSION['step02']))
    {
        $_SESSION['step02']='incomplete';
    }
    elseif (isset($_SESSION['step02']))
    {
        if($_SESSION['step02']=='complete')
        {
            echo "<script>window.location.assign('localhost:8888/knoxville_programmers/user-page.php');</script>";
            #echo "<script>window.location.assign('localhost/knoxville_programmers/user-page.php');</script>";
        }
        else
        {
            $_SESSION['step02']='incomplete';
        }
    }

}
</code>```

My method of approach is error prone and i have not been able to have it work properly for a minute and am in need of a more suitable idea.

答:
I would look at reworking the way you save your data. Profile can exist without picture, while picture can't exist without profile.

So, once people are done with their profile, save it. Once they are done with picture, save it separately. Why separate the registration into a number of pages, if you don't save the data independently?


问:
Why are regular expressions so morbidly attractive?
Exhibit 1, Exhibit 2, I guess you won't find it hard to recall other examples.

Thing is: if there is more than one way to solve a problem, the PHP programmer (I usually browse the PHP tag on StackOverflow) will ask for help on the solution involving regular expressions.

Even when it will be less economic, even when the php manual suggests (link) to use str_replace instead of any preg_* or ereg_* function when no fancy substitution rules are required.

Does somebody have a clue about why this happens?

Don't get me wrong, some of my best friends are regular expressions and I don't despise Perl. What I don't get is why there is no looking for alternatives whatsoever, even when the overkill is obvious (regex to switch strings) or the code complexity rises exponentially (regex for getting data from html in PHP)

答: Because it's an efficient way to program a finite state machine, which is a powerful tool when it applies.  It's basically it's own language for programming FSMs, which is helpful if you know the language, annoying if you don't. </p>

ContentLicense: CC BY-SA 2.5


问:
Saving to Registry vs. CustomFile
I've been using the usual My.Settings... method when it came to saving settings for my program but I was just wondering, If I wanted to save program settings into the Registry and load those settings, are there any benefits when comparing with saving settings to a custom written file and loading those settings from the file.

Which would you prefer and why?

答: In the distant past, I would have suggested using the registry (as opposed to an INI file).  These days, I would lean toward file-based storage of settings and configuration.  The user-changeable parts of the settings should be persisted using the Isolated Storage API.</p>

Title: Saving to Registry vs. CustomFile


答:
One way to approach this problem without extending the tiers of your system is to implement the Command and Strategy patterns together in your design.  Encapsulate the actionable method (in your case, "add") as a Command and decorate it with a Strategy that encapsulates your algorithm.

Inside the Execute of your AbstractCommand, execute a virtual OnAfterExecute() method, which is where you state that you want your Algorithm to process. To tie the patterns together, conceptualize the responsibilities of your Context and of your Invoker as being the same.

Untested code. Typed by hand from memory.

```
public interface ICommand
{
    void OnBeforeExecute();
    void OnExecute();
    void OnAfterExecute();
    void Execute();
}
public abstract class Command : ICommand
{
    protected IStrategy Algorithm{ get;set; }
    public Command(IStrategy algorithm)
    {
      this.Algorithm = algorithm;
    }
    public virtual void OnBeforeExecute(){};
    public virtual void OnExecute(){};
    public virtual void OnAfterExecute(){};
    public virtual void Execute()
    {
       OnBeforeExecute();
       OnExecute();
       OnAfterExecute();
    };
}

public class AddCommand : Command
{
    private IPersistenceService PersistenceService {get;set;}
    public AddCommand(IStrategy algorithm, IPersistenceService persistenceService) :base(algorithm)
    {
       this.PersistenceService = persistenceService;
    }
    public virtual override OnExecute()
    {
       this.PersistenceService.ExecuteAddStuffs();
    }
    public virtual override OnAfterExecute()
    {
       this.Algorithm.Process();
    }
}

public interface IStrategy
{
    void Process();
}

public class HighPassFilterStrategy : IStrategy
{
    private IPersistenceService PersistenceService { get;set; }
    public void Process()
    {
       //Execute your HighPassFilter logic.
    }
}

//DomainProcess is your InvokerContext
//As an alternative design consideration, you could move the virtual 'On' methods
//up into DomainProcess and decouple the strategy from the command.
public class DomainProcess
{
    public ICommand Command{ get; protected set;}
    public DomainProcess(IStrategy strategy, ICommand command)
    {
       command.Algorithm = strategy;
       this.Command = command;
    }

    public void Run()
    {
       Command.Execute();
    }
}

public class YourDataStructure
{
   public string Foo {get;set;}
   public string Bar {get;set;}

   //List of DomainProcess. Won't accept angle brackets.
   //List"left angle bracket"DomainProcess"right angle bracket"
    private List DomainProcesses { get;set; }

    public DataStructure(List workflows)
    {
       this.DomainProcesses = workflows;

       //alternative, but indicative of poor design. **Objects should not
       //construct their own dependencies.**
       //---------------------------------------------------------
       //I'm including this so that I don't have to design all the way up to
       //Composition Root for this illustration.
       //---------------------------------------------------------
       if(!this.DomainProcesses.Any(process => process.Name.Equals("Add"))
       {
          var algorithm = new HighPassFilterStrategy();
          var command = new AddCommand();
          var add = new DomainProcess(algorithm, command);
          this.DomainProcesses.Add(add);
       }
    }

    public void AddRuntimeOperation(string name, ICommand command, IStrategy algorithm)
    {
       DomainProcess process = new DomainProcess(algorithm, command);
       process.Name = name;

       DomainProcesses.Add(process);
    }
    public void Add()
    {
       var add = this.DomainProcesses.Where(operation => operation.Name.Equals("Add'")).SingleOrDefault();

       add.Run();
    }
}
```

Your structure that currently has an Add method on it could instead encapsulate a DomainProcess called Add

```
  public void Add()
  {
    DomainProcess.Run();
  }
```

The OnBeforeExecute, OnExecute and OnAfterExecute methods are colloquially known as aspects.

If you are going to use an object hierarchy in your design, aspects should serve as your primary extension points of that hierarchy.

By creating the default implementation of Execute as an aggregation of these 3 aspects, you can very easily specify inside your Algorithms that you want them to be processed Before or After your main operation is executed.

More specific information about your requirements might change the recommendation.

Body:
One way to approach this problem without extending the tiers of your system is to implement the Command and Strategy patterns together in your design.  Encapsulate the actionable method (in your case, "add") as a Command and decorate it with a Strategy that encapsulates your algorithm.

Inside the Execute of your AbstractCommand, execute a virtual OnAfterExecute() method, which is where you state that you want your Algorithm to process. To tie the patterns together, conceptualize the responsibilities of your Context and of your Invoker as being the same.

Untested code. Typed by hand from memory.

public interface ICommand
{
    void OnBeforeExecute();
    void OnExecute();
    void OnAfterExecute();
    void Execute();
}
public abstract class Command : ICommand
{
    protected IStrategy Algorithm{ get;set; }
    public Command(IStrategy algorithm)
    {
      this.Algorithm = algorithm;
    }
    public virtual void OnBeforeExecute(){};
    public virtual void OnExecute(){};
    public virtual void OnAfterExecute(){};
    public virtual void Execute()
    {
       OnBeforeExecute();
       OnExecute();
       OnAfterExecute();
    };
}

public class AddCommand : Command
{
    private IPersistenceService PersistenceService {get;set;}
    public AddCommand(IStrategy algorithm, IPersistenceService persistenceService) :base(algorithm)
    {
       this.PersistenceService = persistenceService;
    }
    public virtual override OnExecute()
    {
       this.PersistenceService.ExecuteAddStuffs();
    }
    public virtual override OnAfterExecute()
    {
       this.Algorithm.Process();
    }
}

public interface IStrategy
{
    void Process();
}

public class HighPassFilterStrategy : IStrategy
{
    private IPersistenceService PersistenceService { get;set; }
    public void Process()
    {
       //Execute your HighPassFilter logic.
    }
}

//DomainProcess is your InvokerContext
//As an alternative design consideration, you could move the virtual 'On' methods
//up into DomainProcess and decouple the strategy from the command.
public class DomainProcess
{
    public ICommand Command{ get; protected set;}
    public DomainProcess(IStrategy strategy, ICommand command)
    {
       command.Algorithm = strategy;
       this.Command = command;
    }

    public void Run()
    {
       Command.Execute();
    }
}

public class YourDataStructure
{
   public string Foo {get;set;}
   public string Bar {get;set;}

   //List of DomainProcess. Won't accept angle brackets.
   //List"left angle bracket"DomainProcess"right angle bracket"
    private List DomainProcesses { get;set; }

    public DataStructure(List workflows)
    {
       this.DomainProcesses = workflows;

       //alternative, but indicative of poor design. **Objects should not
       //construct their own dependencies.**
       //---------------------------------------------------------
       //I'm including this so that I don't have to design all the way up to
       //Composition Root for this illustration.
       //---------------------------------------------------------
       if(!this.DomainProcesses.Any(process => process.Name.Equals("Add"))
       {
          var algorithm = new HighPassFilterStrategy();
          var command = new AddCommand();
          var add = new DomainProcess(algorithm, command);
          this.DomainProcesses.Add(add);
       }
    }

    public void AddRuntimeOperation(string name, ICommand command, IStrategy algorithm)
    {
       DomainProcess process = new DomainProcess(algorithm, command);
       process.Name = name;

       DomainProcesses.Add(process);
    }
    public void Add()
    {
       var add = this.DomainProcesses.Where(operation => operation.Name.Equals("Add'")).SingleOrDefault();

       add.Run();
    }
}

Your structure that currently has an Add method on it could instead encapsulate a DomainProcess called Add

  public void Add()
  {
    DomainProcess.Run();
  }

The OnBeforeExecute, OnExecute and OnAfterExecute methods are colloquially known as aspects.

If you are going to use an object hierarchy in your design, aspects should serve as your primary extension points of that hierarchy.

By creating the default implementation of Execute as an aggregation of these 3 aspects, you can very easily specify inside your Algorithms that you want them to be processed Before or After your main operation is executed.

More specific information about your requirements might change the recommendation.


问:
What should be the best way to run a long operation in Java Spring?
I am working on a price comparator, one of the module of application crawls through the list of website against the product stored in the database and updates the price in the application database.

This crawler is a slow process and might take around 3 to 4 hours daily to complete. To test the crawling on my local I was running the service method from my Junit test.

What should be the best way to run these service after I host the application on production ?

答:
Have a look at
http://www.quartz-scheduler.org/ to run it in a container such as Tomcat or JBoss.  You could alternately run it from cron (on a Unix box, of course), as a command line process.</p>


答:
You shouldn't be launching long running processes of any sort from a web app. It makes it difficult to do things like failover to another node in the cluster.

Instead, dispatch the "run this" to something outside of the webapp (and thus outside of Spring) so that the webapp can continue on with its life(cycle).

Instead of having a process (within the web container) doing the collecting, move this process to something outside of the web container.  A free standing process that somehow gets a message from the webapp and then starts doing its thing.

This "send a message" could be done with either a message queue, or even just sticking a row in a database.  The other process either listens for messages on the message queue (and then starts a worker thread) or periodically polls the database (and then starts a worker thread).

The worker thread then starts its processing of the page. One thing that the worker thread could then do is push new urls back into the message queue or database for the dispatcher to pick up and create new threads.  You would likely want to use a thread pool for this to avoid overloading your system (there are N workers in the pool available - if none are available, you wait until one is).  This would also be the location to make sure that you are properly throttling the requests to a single server (again, to make sure you aren't overloading their system).

Title: What should be the best way to run a long operation in Java Spring?

Body:
I am working on a price comparator, one of the module of application crawls through the list of website against the product stored in the database and updates the price in the application database.

This crawler is a slow process and might take around 3 to 4 hours daily to complete. To test the crawling on my local I was running the service method from my Junit test.

What should be the best way to run these service after I host the application on production ?


答:
I have a data structure which has an add function. When the user instantiates a new data structure object, she can specify an algorithm which will be executed each time the add function is called and alters the newly inserted value based on the previous values in the data structure. The algorithm needs to have access to all the data in the data structure

This is not a good idea and besides makes not really sense.

If I get you correctly, you want to create an object which contains some elements e1, e2, e3, .... At a given point in time, you want to do a transformation of the elements so far. At a later point, you want to do another transformation on the collection as a whole.

There is no need to do a transformation in between, since it makes no difference whether the collection stores the values plain vanilla or transformed. At a given point, you need to read or change the transformed values: this is the right point to do a transformation of the colletion (so far) as a whole.

If that is, what you want, this would be a perfect use-case for the visitor pattern:
In case, you have have Python at hand or do not mind installing it, here is a nice example how to set up the visitor pattern

```<code>#!/usr/bin/env python3

class Container:
    def __init__(self, values):
        self._values = values

    def transform(self, transformator):
        self._values = transformator.transform(self._values)

    def accept(self, visitor):
        visitor.visit(self)

class Visitor:
    pass

class Transformator(Visitor):
    pass

class DoublingVisitor(Transformator):
    def visit(self, container):
        container.transform(self)

    def transform(self, values):
        return list(map(lambda x: 2*x, values))

def main():
    container = Container([1, 2, 3])
    doublingVisitor = DoublingVisitor()
    container.accept(doublingVisitor)
    print(container._values)

if __name__ == '__main__':
    main()
</code>```

Anyways, the python code is easy to understand. The point is, you need one class which I called (lacking of a better name) Container, which accepts a Visitor. On the other hand, you need an object derived from Visitor, which holds as a Transformator the algorithm (which was the term you used). The Visitor needs one method visit, which has one parameter (the object, which it visits). That is the whole magic.

While visiting, the visitor calls the transform method on the object to visit, which in turn receives the Visitor / Transformator who implements a transform method. That's it.

Every time, you want to do something with your collection, you could accept another Visitor.

Body:
I have a data structure which has an add function. When the user instantiates a new data structure object, she can specify an algorithm which will be executed each time the add function is called and alters the newly inserted value based on the previous values in the data structure. The algorithm needs to have access to all the data in the data structure

This is not a good idea and besides makes not really sense.

If I get you correctly, you want to create an object which contains some elements e1, e2, e3, .... At a given point in time, you want to do a transformation of the elements so far. At a later point, you want to do another transformation on the collection as a whole.

There is no need to do a transformation in between, since it makes no difference whether the collection stores the values plain vanilla or transformed. At a given point, you need to read or change the transformed values: this is the right point to do a transformation of the colletion (so far) as a whole.

If that is, what you want, this would be a perfect use-case for the visitor pattern:
In case, you have have Python at hand or do not mind installing it, here is a nice example how to set up the visitor pattern

#!/usr/bin/env python3

class Container:
    def __init__(self, values):
        self._values = values

    def transform(self, transformator):
        self._values = transformator.transform(self._values)

    def accept(self, visitor):
        visitor.visit(self)

class Visitor:
    pass

class Transformator(Visitor):
    pass

class DoublingVisitor(Transformator):
    def visit(self, container):
        container.transform(self)

    def transform(self, values):
        return list(map(lambda x: 2*x, values))

def main():
    container = Container([1, 2, 3])
    doublingVisitor = DoublingVisitor()
    container.accept(doublingVisitor)
    print(container._values)

if __name__ == '__main__':
    main()

Anyways, the python code is easy to understand. The point is, you need one class which I called (lacking of a better name) Container, which accepts a Visitor. On the other hand, you need an object derived from Visitor, which holds as a Transformator the algorithm (which was the term you used). The Visitor needs one method visit, which has one parameter (the object, which it visits). That is the whole magic.

While visiting, the visitor calls the transform method on the object to visit, which in turn receives the Visitor / Transformator who implements a transform method. That's it.

Every time, you want to do something with your collection, you could accept another Visitor.


问:
How should dynamic, interruptible multitasking structure look like?
I am trying to make an AI that plays a game. Actually, I'm playing around with both StarCraft and MineCraft which are completely different kinds of games. As well, I use different programming languages for both, and one is multi-threaded (java), other event-driven single-threaded (Node.js).

Despite all those differences, I face the same problem: How can I make an AI that can handle tasks in sensible order, but also interrupt the tasks in cases of need and return to them later? How to make a sensible task chain (where one task causes another subtask)?

Examples of above can be:

In minecraft, you're digging a block and you're attacked by a monster

In starcraft you're leading an attack and a critical position in your base is attacked

In minecraft, task of chopping trees is caused by the task building the house - the bot must remember why is he doing what is he doing.

In starcraft, certain buildings are just built in order to unlock types of soldiers

I just was playing around with the idea, but I just kept writing and deleting completely stupid code...

This is what I have now, but it makes no sense. I can see many situations that will not be solved using this model.

```<code>/***
 *  Task pseudo class. After finishing the task, this task notifies the parent task.
 *  Arguments:
 *    action - function callback that will execute. The callback must call the finished() method in the end. The callback will receive
 *             this task's object as a first argument.
 **/
function Task(action, parent, name) {
  this.action = action;
  this.after = after;
  this.name = name||"Void task";
}

Task.prototype.start = function() {
  console.log("Task started...");
  try {
    this.action(this);
  }
  catch(e) {
    console.log("The task action has thrown an error: "+e);
  }
}
Task.prototype.finished = function() {
  console.log("Task over.");
}
//Override this
Task.prototype.pause = function() {};
</code>```

I am afraid I have a lot of reading to do about this. But are there some general known ideas I can start with?

答:
Your event handlers should be fast, like starting one game action and registering and event handler to do the next thing when that action completes. No event handler should be waiting game time for a game action to complete. In MineCraft when you start mining a block, you ask for an event when the mining finishes, and you might get an event before then that a monster is attacking. In Star Craft you give a unit an order to move/attack/build something, and ask for an event when that task is complete. While waiting for that event to occur you might get a different event that your base is under attack, or another unit has completed its task and needs further orders.

By organizing your high level actions into really fast low level actions triggered by events, you allow events relevant to other high level actions to come in the middle.


问:
Getting items from a ListView - without breaking MVC paradigm?
I've got an arraylist of SpecialParts.  A SpecialPart is an object that holds a bunch of information about itself: name, ID, date created, etc.

I've got a ListView that presents the user with all the names of the SpecialParts in this arraylist.  The user can select one of these parts in the list and then do stuff with it.

My problem is that ListView (in my case, '...swt.widgets.List') ONLY holds Strings of the names.  So even though I'd rather refer to these SpecialParts by their unique ID field, ListView doesn't hold that info.

Everywhere else we refer to these parts ONLY by unique ID, and I'd like to continue doing that.

I could create another column in this ListView, have it store the ID, set it to be invisible to the user, and then pull it out from there.  But that feels gross, if not totally against the MVC contract.

How should I go about referring to these parts by unique ID when the list contains only String names?  Am I thinking about this problem correctly?

(last note -- I'm only vaguely aware of the MVC paradigm, not a pro, so if anything I said about it is wrong, I'm sorry.  also, this is Java, if it helps)

答:
There exist bindings you can use to bind list items with data.  This does exactly what I need.

http://www.vogella.com/tutorials/EclipseDataBinding/article.html#tutorial_observablemaplabelprovider


答:
You are building a handcrafted AI Agent, often called an Intelligent Agent (IA); its 'environment' is the game, its 'sensors' are programmatic functions that gather input, its 'actuators' are also functions that output the keyboard/controls the game processes as input.

To the best of my knowledge, if you are writing a handcrafted AI, a state-machine (SM) is probably the best way to start; and will likely get you the biggest result for your efforts.

Handcrafting a SM would let you encode priorities into the states and/or state-transitions. A danger signal could cause a transition to a defense state, then when the danger has been dealt with, you can resume the previous state. Alternatively you could just transition to the next highest priority state. This could leave an objective unfinished, but this may be acceptable. For example it may not be efficient to path back to where you were if the dangerous encounter displaced your AI's position to another location; i.e. re-evaluating what state to transition based on the current context is probably the correct thing to do.

Handcrafting an Agent will only get you so far, in essence you will transferring your expertise and knowledge to the agent. Because of this you will only be able to transfer some fraction of your knowledge to the agent. This process will be difficult, lengthy and error-prone, and your agent will never play 'better' than you, since it only has some subset of your knowledge about the game.

The alternative to hand-crating an agent, is to build a Learned Agent, i.e. one based on Machine Learning.

A learning system needs an objective function, also called a loss function, which needs to encode many things:

goals

survival

rewards

penalties

...

The learning system will try to maximize the objective function; basically the objective function tells the agent how well it is doing.

There are many learning algorithms to choose from to run your learning system, but there are only a few categories:

Supervised learning

Unsupervised learning

Semi-supervised learning

Some learning algorithms include:

Reinforcement learning (Q learning)

Neural Networks

Support vector machines

These methods are not mutually exclusive, ex. one can implement reinforcement learning with a neural network. And these methods/algorithms need to be utilized/combined in some non-trivial way to create an agent. One might even want to combine a learned solution with a handcrafted one; i.e. use learned functions to improve and/or guide your handcrafted solution, for example using a classifier to help choose state transitions.

I included this section so you can have a starting point into researching a Learned solution to your problem.

Title: How should dynamic, interruptible multitasking structure look like?

Body:
I am trying to make an AI that plays a game. Actually, I'm playing around with both StarCraft and MineCraft which are completely different kinds of games. As well, I use different programming languages for both, and one is multi-threaded (java), other event-driven single-threaded (Node.js).

Despite all those differences, I face the same problem: How can I make an AI that can handle tasks in sensible order, but also interrupt the tasks in cases of need and return to them later? How to make a sensible task chain (where one task causes another subtask)?

Examples of above can be:

In minecraft, you're digging a block and you're attacked by a monster

In starcraft you're leading an attack and a critical position in your base is attacked

In minecraft, task of chopping trees is caused by the task building the house - the bot must remember why is he doing what is he doing.

In starcraft, certain buildings are just built in order to unlock types of soldiers

I just was playing around with the idea, but I just kept writing and deleting completely stupid code...

This is what I have now, but it makes no sense. I can see many situations that will not be solved using this model.

```<code>/***
 *  Task pseudo class. After finishing the task, this task notifies the parent task.
 *  Arguments:
 *    action - function callback that will execute. The callback must call the finished() method in the end. The callback will receive
 *             this task's object as a first argument.
 **/
function Task(action, parent, name) {
  this.action = action;
  this.after = after;
  this.name = name||"Void task";
}

Task.prototype.start = function() {
  console.log("Task started...");
  try {
    this.action(this);
  }
  catch(e) {
    console.log("The task action has thrown an error: "+e);
  }
}
Task.prototype.finished = function() {
  console.log("Task over.");
}
//Override this
Task.prototype.pause = function() {};
</code>```

I am afraid I have a lot of reading to do about this. But are there some general known ideas I can start with?


问:
Are case-studies an effective way of getting efficiency-focused team members to be willing to trade some efficiency for quality?

Firstly, this does not suggest that efficiency and quality are in conflict... only that some methods prioritize them differently.

Secondly, this is not a question of whether you agree with Scrum practice or not.

An expressed goal of Scrum is to create high quality increments of a deliverable product. This does not exclude that it might be done efficiently, but efficiency is not the focus.

Most programmers want to both deliver quality products and be efficient about it. Scrum's requirement to add product backlog items to a sprint backlog from the top of the prioritized list only... will often result in resistance from programmers, such as:

"But it will be more efficient if we add these other two items, from further down the priority list, to this sprint".

Perhaps the prioritization of the product backlog items could have been influenced differently by the Scrum Master, while working with the Product Owner. Such could be addressed in the next product backlog refinement session.

Setting aside such issues, are case-studies (of other teams' effective uses of Scrum) an effective way of swaying reluctant team members? (particularly on the issue of efficiency) Or, is there something better than case-studies?

答:
There is something better. It is called 'authority'. Product owner decides what goes first and what goes after.

However, it's expected from developers to communicate to product owner that some things might be more efficient doing one way or another.

That being said, authority is still the product owner, and based on the input from developers, product owner has to decide whether to stick to his plan or alter the plan a bit.

Professional developer is the one who informs the product owner of possible optimizations, but not the one who refuses to do something because "he believes so".


问:
Should my sequential collection start at index 0 or index 1?
I am creating an object model for a device that has multiple channels.  The nouns used between the client and I are Channel and ChannelSet.  ("Set" isn't semantically accurate, because it's ordered and a proper set isn't.  But that's a problem for a different time.)

I'm using C#.  Here is a usage example of ChannelSet:

```<code>// load a 5-channel ChannelSet
ChannelSet channels = ChannelSetFactory.FromFile("some_5_channel_set.json");

Console.Write(channels.Count);
// -> 5

foreach (Channel channel in channels) {
    Console.Write(channel.Average);
    Console.Write(",  ");
}
// -> 0.3,  0.3,  0.9,  0.1,  0.2
</code>```

All is dandy.  However, the clients are not programmers and they absolutely will be confused by zero indexing - the first channel is channel 1 to them.  But, for the sake of consistency with C#, I want to keep the ChannelSet indexed from zero.

This is sure to cause some disconnects between my dev team and the clients when they interact.  But worse, any inconsistency in how this is handled within the codebase is a potential problem.  For example, here's a UI screen where the end user (who thinks in terms of 1 indexing) is editing channel 13:

That Save button is eventually going to result in some code.  If ChannelSet is 1 indexed:

```<code>channels.GetChannel(13).SomeProperty = newValue;  // notice: 13
</code>```

or this if it's zero indexed:

```<code>channels.GetChannel(12).SomeProperty = newValue;  // notice: 12
</code>```

I'm not really sure how to handle this.  I feel like it's good practice to keep an ordered, integer-indexed list of things (the ChannelSet) consistent with all of the other array and list interfaces in the C# universe (by zero indexing ChannelSet).  But then every piece of code between the UI and the backend will need a translation (subtract by 1), and we all know how insidious and common off-by-one errors already are.

So, has a decision like this ever bitten you?  Should I zero index or one index?

答: You are exposing an interface through your ChannelSet class that you expect your users to interact with. I would make it as natural for them to use as possible. If you expect your users will start counting from 1 instead of 0, then expose this class and its usage with that expectation in mind.


答:
Show the UI with index 1, use index 0 in code.

That said, I worked with audio devices like this and used index 1 for the channels and designed the code never to use "Index" or indexers to help avoid frustration. Some programmers still complained, so we changed it. Then other programmers complained.

Just pick one and stick with it. There are bigger problems to solve in the grand scheme of getting software out the door.

Title: Should my sequential collection start at index 0 or index 1?

Body:
I am creating an object model for a device that has multiple channels.  The nouns used between the client and I are Channel and ChannelSet.  ("Set" isn't semantically accurate, because it's ordered and a proper set isn't.  But that's a problem for a different time.)

I'm using C#.  Here is a usage example of ChannelSet:

```<code>// load a 5-channel ChannelSet
ChannelSet channels = ChannelSetFactory.FromFile("some_5_channel_set.json");

Console.Write(channels.Count);
// -> 5

foreach (Channel channel in channels) {
    Console.Write(channel.Average);
    Console.Write(",  ");
}
// -> 0.3,  0.3,  0.9,  0.1,  0.2
</code>```

All is dandy.  However, the clients are not programmers and they absolutely will be confused by zero indexing - the first channel is channel 1 to them.  But, for the sake of consistency with C#, I want to keep the ChannelSet indexed from zero.

This is sure to cause some disconnects between my dev team and the clients when they interact.  But worse, any inconsistency in how this is handled within the codebase is a potential problem.  For example, here's a UI screen where the end user (who thinks in terms of 1 indexing) is editing channel 13:

That Save button is eventually going to result in some code.  If ChannelSet is 1 indexed:

```<code>channels.GetChannel(13).SomeProperty = newValue;  // notice: 13
</code>```

or this if it's zero indexed:

```<code>channels.GetChannel(12).SomeProperty = newValue;  // notice: 12
</code>```

I'm not really sure how to handle this.  I feel like it's good practice to keep an ordered, integer-indexed list of things (the ChannelSet) consistent with all of the other array and list interfaces in the C# universe (by zero indexing ChannelSet).  But then every piece of code between the UI and the backend will need a translation (subtract by 1), and we all know how insidious and common off-by-one errors already are.

So, has a decision like this ever bitten you?  Should I zero index or one index?


问:
Can you do iterative development in c#?
I'm primarily a Python/R developer. In those languages, the way I develop is to sketch out a data and class structure, write the methods and their tests in interactive mode, then refactor them up into class methods and properties and sort out the tests. Some friends are suggesting I learn C#. I don't do much work with complied/staticly typed languages.

Can I develop in an 'interactive mode' the same way in C# - that is, load in some sample data, write methods interactively to ensure they're working right, then push methods up to classes as they're completed? Or is this not a natural way to develop in a compiled language?

答:
Can I develop in an 'interactive mode' the same way in C# - that is, load in some sample data, write methods interactively to ensure they're working right, then push methods up to classes as they're completed?

Not the same way. There isn't really such interactive tools for C# since the problems you're usually solving are large enough to make that unweildy (and the standard compilation model doesn't lend itself to it).

Or is this not a natural way to develop in a compiled language?

Every language has its quirks and idioms. I can't write C# code like I do C++, and I can't write JavaScript the same way as perl. You're going to need to adapt when learning a new language, and that sort of adaptation is the main benefit of learning different languages - you get a broader perspective of different ways of doing things.

All that said, you can and should do iterative development in C#. Smaller chunks of code are easier to reason about, easier to test, easier to debug. The mechanics of doing that though are likely to change due to the quirks of the language and the tools available.

Title: Can you do iterative development in c#?


答:
Use both.

Do not mix the UI with your core code. Internally (as a library) you should code "without knowing" how each element on the array will be called by the final user. Use the "natural" 0-indexed arrays and collections.

The part of the program that joins the data with the UI, the view, should take care to correctly translate data between the User's Mental Model and the 'Library' that does the actual work.

Why is this better?

The code can be cleaner, no hacks to translate indexing. This also helps the programmers by not expecting them to follow and remember to use unnatural conventions.

The users will use the indexing that they expect. You don't want to annoy them.


答:
You can see the collection from two different angles.

(1) It is, in the first place, a regular sequential collection, like an array or a list. Index from 0 is obviously the right solution then, following the convention. You allocate enough entries and map channel number to indices, which is trivial (just subtract 1).

(2) You collection is essentially a mapping between channel identifiers and channel info objects. It just happens that channel identifiers is a sequential range of integers; tomorrow it might be something like [1, 2, 3, 3a, 4, 4.1, 6, 8, 13]. You use this ordered set as mapping keys.

Choose one of the approaches, document it, and stick to it. From flexibility standpoint, I'd go with (2), because the representation of channel number (at least the displayed name) is relatively likely to change in the future.


问:
What is a good metric for guiding a switch from a prototyping language to a production language?
By "prototyping language", I mean one which was chosen by virtue of it's relative ease of quickly accomplishing the sort of design changes common to prototyping in a particular context. (such as data visualisation, for example)

By "production language", I mean one which, with a more solidified design, is likely to produce a more satisfactory, optimised, maintainable product.
One might, for example, prototype a data visualisation in MatLAB or IDL, but switch to C++.

A really simplistic decider might be the subjective judgement that "I'm done prototyping now", but prototyping often "tapers off" rather than ending abruptly, and there is often a realisation that one should probably have swapped to the production language of choice at some point in the past. Maybe a good metric involves capturing some "velocity" information (agile-style) and watching for an inflection point as the velocity changes?

FYI, "Why do dynamic..." and "...scale of the project and the strictness...", while related, are not duplicated by the current question.

答:
Since you mentioned Matlab (and IDL) vs C++ I'll address my answer to that scenario.

Short summary of indicators when switching from a prototyping to production language is necessary:

When programming data structures , algorithms, or distributed processing architectures  not well supported by
the prototyping language, or better supported by the production language,  become needed.

When performance of the programming language becomes inferior to that
of the production language due to data or algorithmic considerations.

When the prototyping language's support for code reuse,

modularization, and creation of libraries is inferior to the

production language and this causes development velocity  and team collaboration to suffer.

I'll talk a bit more about some of these aspects.

One clear indicator that it is time to migrate is often scale. By this, when the problem's complexity, or the complexity of the software development process, becomes large enough in scale that something like Matlab cannot handle it well, it becomes time for a switch to a more production-oriented language.

Problem complexity scale can include when the amount of data to be processed gets to the point where computing with an interpreted language is not sufficient for adequate throughput.

The choice between Matlab and a production language has become less clear cut with recent releases of Matlab. Matlab does now offer some support for multicore, GPU, and distributed computing. It's debatable how adequate that support is, both in development expressiveness and in performance, compared to native implementations.  But it does make the inflection point less clear cut than it was when this support wasn't available.

So a careful evaluation needs to be done of whether the development of code in a production language offers clear cut advantages in performance , or suitability to a parallel or distributed computing architecture, over the prototyping language. A production language, especially one that  can be natively compiled, inarguably can take greater advantage of compiler and processor specific optimizations than even a JIT-compiled interpreted language.

Another aspect of scale you alluded to in your question is in software development process. A production language offers significant advantages over Matlab in  the ability to develop large scale software. Matlab's support of objected oriented programming, string processing, data structures other than matrices, is generally considered  weaker than found in production languages, or even Python.

But it is in the ability to  partition  and reuse code by developing libraries and modules where a prototyping language like Matlab really falls short of production languages. It becomes time to switch when the code base becomes large enough that these deficiencies cause development times and team collaboration to suffer.


问:
How to handle large number of configuration parameters across a program conceptually?
Imagine a software system where you have like 100 parameters, each of which is sensible to change (in my case this is a reasearch system for machine learning). The obvious solution is to store all parameters in a config file, so that the system is easy to handle and see through.

Whis approach is better, what are benefits and disadvantages:

a) load the config file at the entry point of the program and pass down a big collection of config variables through each method in the code

b) load the config file at the entry point of the program and pass down the relevant collection of config variables through each method in the code

c) load the config variables directly where they are needed

d) load the config and make it global

I'm open for any suggestion or examples of a particular implementation. At the moment I'm experimenting with nested config variables, each nested object storing config of different modules in the code.

答: YAML, JSON or XML are often used in frameworks for managing config settings. Depending on the language you are using, another option can be to use a structured entity (ie in a OO language using a class) to hold your config settings.</p>


问:
Try Catch and Flow Control dilemma
I am aware that doing Flow Control on a program using a try-catch block is bad practice, but I can't see how to do it in another way when the error caught needs a redirection of the code's execution.

For example, let's say I have screen where the user clicks a button, and on the buttons click I execute some code. After the code ends execution, I redirect the user to a new screen....

... But the code execution can failure, and in that case, I need to let the user know of the failure and redirect him to the previous screen.

The way I will do it is:

```<code>try
{
     ExcuteCode();
     NavigateToNextScreen();
}
catch(Exception e)
{
     Log.Write(e);
     ShowErrorMessage();
     GoBack();
}
</code>```

Even if I change this to:

```<code>bool hasError = false;

try
{
     ExecuteCode();
}
catch(Exception e)
{
      Log.Write(e);
      ShowErrorMessage();
      hasError = true;
 }

  if(hasError) { GoBack(); }
  else { NavigateToNextScreen();}
</code>```

It's still doing Flow Control inside the try-catch block.

So, is it there a recommend way to handle this properly and avoid this bad practice?

答:
There are a lot of ways to deal with this. Here's just two ideas:

Wrap your try-catch into a method with boolean return type, indicating whether the ExecuteCode() succeeded. The control flow is decided on the usage site then, where you show the error message and go back on failure. It's similar to you second version, but instead of directly modifying a variable that is used for the control flow, you just return the result status and make no assumptions about the caller's control flow.

Switch the Exception throwing to a Validation-like pattern. This is like the boolean, but without try-catch. In case of an error, ExecuteCode returns a Failure object with the problem description. This similarly allows you to modify your flow control depending on the result value, without the error detecting code needing to know about it.

In general, most of the ways I can think of are based on having a better type for ExecuteCode. When ExecuteCode() doesn't return anything, but throws the exception, then this is essentially what requires you to move your logic into try and catch. A better return type allows you to simply delegate the control flow decisions based on that.

Title: Try Catch and Flow Control dilemma


答: Like @theatlasroom mentioned use some technique to structure your config-parameters. When that is in place, and since the parameters are "sensible to change" you might consider building some interface for editing them. Having one, it can guard against unreasonable or harmful values (some times entered by mistake) giving the user guidance.</p>

Title: How to handle large number of configuration parameters across a program conceptually?

Body:
Imagine a software system where you have like 100 parameters, each of which is sensible to change (in my case this is a reasearch system for machine learning). The obvious solution is to store all parameters in a config file, so that the system is easy to handle and see through.

Whis approach is better, what are benefits and disadvantages:

a) load the config file at the entry point of the program and pass down a big collection of config variables through each method in the code

b) load the config file at the entry point of the program and pass down the relevant collection of config variables through each method in the code

c) load the config variables directly where they are needed

d) load the config and make it global

I'm open for any suggestion or examples of a particular implementation. At the moment I'm experimenting with nested config variables, each nested object storing config of different modules in the code.


答:
It seems that you have misunderstood what is meant when people say that you shouldn't use exceptions for flow-control in your program.

Throwing an exception and catching that exception elsewhere in your program changes the control flow of the program. In that way, exception handling is a flow-control construct, just like a while loop or a goto statement.

What sets exception handling apart from other flow-control constructs is that exception handling can let you exit multiple function invocations at once, but that power also makes it an expensive operations because the runtime environment has to figure out which catch block to jump to.

The relative cost of handling exceptions is the source for the adagio not to use them for flow-control, but what is actually meant is that you should not use exceptions to realize a flow through your program that is expected to happen with any regularity.

Exceptions are a perfect tool if you encounter an error and need to bail out of multiple levels of you call stack. They are exactly the wrong tool to jump out of a loop because you found what you were looking for.

Title: Try Catch and Flow Control dilemma

Body:
I am aware that doing Flow Control on a program using a try-catch block is bad practice, but I can't see how to do it in another way when the error caught needs a redirection of the code's execution.

For example, let's say I have screen where the user clicks a button, and on the buttons click I execute some code. After the code ends execution, I redirect the user to a new screen....

... But the code execution can failure, and in that case, I need to let the user know of the failure and redirect him to the previous screen.

The way I will do it is:

```<code>try
{
     ExcuteCode();
     NavigateToNextScreen();
}
catch(Exception e)
{
     Log.Write(e);
     ShowErrorMessage();
     GoBack();
}
</code>```

Even if I change this to:

```<code>bool hasError = false;

try
{
     ExecuteCode();
}
catch(Exception e)
{
      Log.Write(e);
      ShowErrorMessage();
      hasError = true;
 }

  if(hasError) { GoBack(); }
  else { NavigateToNextScreen();}
</code>```

It's still doing Flow Control inside the try-catch block.

So, is it there a recommend way to handle this properly and avoid this bad practice?


问:
Rendering trillions of "atoms" instead of polygons?
I just saw a video about what the publishers call the "next major step after the invention of 3D". According to the person speaking in it, they use a huge amount of atoms grouped into clouds instead of polygons, to reach a level of unlimited detail.

They tried their best to make the video understandable for persons with no knowledge of any rendering techniques, and therefore or for other purposes left out all details of how their engine works.

The level of detail in their video does look quite impressive to me.

How is it possible to render scenes using custom atoms instead of polygons on current hardware? (Speed, memory-wise)

If this is real, why has nobody else even thought about it so far?

I'm, as an OpenGL developer, really baffled by this and would really like to hear what experts have to say. Therefore I also don't want this to look like a cheap advert and will include the link to the video only if requested, in the comments section.

答:
the way it works is much simpler then you might think, instead of pre-loading say a game level it only loads a single screen, one or a few atoms per pixel on your screen, nothing more, the game/engine then predicts what the next frames are and that's the only thing loaded, only the part of the object visible is rendered, not the entire object itself.
PROS: as much definition and resolution your monitor can handle, low memory usage
CONS: read rate from disk is fairly large and could lead to low frame rate. </p>

OwnerDisplayName: Baring


问:
Are SMART goals useful for programmers?
Several organisations I know use SMART goals for their programmers. SMART is an acronym for Specific, Measurable, Achievable, Relevant and Time-Bound. They are fairly common in large corporations.

My own prior experience with SMART goals has not been all that positive. Have other programmers found them an effective way to measure performance? What are some examples of good SMART goals for programmers (if they exist).

答:
In a word

No

First : I've never had my projects remain stable enough that I could establish the SMART goals with any meaning. The time scales between when my roles change on a project and when perf reviews are done are just too far out of sync.

Second: Measuring individual performance is a great way to create a "not my job" mentality and negative competition between individuals and/or the various sub teams in an organization. It's very easy to game the system and make sure you're looking out for yourself and not really helping out the entire team. We should be encouraging people to be team players, but then our organizations do the exact opposite.

Most of these sorts of systems are antithetical to team building. Mary Poppendieck's done a far better job of articulating this than I can ever do in LeanEssays: Team Compensation.

Sue got a call from Janice in human resources. “Sue,” she said, “Great job your team did! And thanks for filling out all of those appraisal input forms. But really, you can’t give everyone a top rating. Your average rating should be ‘meets expectations’. You can only have one or two people who ‘far exceeded expectations’...”

... One of the greatest thought leaders of the 20th century, W Edwards Deming, wrote that un-measurable damage is created by ranking people, merit systems, and incentive pay. Deming believed that every business is a system and the performance of individuals is largely the result of the way the system operates. In his view, the system causes 80% of the problems in a business, and the system is management’s responsibility. He wrote that using exhortations and incentives to get individuals to solve management problems simply doesn’t work. Deming opposed ranking because it destroys pride in workmanship, and merit raises because they address the symptoms, rather than the causes, of problems.

...let’s take a deeper look into employee evaluation and reward systems, and explore what causes them to become dysfunctional...

Title: Are SMART goals useful for programmers?


答:
0-based indexing was popular, and defended by important people, because the declaration shows the size of the object.

With modern computers, with the computers your users will be using, is the size of the object important at all?

If your langauge (C#) doesn't support a clean way of declaring the first and last element of an array, you can just declare a bigger array, and use declared constants (or dynamic variable) to identify to the logical start and end of the active area of the array.

For UI objects, you can almost certainly afford to use a dictionary object for your mapping, (if you've got 10 million objects, you've got a UI problem), and if the best dictionary object turns out to be a list with wasted space at either end, you haven't lost anything important.


答:
Everybody and their dog uses zero based indexes. Using one-based indexes inside your application will cause you maintenance problems forever.

Now what you display in a user interface, that is entirely up to you and your client. Just display i+1 as the channel number, together with channel #i, if that makes your client happy.

If you expose a class, then you expose it to programmers. People you are confused by a zero-based index are not programmers, so there is a disconnect here.

You seem to worry about the conversion between UI and code. If that worries you, create a class carrying the user interface representation of a channel number. One call turning the number 12 into the UI representation "Channel 13", and one call turning "Channel 13" into the number 12. You should do that anyway, in case the customer changes their mind, so there are just two lines of code to change. And it works if the customer asks for roman numerals, or letters A to Z.


问:
How long do I have to provide the source code for a LGPL-library?
In case I would dynamically link to a LGPL-licensed library (in this case Qt) in a commercial application: Which way do I have to provide the library's source code?

Is a link to the project homepage sufficient? Or would I need to host the source code on our servers? For which period of time after distribution of the software would this website need to be kept up? (or would "on request" be also compliant with the LGPL?)

Is it still necessary to offer the source code in a physical way (e.g. on CD via snail mail) for 3 years (any difference between LGPL 2.1 and LGPL 3 here?)?

I've found this in the GNU FAQ:

Can I put the binaries on my Internet server and put the source on a
different Internet site?

Yes. Section 6(d) allows this. However, you must provide clear instructions people can follow to obtain the source, and you must take
care to make sure that the source remains available for as long as you
distribute the object code.

I've highlighted the relevant part as bold text. However, I cannot believe, that this is the complete truth. If I distribute an application only once, then I could put the source code online and take it down a day later. So this still doesn't answer my question...

There is another question with a related topic here, but it has a different attempt than mine. It only asks for alternatives to shipping the source code directly with the binaries, while my question aims to clarify which circumstances and conditions I would have to consider / respect when sharing the LGPL library source code.

答:
In your particular case (you are mentioning Qt) I believe that in practice giving a link to Qt - including to the download page of the particular version of Qt your are basing your product on - is probably enough.

However, be sure that the link is valid (you have no control on how Qt people are managing their website). This means that you should at least watch it every week (or setup a script doing that).

However, as a courtesy, you'll better add a local copy on your web site of the tar source archive of the relevant version of Qt, and keep that copy as long as you offer for sale your product using Qt or some maintenance or services on it.

IMHO (and I am not a lawyer) it is not much a matter of legal obligations, but much more a matter of being nice with your customers and the Qt community at large. And a local copy of Qt source code on your company's web site don't cost that much to it!

At last, your company might buy a different license of Qt.


问:
Is anything in programming truly evil?
So, there are a bunch of questions appearing asking is X evil, is Y evil.

My view is that there are no language constructs, algorithms or whatever which are evil, just ones which are badly used.  Hell, if you look hard enough there are even valid uses of goto.

So does absolute evil, that is something which is utterly incompatible with best practice in all instances, exist in programming?  And if so what is it?  Or is it just bad programmers not knowing when something is appropriate?

Edit: To be clear, I'm not talking about things programmers do (such as not checking return codes or not using version control - they're choices made by bad programmers), I mean tools, languages, statements, whatever which are just bad...

答:
What does the FAQ mean by "such and such is evil"?

It means such and such is something you should avoid most of the time, but not something you should avoid all the time. For example, you will end up using these "evil" things whenever they are "the least evil of the evil alternatives." It's a joke, okay? Don't take it too seriously.

Title: Is anything in programming truly evil?


问:
How do I implement role permissions in the service layer?
In my current project I have a Report class, and I am going to implement a service layer for it. Every method will be allowed only for some roles. Like this:

```<code>public class ReportService : IReportService
{
    public void CreateReport(Report report, User user)
    {
        if(user.HasRole("Admin"))
        {
            throw new SecurityException("You do not have permissions to do it");
        }

        ...
    }

    public void ModifyReport(Report report, User user)
    {
        if(user.HasRole("Admin"))
        {
            throw new SecurityException("You do not have permissions to do it");
        }

        ...
    }

    public bool ValidateReport(Report report, User user)
    {
        if (!user.HasRole("Manager"))
        {
            throw new SecurityException("You do not have permissions to do it");
        }
    }

    public void DeleteReport(Report report, User user)
    {
        if (user.HasRole("Employee") || user.HasRole("Manager"))
        {
            throw new SecurityException("You do not have permissions to do it");
        }
        ...
    }
}
</code>```

Is this straightforward approach OK? Do you have some better ideas?

I have just an idea to implement it as the decorator pattern, so the code will be like this:

```<code>public class ReportService : IReportService
{
    public void CreateReport(Report report, User user)
    {
      // Actual implementation
    }

    public void ModifyReport(Report report, User user)
    {
        // Actual implementation
    }

    public bool ValidateReport(Report report, User user)
    {
        // Actual implementation
    }

    public void DeleteReport(Report report, User user)
    {
        // Actual implementation
    }
}

public class PermissionsReportService : IReportService
{
    private IReportSerivce _service;
    public PermissionsReportService(IReportService service)
    {
        _service = service;
    }

    public void CreateReport(Report report, User user)
    {
        if (user.HasRole("Admin"))
        {
            throw new SecurityException("You do not have permissions to do it");
        }

        _service.CreateReport(report, user);
    }

    public void ModifyReport(Report report, User user)
    {
        if (user.HasRole("Admin"))
        {
            throw new SecurityException("You do not have permissions to do it");
        }
        _service.ModifyReport(report, user);
    }

    public bool ValidateReport(Report report, User user)
    {
        if (!user.HasRole("Manager"))
        {
            throw new SecurityException("You do not have permissions to do it");
        }

        _service.ValidateReport(report, user);
    }

    public void DeleteReport(Report report, User user)
    {
        if (user.HasRole("Employee") || user.HasRole("Manager"))
        {
            throw new SecurityException("You do not have permissions to do it");
        }

        _service.DeleteReport(report, user);
    }
}
</code>```

It seems better because because role permissions checking and other logic now is splitted, doesn't it?

I also have another concern. Most likely this service will be used in ASP.NET MVC project and Microsoft proposes to use Authorize attributes for different role permissions, like

```<code> public class ReportController : Controller
{
    [HttpGet]
    [Authorize(Roles="Admin")]
    public void DeleteReport(int reportId)
    {

    }
}
</code>```

If I use this approach I will duplicate role permissions logic (inside the service layer and inside the controller). What should I do? Do I need to refuse Microsoft's approach? Or do I need to remove my role permissions checking in the service layer (but in this case what do I do if my service will be used in (for example) console application)? Or is it OK to have this code duplication and have permissions checks in the service and web layers?

答:
I would say to ditch both in favor for a class which handles all permissions.  Your classes would then pass a string identifier of the permission you want to check and your class would perform a lookup to see what roles are required to perform that action.

For instance, rather than have a method like:

```<code>public void CreateReport(Report report, User user)
{
    if(user.HasRole("Admin"))
    {
        throw new SecurityException("You have not permissions to do it");
    }

    ...
}
</code>```

I would expect something more like:

```<code>public void CreateReport(Report report, UserAuth auth)
{
    auth.Validate("report.create");  // throws SecurityException if invalid

    ...
}
</code>```

UserAuth class would take a User instance, and throw a SecurityException if user doesn't have the roles required to perform that action.  Ideally the link between action and what roles are required would be dynamically loaded from a database, though you can start off with a simple Dictionary.

I would still use the facade to separate the actual permission checking and the actual action, because in my humble opinion, that is a separation of concerns and should be kept in a separate class just the same.

Your controller would do the same.  What's important is that the logic behind the permissions is in its own class.  You're still having to call it, but you don't have to care about anything other than what the permission you're trying to lookup is called.  Checking if a user has employee or administrator role for every method call which merits such a check, for instance, is sort of an antipattern.

I hope that helps!

Body:
I would say to ditch both in favor for a class which handles all permissions.  Your classes would then pass a string identifier of the permission you want to check and your class would perform a lookup to see what roles are required to perform that action.

For instance, rather than have a method like:

public void CreateReport(Report report, User user)
{
    if(user.HasRole("Admin"))
    {
        throw new SecurityException("You have not permissions to do it");
    }

    ...
}

I would expect something more like:

public void CreateReport(Report report, UserAuth auth)
{
    auth.Validate("report.create");  // throws SecurityException if invalid

    ...
}

UserAuth class would take a User instance, and throw a SecurityException if user doesn't have the roles required to perform that action.  Ideally the link between action and what roles are required would be dynamically loaded from a database, though you can start off with a simple Dictionary.

I would still use the facade to separate the actual permission checking and the actual action, because in my humble opinion, that is a separation of concerns and should be kept in a separate class just the same.

Your controller would do the same.  What's important is that the logic behind the permissions is in its own class.  You're still having to call it, but you don't have to care about anything other than what the permission you're trying to lookup is called.  Checking if a user has employee or administrator role for every method call which merits such a check, for instance, is sort of an antipattern.

I hope that helps!


问:
Am I overdoing stuff when I sever interfaces from concrete implementations?
I've separated interfaces from their implementations by different packages, it's just add clarity, the separation is good looking and it is easier to navigate the project structure. I like it. The only point which confuses me - I've started thinking I might overdo stuff. So the question is - do you think it's a good practice to split code like that?

答:
I think it is fine, and I do it.

However I would flip it from how you are doing it, the *impl on every class would drive me insane. Instead I would name the interfaces differently (IThing as I am .Net type) and have them in an Interfaces folder. Then the concrete class (Thing) is 'normal' and would not need to live in a concrete class folder, just wherever made sense.

In some cases I then publish the interfaces folder as a Contracts package for other things that want to work with my main types.


问:
AABB collision algorithm with a condition
So I'm doing a 3D implementation of collision detection.

Considering

Boxes are oriented on the axis.

They are rotatable but has to be orientated on the axis.

Box A and Box B cannot go through each other. However; one of there sides can have similar (x,y,z) points.

Here is a visual aid of what SHOULD happen.

COLLIDING(Examples in RED BOX)  -------------------   NOT COLLIDING(Examples in GREEN BOX)

However, example 1 and Example 3 in the GREEN box are considered as collision when I don't want them to be. I want them to be considered not colliding.

Here is my code so far.

```<code>if((xMax1>=xMin2)||(xMin1<=xMin2)){
            if((yMax1>=yMin2)||(yMin1<=yMin2)){
                        if((zMax1>=zMin2)||(zMin1<=zMin2)){
                            isSeperate = false;
                        }
                    }
                }
</code>```

What is a conditional that I should add to  the code for my issue to be solved.

答:
There are so many different cases to consider when developing collision detection that it can get confusing. I'd recommend implementing the Separating Axis Theorem(SAT) to detect collisions between convex objects. It takes into account position and rotation of objects and lets you handle the collisions. You can take a look at this video I made a few months ago of my implementation of it in C# for 2D shapes: https://youtu.be/VOBSijUuBgc

This will also work for 3D shapes it just needs to take into account the z-axis.


答:
It feels like you're conflating the Identifier for the Channel with its position within a ChannelSet. The following is my visualisation of how your code/comments would look at the moment :

```<code>public sealed class ChannelSet
{
    private Channel[] channels;
    /// <summary>Retrieves the specified channel</summary>
    /// <param name="channelId">The id of the channel to return</param>
    Channel GetChannel(int channelId)
    {
        return channels[channelId-1];
    }
}
</code>```

It does feel like you've decided that because Channels within a ChannelSet are identified by numbers that have an upper and lower bound they must be indexes and therefore as it's C#, 0 based. If the natural way to refer to each of the channels is by a number between 1 and X, refer to them by a number between 1 and X. Don't try and force them into being indexes.

If you really want to provide a way to access them by 0 based index (what benefit does this give your end user, or developers that consume the code?) then implement an Indexer:

```<code>public sealed class ChannelSet
{
    private Channel[] channels;
    /// <summary>Retrieves the specified channel</summary>
    /// <param name="channelId">The id of the channel to return</param>
    public Channel GetChannel(int channelId)
    {
        return channels[channelId-1];
    }

    /// <summary>Return the channel at the specified index</summary>
    public Channel this[int index]
    {
        return channels[index];
    }
}
</code>```

Body:
It feels like you're conflating the Identifier for the Channel with its position within a ChannelSet. The following is my visualisation of how your code/comments would look at the moment :

public sealed class ChannelSet
{
    private Channel[] channels;
    /// <summary>Retrieves the specified channel</summary>
    /// <param name="channelId">The id of the channel to return</param>
    Channel GetChannel(int channelId)
    {
        return channels[channelId-1];
    }
}

It does feel like you've decided that because Channels within a ChannelSet are identified by numbers that have an upper and lower bound they must be indexes and therefore as it's C#, 0 based. If the natural way to refer to each of the channels is by a number between 1 and X, refer to them by a number between 1 and X. Don't try and force them into being indexes.

If you really want to provide a way to access them by 0 based index (what benefit does this give your end user, or developers that consume the code?) then implement an Indexer:

public sealed class ChannelSet
{
    private Channel[] channels;
    /// <summary>Retrieves the specified channel</summary>
    /// <param name="channelId">The id of the channel to return</param>
    public Channel GetChannel(int channelId)
    {
        return channels[channelId-1];
    }

    /// <summary>Return the channel at the specified index</summary>
    public Channel this[int index]
    {
        return channels[index];
    }
}


答: It looks like you don't want >= and <=, because then touching boxes are considered colliding. Use > and < instead.

Title: AABB collision algorithm with a condition

Body:
So I'm doing a 3D implementation of collision detection.

Considering

Boxes are oriented on the axis.

They are rotatable but has to be orientated on the axis.

Box A and Box B cannot go through each other. However; one of there sides can have similar (x,y,z) points.

Here is a visual aid of what SHOULD happen.

COLLIDING(Examples in RED BOX)  -------------------   NOT COLLIDING(Examples in GREEN BOX)

However, example 1 and Example 3 in the GREEN box are considered as collision when I don't want them to be. I want them to be considered not colliding.

Here is my code so far.

```<code>if((xMax1>=xMin2)||(xMin1<=xMin2)){
            if((yMax1>=yMin2)||(yMin1<=yMin2)){
                        if((zMax1>=zMin2)||(zMin1<=zMin2)){
                            isSeperate = false;
                        }
                    }
                }
</code>```

What is a conditional that I should add to  the code for my issue to be solved.


答:
We've used SMART goals in the large corporation where I work.  They're meaningless for the most part.

Goals come down from upper management and are lofty and abstract.  Relating them to concrete projects and development is usually a joke.  Most of the projects that come into the group come from the business and are to meet a specific business need.  So you code the project, put it in production and do an awesome job as usual.  How does that relate to a goal that someone in upper management came up with?

We do much better as a group when we come up with our own goals.  Sometimes they include training on a specific topic or implementing a new process change, something that can actually be related to what we do.  They're still not really related to the day to day operation of coding by they're at least things that help move the group foward in the corporate environment.

EDIT

As Mnementh has so correctly pointed out, my answer is based on SMART goals not being, well, SMART.  I would add to my answer that if you are a manager of programmers and want to implement SMART goals, be sure that they are SMART.  Use my mangagers' example as a way NOT to implement SMART goals.  If you don't manage programmers and someone tells you that you're now going to start using SMART goals and they end up like ours did, then understand that you've got people in upper management who likes buzz words and being able to check them off a list of things they've implemented.

Title: Are SMART goals useful for programmers?

Body:
Several organisations I know use SMART goals for their programmers. SMART is an acronym for Specific, Measurable, Achievable, Relevant and Time-Bound. They are fairly common in large corporations.

My own prior experience with SMART goals has not been all that positive. Have other programmers found them an effective way to measure performance? What are some examples of good SMART goals for programmers (if they exist).


问:
Partial Update of Database Table
I have a database table with numerous fields including "category". The source of this table is an xml file which the system receiving occasionally. Each xml file contains data for one category. The table needs to be updated with the new category data from the xml file. The xml file includes all data for that category, not just the changes.

I see two possible ways of handling this:

First deleting all rows from the table where category = categoryID, and then doing inserts based on all the xml data. Obviously the deletion and insertion operations would be contained within a transaction.

For each record in the xml, first do a select to test if that record exists. If it does exist, update the data with that from the xml. If it doesn't exists, insert it.

Obviously, the second approach avoids deleting the data first but involves many more db queries although this could be mitigated by doing an initial select to a hash table, and just querying the hash. The big downside to the second approach is how to handle deletions, i.e. records that no longer appear in the xml and should be removed from the table.

What is the best practice for handling this kind of operation?

Thanks.

答:
Since you have the primary key of each record, I highly recommend using the approach of examining each record individually.

Primary key lookups are extremely fast in any professional-grade database.

Updating a record based on primary key has a very granular lock level and is fast.

By inserting or updating rather than delete/insert, you maintain the existence of data: at no time is it possible to query the category table and come up empty (unless you are querying a category that you have not gotten around to inserting yet).

In short, do not worry about performing extra queries here because the queries will execute just about as fast as possible. I also assume categories are relatively fixed in quantity, as compared to say a logging event or banking transaction which is always increasing the amount of data.

Title: Partial Update of Database Table


问:
How can I create a RESTful-style website if HTML forms only allow to use GET and POST?
Let's say that I want to create a website where users will be able to create, edit and delete some kind of resources, for example posts.

I have created a RESTful API, so user can create a post by sending a PUT request to http://www.example.com/posts/my-new-awesome-post, delete it by sending DELETE request, etc.

But most users don't know anything about HTTP requests. They want to click a "New post" button and have the new post created.  But HTML only allows me to use GET and POST.

How can I create a "New post" button that will send a PUT request? Or is "RESTful creation/deletion" implemented in a totally different way?

Let's say I'm using Spring + Thymeleaf.

答:
The 'New Post' button would go to a form for the user to input the information for a new post. When the user submits that form the browser rightly sends that data via HTTP POST (use POST for create).

An edit submission would use PUT or PATCH depending on whether it is a replace (delete the missing properties) or update (only change the submitted properties), respectively.

We usually make an XMLHTTPRequest (XHR)  using JavaScript for events other than GET or POST.

```<code>jQuery.ajax('/products/42', {method: 'PUT', data: product_data});
</code>```

jQuery Docs: http://api.jquery.com/jquery.ajax/

Additionally, Rails will use a '_method' param in POSTs to force a different action on the server ( like PUT or PATCH).

Body:
The 'New Post' button would go to a form for the user to input the information for a new post. When the user submits that form the browser rightly sends that data via HTTP POST (use POST for create).

An edit submission would use PUT or PATCH depending on whether it is a replace (delete the missing properties) or update (only change the submitted properties), respectively.

We usually make an XMLHTTPRequest (XHR)  using JavaScript for events other than GET or POST.

jQuery.ajax('/products/42', {method: 'PUT', data: product_data});

jQuery Docs: http://api.jquery.com/jquery.ajax/

Additionally, Rails will use a '_method' param in POSTs to force a different action on the server ( like PUT or PATCH).


问:
Importing plain javascript libraries in an AngularJs application
I am working on an AngularJs project which is getting bigger very fast.

Currently I need to store some user data, so I was using $localStorage for Angular.

But I had a problem, as the application is saving a big amount of data, it is hanging the browser some seconds which is very annoying.

Searching for asynchronous uses of localStorage I've found a bunch of people saying that it not possible to use it. But I managed to found some plain javascript implementations on GitHub:

localForage - by Mozilla

Async Local Storage - by a guy who works at Google

There is an Angular implementation which is based on what Mozilla provides, but the build is failing and I want to use something more stable due to the importance of the project.

Then I came to this doubt, how should I use plain/vanilla javascript inside an Angular app?

I know that it is discouraged to use jQuery in the way people normally are "tempted" to use. How should I organize my pure javascript libraries in my application in a way that I can still see it very organized and fitting in the "Angular Way"?

EDIT: I know I have given you a fairly specific example about my data storage problem and some people might want help me with this, I really appreciate that (seriously). But unfortunately this is not the kind of answer I expect, since it does not have any relation with my real question. Please consider that even if I solve my data problem on my own, I will still want to know what are the best practices of including plain javascript code on my Angular Apps (that's the reason I've posted it here and not in StackOverflow). I could not find any good articles or questions here about it. I want the power of thinking of all great developers out there to help me, but most of all, help the community. I really think that good answers to this question could help a great amount of people, and that is what StackExchange is all about.

答:
You might like Require.js. I don't believe there is a "standard Angular way" of importing code because they figure you'll use any of the other techniques:

Concatenate and minify using Bower

Import using regular script tags

Use a loading library like Require.js

Just define your own stuff as services in Angular

You also might want to read http://oblongmana.com/articles/angular-third-party-injection-pattern/ as it describes a pattern for Angularizing third party libraries, which are just plain old JavaScript.