答:
There are a few points:

Your implementation must do what the documented contract states, and should do nothing more.

Simplicity is important, for both contract and implementation, though more for the former.

Trying to correct for erroneous input adds complexity, counter-intuitively not only to contract and implementation but also to use.

Errors should only be caught early if that improves debugability and doesn't compromise efficiency too much.

Remember that there are debug-assertions for diagnosing logic errors in debug-mode, which mostly alleviates any performance-concerns.

Efficiency, as far as available time and money allow without compromising simplicity too much, is always a goal.

If you implement a user-interface, friendly error-messages (including suggestions and other help) are part of good design.

But remember that APIs are for programmers, not end-users.

A real-life experiment in being fuzzy and permissive with input is HTML.

Which resulted in everyone doing it slightly differently, and the spec, now it is documented, being a mammoth tome full of special cases.

See Postel's law ("Be conservative in what you do, be liberal in what you accept from others.") and a critic touching on that (Or a far better one MichaelT made me aware of).

Title: Should a method be forgiving with the arguments that are passed in?

Body:
Suppose we have a method foo(String bar) that only operates on strings that meet certain criteria; for example, it must be lowercase, must not be empty or have only whitespace, and must match the pattern [a-z0-9-_./@]+. The documentation for the method states these criteria.

Should the method reject any and all deviations from this criteria, or should the method be more forgiving about some criteria? For example, if the initial method is

```<code>public void foo(String bar) {
    if (bar == null) {
        throw new IllegalArgumentException("bar must not be null");
    }
    if (!bar.matches(BAR_PATTERN_STRING)) {
        throw new IllegalArgumentException("bar must match pattern: " + BAR_PATTERN_STRING);
    }
    this.bar = bar;
}
</code>```

And the second forgiving method is

```<code>public void foo(String bar) {
    if (bar == null) {
        throw new IllegalArgumentException("bar must not be null");
    }
    if (!bar.matches(BAR_PATTERN_STRING)) {
        bar = bar.toLowerCase().trim().replaceAll(" ", "_");
        if (!bar.matches(BAR_PATTERN_STRING) {
            throw new IllegalArgumentException("bar must match pattern: " + BAR_PATTERN_STRING);
        }
    }
    this.bar = bar;
}
</code>```

Should the documentation be changed to state that it will be transformed and set to the transformed value if possible, or should the method be kept as simple as possible and reject any and all deviations? In this case, bar could be set by the user of an application.

The primary use-case for this would be users accessing objects from a repository by a specific string identifier. Each object in the repository should have a unique string to identify it. These repositories could store the objects in various ways (sql server, json, xml, binary, etc) and so I tried to identify the lowest common denominator that would match most naming conventions.


问:
Should a method be forgiving with the arguments that are passed in?
Suppose we have a method foo(String bar) that only operates on strings that meet certain criteria; for example, it must be lowercase, must not be empty or have only whitespace, and must match the pattern [a-z0-9-_./@]+. The documentation for the method states these criteria.

Should the method reject any and all deviations from this criteria, or should the method be more forgiving about some criteria? For example, if the initial method is

```<code>public void foo(String bar) {
    if (bar == null) {
        throw new IllegalArgumentException("bar must not be null");
    }
    if (!bar.matches(BAR_PATTERN_STRING)) {
        throw new IllegalArgumentException("bar must match pattern: " + BAR_PATTERN_STRING);
    }
    this.bar = bar;
}
</code>```

And the second forgiving method is

```<code>public void foo(String bar) {
    if (bar == null) {
        throw new IllegalArgumentException("bar must not be null");
    }
    if (!bar.matches(BAR_PATTERN_STRING)) {
        bar = bar.toLowerCase().trim().replaceAll(" ", "_");
        if (!bar.matches(BAR_PATTERN_STRING) {
            throw new IllegalArgumentException("bar must match pattern: " + BAR_PATTERN_STRING);
        }
    }
    this.bar = bar;
}
</code>```

Should the documentation be changed to state that it will be transformed and set to the transformed value if possible, or should the method be kept as simple as possible and reject any and all deviations? In this case, bar could be set by the user of an application.

The primary use-case for this would be users accessing objects from a repository by a specific string identifier. Each object in the repository should have a unique string to identify it. These repositories could store the objects in various ways (sql server, json, xml, binary, etc) and so I tried to identify the lowest common denominator that would match most naming conventions.

答:
As others have said, making the string matching "forgiving" means introducing additional complexity. That means more work in implementing the matching. You now have many more test cases, for example. You have to do additional work to ensure there are no semantically-equal names in the namespace. More complexity also means there is more to go wrong in the future. A simpler mechanism, such as a bicycle, requires less maintenance than a more complex one, such as a car.

So is the lenient string matching worth all that extra cost? It does depend on the use case, as others have noted. If the strings are some kind of external input you have no control over, and there is a definite advantage to lenient matching, it might be worth it. Perhaps the input is coming from end users who may not be very conscientious about space characters and capitalization, and you have a strong incentive to make your product easier to use.

On the other hand, if the input were coming from, say, properties files assembled by technical folks, who should understand that "Fred Mertz" != "FredMertz", I'd be more inclined to make the matching stricter and save the development cost.

I do think in any case there is value in trimming and disregarding leading and trailing spaces, though -- I've seen too many hours wasted on  debugging those kinds of issues.

ContentLicense: CC BY-SA 3.0


问:
Why use Android Fragments?
I have read the documentation and some other questions' threads about this topic and I don't really feel convinced; I don't see clearly the limits of use of this technique.

Fragments are now seen as a Best Practice; every Activity should be basically a support for one or more Fragments and not call a layout directly.

Fragments are created in order to:

allow the Activity to use many fragments, to change between them, to reuse these units... ==> the Fragment is totally dependent to the Context of an activity , so if I need something generic that I can reuse and handle in many Activities, I can create my own custom layouts or Views ... I will not care about this additional Complexity Developing Layer that fragments would add.

a better handling to different resolution ==> OK for tablets/phones in case of long process that we can show two (or more) fragments in the same Activity in Tablets, and one by one in phones. But why would I use fragments always ?

handling callbacks to navigate between Fragments (i.e: if the user is Logged-in I show a fragment else I show another fragment). ===> Just try to see how many bugs facebook SDK Log-in have because of this, to understand that it is really (?) ...

considering that an Android Application is based on Activities... Adding another life cycles in the Activity would be better to design an Application... I mean the modules, the scenarios, the data management and the connectivity would be better designed, in that way. ===> This is an answer of someone who's used to see the Android SDK and Android Framework with a Fragments vision. I don't think it's wrong, but I am not sure it will give good results... And it is really abstract...

====> Why would I complicate my life, coding more, in using them always? else, why is it a best practice if it's just a tool for some cases? what are these cases?

答:
I asked this question more than one year ago.

I am using fragments everyday and I would recommend it.

First of all, I want to say that using fragments is just an options and will be a reflex to consider it once you start using them.

Advantages:

1/ it helps to modularize the code where you can have a full flow in one Activity, in separated fragments. Example:
 + list/grid & detail,
 + login & registration & forget password,
 + etc.
This is awesome to get a reusable code, that you can always copy & past in different projects.

2/ you have a new lifecycle, full of of hassles that's true, but with advantages as well. Example: the retained instance fragment is awesome because it solves the problem of the orientation.

3/ you can manage the flow of your fragments by events and listeners from the Activity.

4/ a stack of your fragments in your Activity.

5/ use the same Action bar in many screens.

And many others...

I am still using the Activity as only container sometimes, especially for the Camera case. Some Android APIs and some third party libraries are not easy to implement in fragments.

Well, it's like any tool, you have to consider it, and judge by yourself if it's better to use it in a case or another.

I hope this can help!!!

Title: Why use Android Fragments?


问:
Multiple methods in single test case
I am new to Junit. I have a class with four methods. I am creating a test class with test cases. Can I have a test case that uses more than one methods of testing class or there should one test case per one method. What is good practice ?</p>

答:
Can I have a test case that uses more than one method of the tested class

Obviously yes, how will you otherwise test methods which need a specific initialization before? For example

```<code>  fooCalculator = new FooCalculator(someParameters);
  fooCalculator.SetOption1(valueForOption1);
  fooCalculator.SetOption2(valueForOption2);
  result = fooCalculator.Calc();
  Assert.AreEqual(expectedResultForTheseOptions,result);
</code>```

If, however, your question is "Can I have a test case that tests more than one method", then the answer is "you should avoid that", because that will typically result in too large tests. See this former question for a detailed explanation.

Title: Multiple methods in single test case

Body:
Can I have a test case that uses more than one method of the tested class

Obviously yes, how will you otherwise test methods which need a specific initialization before? For example

  fooCalculator = new FooCalculator(someParameters);
  fooCalculator.SetOption1(valueForOption1);
  fooCalculator.SetOption2(valueForOption2);
  result = fooCalculator.Calc();
  Assert.AreEqual(expectedResultForTheseOptions,result);

If, however, your question is "Can I have a test case that tests more than one method", then the answer is "you should avoid that", because that will typically result in too large tests. See this former question for a detailed explanation.


问:
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).

答:
There's plenty of research to show that programmers will do an excellent job at whatever criteria are presented to them, at the cost of other possible goals.

This means that they will do well at achieving specific and measurable goals, and less well at anything not specifically listed.  That means you have to be extremely careful at setting goals.

You don't want to set lines of code as a goal.  Trust me.  Setting bugs fixed leads to writing buggy code to begin with.  Asking for bug fixes in existing code will result in very liberal definitions of "bug" (and maybe "fix").  (Also, the "achievable" part depends on how buggy the code was.)  Asking for feature completeness in a certain time, well....

What you want your programmers to do is to write useful stuff in a reasonable period of time with good code quality, and enhance and modify it while maintaining code quality.  I've never seen specific and measurable goals that would be good criteria myself.

Title: Are SMART goals useful for programmers?

ContentLicense: CC BY-SA 2.5


答:
You mention some of the context from which this question comes.

Given that, I would have the method do just one thing, it asserts the requirements on the string, let it execute based on that - I wouldn't try to transform it here. Keep it simple and keep it clear; document it, and endeavour to keep the documentation and code in sync with each other.

If you wish to transform the data that comes from the user database in some more forgiving manner, put that functionality into a separate transformation method and document the functionality tied it.

At some point the function's requirements need to be metered out, clearly documented and the execution must continue. The "forgiveness", at his point, is a little mute, it's a design decision and I would argue for the function not mutating its argument. Having the function mutate the input hides some of the validation that would be required of the client. Having a function that does the mutation helps the client get it right.

The big emphasis here is clarity and to document what the code does.


答:
A method's behavior should be clear cut, intuitive, predictable, and simple. In general, we should be very hesitant to do extra processing on a caller's input. Such guesses about what the caller intended invariably have a lot of edge cases that produce undesired behavior. Consider an operation as simple as file path joining. Many (or perhaps even most) file path joining functions will silently discard any preceding paths if one of the paths being joined appears to be rooted! For example, /abc/xyz joined with /evil will result in just /evil. This is almost never what I intend when I join file paths, but because there's no interface that doesn't behave this way, I'm forced to either have bugs or write extra code covering these cases.

That said, there are rare occasions when it makes sense for a method to be "forgiving," but it should always be within the power of the caller to decide when and whether these processing steps apply to their situation. So when you've identified a common preprocessing step that you want to apply to arguments in a variety of situations, you should expose interfaces for:

The raw functionality, without any preprocessing.

The preprocessing step by itself.

The combination of the raw functionality and the preprocessing.

The last is optional; you should only provide it if a large number of calls will use it.

Exposing the raw functionality gives the caller the ability to use it without the preprocessing step when they need to. Exposing the preprocessor step by itself allows the caller to use it for situations where they're not even calling the function or when they want to preprocess some input before calling the function (like when they want to pass it into another function first). Providing the combination allows callers to invoke both without any hassle, which is useful primarily if most callers will use it this way.


问:
VO to Entity Conversion
In our application we have multiple layers.

UI -> This can be JSP/ JSON result of the API

Controllers -> as in MVC

Services  -> perform single business operation per service

DAOs  -> Data Access Layer (including connection/and DB layer)

And two types of ValueObjects

FormValueObjects --> More close to View

Entities  --> replica of a row in DB

Since, Entities are DB related, they should not be exposed to other layers.

Since FormValueObjects are not related to DB, they should not be exposed to DAO layer.

I need to populate FormValueObjects from Entities and vice versa. In which layer should this be done? DAO layer/ Services layer or should I create an Adapter layer in between the two?

Please suggest me a good design.

答:
That's the responsibility of your controller as that is the class that is responsible for receiving data from the view and translating it onto methods for the model, as well as receiving data from the model and handing it up to the view.

This does not mean the controller has to do this directly however. Your model can use ViewBuilders for example to build view-objects from Entities and these builders would probably belong to the view-layer. For changes to the model, the controller could just as well package data from the view into a command and hand that off to a command-handler type object. This might be part of the domain layer.

Title: VO to Entity Conversion


问:
Is there any reason to use C++ instead of C, Perl, Python, etc.?
As a Linux (server side) developer, I don't know where and why should I use C++.

When I'm going for performance, the first and last choice is C.

When "performance" isn't the main issue, programming languages like Perl and Python would be good choices.

Almost all open source applications I know in this area have been written in C, Perl, Python, Bash script, AWK or even PHP, but no one uses C++.

I'm not discussing other areas like GUI or web applications, I'm just talking about Linux, CLI and daemons.

Is there any satisfactory reason to use C++?

答:
Is there any satisfiable reason to use C++?

Templates and the STL.  You trade a little build time (and some potentially incomprehensible error messages) for a lot of useful abstraction and labor-saving tools, with no appreciable run-time performance hit (although the binary footprint may be a little larger).

It takes a while to wrap your head around (took me a couple of years before it clicked), but once you do it can make life a lot simpler.

Text processing in C++ is orders of magnitude less painful than it is in C.


问:
Should I put stack trace in error files and halt my app with user friendly error
In my earlier project I wrote an app that is used in-house. My usual practice is to capture errors/exceptions from different classes and threads and put them in different log files corresponding to different classes and threads grouped logically. And few simplified errors I targeted to the text area in the UI. So user is presented with only simplified user friendly error explanation. And when the app stuck/hang, I simply used to fetch the detailed logs and find out what was going wring from the stack trace in there. This allowed me to quickly and precisely diagnose issue many times.

Now I am in new project and people here dont print stack trace at all in any file. They simply write whats going wrong in some files, and check those file in hang ups and guess what might be wrong. They might be able to do this, since they are handling this piece of software for long and their guessing works many times. But thats not possible for me, since I am new in this project and I cant guess anything.

So the question boils down to many small questions:

Is putting stack trace in files is bad? Since writing to files has nothing to do with UX, is just that security issue that makes it look bad idea?

If answer to first question is Yes, then does the concept of stacktrace is meant to be used only during the development time?

If answer to first question is Yes, then is it a wise way to put simplified error messages in files and then do guessing?

What are standard approaches followed in the industry?

答:
Is putting stack trace in files is bad? Since writing to files has nothing to do with UX, is just that security issue that makes it look bad idea?

No it is not a bad thing. It is a good thing.

Fatal errors need consistent and clear logs and information to attempt to reproduce the error, verify the error seen, triage, resolution and then testing. Depending on the target environment, crash dumps are not always possible or feasible to get hold of. Developer focused logs are very useful.

I would expect a few things to be in that log, inter alia;

Stack trace (where)

The actual error or exception (what)

Any inner exceptions (how)

Function argument values (when)

Possibly the user rights (who)

Date and time for cross referencing

Possibly a user description of what they were doing, this may be tied to the bug report filing

On the security issue, if there is sensitive data in the log, it will then need to be sanitised or encrypted. Deal with the security, but don't let it obscure the error.

Crash dump files and ilk are a well known concept. Use them judiciously and they are very helpful and useful.


问:
Is it bad to store data in JSON form or should I use mySQL?
I've been building an application and the whole thing is built around a simple data storage system.

Create an array.

Convert it into JSON.

Add <?php die() at the beginning to prevent access.

Save to PHP file and save to disk.

Then.

Open file.

Remove <?php die();.

Decode it from JSON.

Edit/Read array.

Save it back to file if edited.

Is this a safe way to store data? When I made this I didn't know MySQL, and I still don't know it that well. However, I want to make the choice to whether to edit my platform while it is small and change it to MySQL or to keep using the current system.

I've never encountered issues with a file being edited at the same time, and it doesn't seem to make the website slower at the moment.

Is it worth changing my medium sized application now, and not face having to spend weeks changing it now it is growing? Or is the current system secure enough to keep using.

This is what the system currently works from;

Setting data:

```<code>function setDat($dat_file, $sec, $subsec, $val) {
    global $INS_DIR;
    $dat_file_dat = json_decode(str_replace("<?php die(); ", "", file_get_contents($_SERVER['DOCUMENT_ROOT'] . $INS_DIR . 'data/dat-'.$dat_file.'.php')), true);
    $dat_file_dat[$sec][$subsec] = [$val];
    file_put_contents($_SERVER['DOCUMENT_ROOT'] . $INS_DIR . 'data/dat-'.$dat_file.'.php', "<?php die(); ".json_encode($dat_file_dat));
}
</code>```

Getting data:

```<code>function getDat($dat_file, $sec, $subsec) {
    global $INS_DIR;
    $dat_file_dat = json_decode(str_replace("<?php die(); ", "", file_get_contents($_SERVER['DOCUMENT_ROOT'] . $INS_DIR . 'data/dat-'.$dat_file.'.php')), true);
    return $dat_file_dat[$sec][$subsec][0];
}
</code>```

And so on.

If I explain this:

$dat_file is the file that the data will be stored in, a file within /data/

$sec is the top level of the array you want to edit $array[$sec];

$subsec is the second level array $array[$sec][$subsec];

I do this because each application can use the $sec as the category for the data, and the $subsec and the search within their category. They can also have their own file. So the file main-settings has a category called theme-settings and then some information like active-theme which is set to default.

So this being said, it it worth keeping the current system and will it cope in the future? What are its weaknesses, and any problems with it.

OR

Should I start to change everything to MySQL, even though I will have to reprogram the whole data side of my program? What are the upsides to this and downsides?

答:
If you ask for my opinion and my advice. Go with MySQL because in the previous years I have built application using a JSON data structure but it has been very hard to maintain (it might also be my lack of knowledge).

JSON is cool and simple. I admit !! But not as powerful as MySQL.

Go with MySQL.

MySQL Vs JSON


问:
How to make a large codebase easier to understand
Suppose that I am developing a relatively large project. I have already documented all my classes and functions with Doxygen, however, I had an idea to put a "programmer's notes" on each source code file.

The idea behind this is to explain in layman's terms how a specific class works (and not only why as most comments do). In other words, to give fellow programmers an other-view of how a class works.

For example:

```<code>/*
 * PROGRAMMER'S NOTES:
 *
 * As stated in the documentation, the GamepadManager class
 * reads joystick joystick input using SDL and 'parses' SDL events to
 * Qt signals.
 *
 * Most of the code here is about goofing around the joystick mappings.
 * We want to avoid having different joystick behaviours between
 * operating systems to have a more integrated user experience, since
 * we don't want team members to have a bad surprise while
 * driving their robots with different laptops.
 *
 * Unfortunately, we cannot use SDL's GamepadAPI because the robots
 * are interested in getting the button/axes numbers, not the "A" or
 * "X" button.
 *
 * To get around this issue, we created a INI file for the most common
 * controllers that maps each joystick button/axis to the "standard"
 * buttons and axes used by most teams.
 *
 * We choose to use INI files because we can safely use QSettings
 * to read its values and we don't have to worry about having to use
 * third-party tools to read other formats.
 */
</code>```

Would this be a good way to make a large project easier for new programmers/contributors to understand how it works? Aside from maintaining a consistent coding style and 'standard' directory organization, are there any 'standards' or recommendations for these cases?

答:
If the code base is large - I try to provide a design document that maps out the key elements of its design and the implementation. The intention here is not to detail any of the classes used, but provide a key to code and the thought that went into the design. It gives a overarching context to the system, its components and the application thereof.

Things to include in the design document are;

Application architecture

Logical code structure

Data flows

Key patterns used and the motivation behind their use

Code source structure

How to build it (this offers insight into implicit dependencies and physical code source structure)

Following on from this, documentation for the classes, and functions/methods should be completed as appropriate. In particular the public API; it should be clear what the following all are in each case;

Preconditions

Effects

Invariants

Exception conditions (throws)

ContentLicense: CC BY-SA 4.0


答:
Did you consider using some JSON-based noSQL database like MongoDB? It might perhaps fit your needs.

And you obviously can put JSON text in some SQL relational database like PostgreSQL, MariaDB (or MySQL) or Sqlite

Saving your persistent state as some PHP file is brittle, error-prone (beware of code injection), and probably not very efficient. Several languages better than PHP (e.g. HOP, Opa, Ocaml with Ocsigen, ...) are handling persistence (and mixing of browser & server computation) much better than PHP.

Title: Is it bad to store data in JSON form or should I use mySQL?

Body:
I've been building an application and the whole thing is built around a simple data storage system.

Create an array.

Convert it into JSON.

Add <?php die() at the beginning to prevent access.

Save to PHP file and save to disk.

Then.

Open file.

Remove <?php die();.

Decode it from JSON.

Edit/Read array.

Save it back to file if edited.

Is this a safe way to store data? When I made this I didn't know MySQL, and I still don't know it that well. However, I want to make the choice to whether to edit my platform while it is small and change it to MySQL or to keep using the current system.

I've never encountered issues with a file being edited at the same time, and it doesn't seem to make the website slower at the moment.

Is it worth changing my medium sized application now, and not face having to spend weeks changing it now it is growing? Or is the current system secure enough to keep using.

This is what the system currently works from;

Setting data:

```<code>function setDat($dat_file, $sec, $subsec, $val) {
    global $INS_DIR;
    $dat_file_dat = json_decode(str_replace("<?php die(); ", "", file_get_contents($_SERVER['DOCUMENT_ROOT'] . $INS_DIR . 'data/dat-'.$dat_file.'.php')), true);
    $dat_file_dat[$sec][$subsec] = [$val];
    file_put_contents($_SERVER['DOCUMENT_ROOT'] . $INS_DIR . 'data/dat-'.$dat_file.'.php', "<?php die(); ".json_encode($dat_file_dat));
}
</code>```

Getting data:

```<code>function getDat($dat_file, $sec, $subsec) {
    global $INS_DIR;
    $dat_file_dat = json_decode(str_replace("<?php die(); ", "", file_get_contents($_SERVER['DOCUMENT_ROOT'] . $INS_DIR . 'data/dat-'.$dat_file.'.php')), true);
    return $dat_file_dat[$sec][$subsec][0];
}
</code>```

And so on.

If I explain this:

$dat_file is the file that the data will be stored in, a file within /data/

$sec is the top level of the array you want to edit $array[$sec];

$subsec is the second level array $array[$sec][$subsec];

I do this because each application can use the $sec as the category for the data, and the $subsec and the search within their category. They can also have their own file. So the file main-settings has a category called theme-settings and then some information like active-theme which is set to default.

So this being said, it it worth keeping the current system and will it cope in the future? What are its weaknesses, and any problems with it.

OR

Should I start to change everything to MySQL, even though I will have to reprogram the whole data side of my program? What are the upsides to this and downsides?


问:
What's the best way to track updates when syncing data from MySQL remote server to local SQLite database?
I'm making an iOS App, well, two actually. App A will be able to write TO-DOs to a remote MySQL database, and App B will be able to read what App A has written/modified. App B needs to be always up-to-date and there can be more than one instance of App B running on different iDevices. App B stored the almost-exact copy of what App A has written on the remote MySQL DB, in a local SQLite DB. MySQL operations are handled by a simple PHP script. The problem is how to update App B' local DB when something changes on the remote MySQL database (that is, when App A writes something new or modifies something existing). I came up with two possible solutions: The first is to tell the PHP the last_row_id (the id of the last row that App B has got from the server) so that the PHP can ask MySQL to get all the rows with a greater ID (ID is an auto increment value on MySQL table).

But... This won't help to discover the changed items.

The second solution I thought was to put a "last_updated" column on the MySQL with a timestamp and update it every time the row changes. App B should store the timestamp of the last sync, and report back this value to PHP so that the it can request the MySQL all the rows that have a timestamp greater than the one it receives from App B.

But... Both solutions fail when the MySQL is sharded and clustered (and this is what I'm interested in the most). The auto-increment id approach fails because it will no longer be progressive (see auto_increment_offset and auto_increment_increment), and the timestamp approach would be unreliable because the clock can be out of sync on any MySQL server.

How would you solve this problem in a reliable way?

答:
Invertible Bloom filters, e.g., per this paper.

The GNU Name System video from 30c3
has an intro.  Server adds primary keys of records it has to a filter. Client sends server primary keys of records client has.  Server removes those from filter.   What remains are records to send to client.

To cut down bandwidth used, you can store coarser timestamps.  E.g., only send records starting from the week before the last sync.  Then it will work even if your clocks are off by several days.


问:
Is it good practice to assign an instantiated class to a static property in the same class?
I have code that was written by someone else that goes like this:

On a ViewModel:

```<code>public static ACertainViewModel Default { get; private set; }
</code>```

On the same ViewModel's constructor:

```<code>    public ACertainViewModel()
    {
        Default = this;
    }
</code>```

On a method in the class that ACertainViewModel implements:

```<code>        if (ACertainViewModel.Default != null && ACertainViewModel.Default.property != null)
        //do something to property
</code>```

Seems to work, but it doesn't really feel right. Can something go wrong here?

答:
Having a static default instance like that is fine.

This particular implementation though is not fine. If you have a static default instance, I would expect there to be one static default instance. As shown, this changes the static default instance every time you make one of these (and leaves it null until then).

It would be better to do this in a static constructor, initializer, or getter so that you only have one, and it is always there when you ask for it.


问:
CQRS: How to restore read model
It's very interesting how to restore read model in system based on CQRS.

In regular mode system processes commands, creates domain events and posts them to message bus. Then another part of system (call it RM subsystem) processes these messages and saves them to read model. This mode is good enough for regular purpose.

But how should I repair my read model? For example storage with read model was corrupted or I changed location of storage. I want my system to restore read model during initialization, before queries begin to try read data. And I want to know the end of repairing process.

I can imagine two ways:

Create REST controller, throug which my RM subsystem will be able to query all domain events (in messages forms) and restore it synchronously.

Create special mechanism, calling which my RM subsystem will be able to start replaying all messages. As for me, this way isn't very good, because I cannot control time of finish of repairing process. And the second, if there are other consumers of messages, they probably can corrupt their data.

Which way is more preferable?

答:
If the query model ("read model") is stored in a full-fledged transactional database, normally you do not have to care about such things, because "reparing a corrupted read model" should be possible by the backup/restore mechanism of your database. So lets assume this is not the case (maybe you backup your read model only once per night), whilst your command model is fully backuped (maybe in some kind of sequential log). This means a repair of the read model will be include a restore from the latest backup and afterwards executing the commands from the command model. (Note that transactional database internally work with a transaction log which works exactly like that, allowing you to restore your "read model" up to the point immediately before a system crash).

I am not an expert on CQRS, but when I understood that concept right, there is a time lag to expect between the state of the data in the "query model" and the state of the data implied by the command model. So your system should be able to handle eventual consistency anyway, which is what you have to deal with when choosing an asynchronous repair process. Therefore, option 2 is a viable solution, as well as option 1.

The difference is that option 2 might bring your system faster on-line back again after a corruption of the read model, for the price of a bigger time lag until the query model and the command model are in-sync again. Option 1 will block your system during the repair process, but when the system goes on-line again, the consistency time lag between the two models is (hopefully) much smaller.

So what you pick depends on the acceptable trade-off between availability and consistency for the particular system, and how much time the actual "repair process" for the system will take. The latter will also depend on speed of the backup/restore process of the databases involved, the amount of data to process, the number of users, the traffic involved, and so on.

Title: CQRS: How to restore read model


问:
How to avoid circular patterns in Node?
I'm new to Node and JavaScript (well, asynchronous programming in general) and I noticed when I was working on a project that the following code is a circular pattern and that these are bad practice for the obvious reason that the module might not have loaded yet (and the example code is throwing errors because of that).

Here's my code:

Main module

```<code>var module2 = require('./module2');

var data = 'data';

module2.fetchStuff(data);
</code>```

Module2

```<code>var module3 = require('./module3');

var cleanDataArray = [];

function fetchStuff(data){
    // Fetches stuff based on data
    module3.cleanStuff(data);
}

function takeStuffBack(data){
    cleanData.push(data);
}

module.exports = {
    fetchStuff: fetchStuff,
    takeStuffBack: takeStuffBack,
    cleanData: cleanDataArray
};
</code>```

Module3

```<code>var module2 = require('./module2');

function cleanStuff(data){
    // Clean data from needless stuff
    module2.takeStuffBack(data); // I get a TypeError here because `module2` is yet to fully load.
}

module.exports = {
    cleanStuff: cleanStuff
};
</code>```

The XY

What this structure is supposed to do is for the start module to call a fetching function in module2, the fetching function needs to "wash" the data in the 3rd module before taking it back and providing it for whatever wants to export it. So I suppose the XY is that I need to do is to get data from a 3rd party API and then "clean" the data from the things it contains but I don't want, and then I need to make that "clean" version available to the rest of the application.

What other ways are there to do this in a better manner, without a circular pattern such as this which is broken because module2 won't load before module3 tries to call it?

答:
Use a callback, pass takeStuffBack to cleanStuff as callback taking the data:

```<code>function cleanStuff(data, continuation){
    // Clean data from needless stuff
    continuation(data);
}
</code>```

fetchStuff in module2 becomes:

```<code>function fetchStuff(data){
    // Fetches stuff based on data
    module3.cleanStuff(data, takeStuffBack);
}
</code>```

Title: How to avoid circular patterns in Node?

Body:
Use a callback, pass takeStuffBack to cleanStuff as callback taking the data:

function cleanStuff(data, continuation){
    // Clean data from needless stuff
    continuation(data);
}

fetchStuff in module2 becomes:

function fetchStuff(data){
    // Fetches stuff based on data
    module3.cleanStuff(data, takeStuffBack);
}


问:
Upgrading from XP Pro to Win 7, anything I should worry about?
I do mainly .NET work so I assume that the framework is all fine and that.  But have there been reports of various tools like .NET Reflector and the like not working properly with Win 7?  This is a company-wide thing so there isn't much I can do about it, but once everything is reinstalled I'm hoping to not find anything shocking.

Cheers.

答: For me IIS 5+ to IIS7 was a big jump. You might want to consider that. :)</p>


答:
You can create a transaction log table with guids which stores the changes made and by whom and when (and on what table/entity if you choose to break it out).

ex:
logid|trantype|oldvalue|newvalue|datetime|user
{guidxx1234}|update  |{x=1, y=5}|{x=1, y=7}|yyyymmdd hh:mm|username or id
{guidxx1235}|insert  |{}        |{x=45, y=7}|yyyymmdd hh:mm|username or id

The sync process would have to repopulate the changes made in the local database to the server database by comparing missing transactions in this log.

This may not necessarily be the best way for you, but easy enough to implement regardless of db vendor.

Title: What's the best way to track updates when syncing data from MySQL remote server to local SQLite database?

Body:
I'm making an iOS App, well, two actually. App A will be able to write TO-DOs to a remote MySQL database, and App B will be able to read what App A has written/modified. App B needs to be always up-to-date and there can be more than one instance of App B running on different iDevices. App B stored the almost-exact copy of what App A has written on the remote MySQL DB, in a local SQLite DB. MySQL operations are handled by a simple PHP script. The problem is how to update App B' local DB when something changes on the remote MySQL database (that is, when App A writes something new or modifies something existing). I came up with two possible solutions: The first is to tell the PHP the last_row_id (the id of the last row that App B has got from the server) so that the PHP can ask MySQL to get all the rows with a greater ID (ID is an auto increment value on MySQL table).

But... This won't help to discover the changed items.

The second solution I thought was to put a "last_updated" column on the MySQL with a timestamp and update it every time the row changes. App B should store the timestamp of the last sync, and report back this value to PHP so that the it can request the MySQL all the rows that have a timestamp greater than the one it receives from App B.

But... Both solutions fail when the MySQL is sharded and clustered (and this is what I'm interested in the most). The auto-increment id approach fails because it will no longer be progressive (see auto_increment_offset and auto_increment_increment), and the timestamp approach would be unreliable because the clock can be out of sync on any MySQL server.

How would you solve this problem in a reliable way?


问:
Deploy PHP application on customer server independent of the envirorment
Our company has developed a PHP(CakePHP) "Cloud" application that is running on our servers, now we have some customers that would like to use our service and make integrations to their local systems. The local systems are behind a firewall that won't be opened for us to access them from the "Cloud", therefore we need to deploy our system on their servers.

How to do this in a way that makes us able to:

Make it independent of existing software versions on the server(might be an old PHP version installed or something similar that we are not allowed to upgrade).

Update the system.

Track usage of the system(we charge based on features that the user can activate, no problem on Cloud were we have access to the database)

I think that we can assume that the server will have internet access. The initial installation will be done by us via VPN or on site, alternatively we can let the customer install it if the procedur is easy enought.

We think that we can solve 2 and 3 by letting the system make requests to some kind of "licensing server" that we need to build. Is there a best practice here or maby some ready to use software?

The biggest issue for us is 1., we are looking at setting up a virtual machine(the clients will not have vmware so were talking about something like virtualbox that can be running on an exsisting OS) that the entire system with all of it dependencies will run on, here we are also looking for any best practice advice. Maby a virtual envirorment isn't a good way to go?

Any help or thoughts is appriciated!

答:
You can utilize a cloud hosting provider like Microsoft Azure, which is in no way limited to Windows VM's, they have plenty of Unix/Linux images as well as give you the ability to upload your own VM's.  Amazon has similar features.

You can create virtual networks, web farms, create vpn connections, etc, manage multiple subscriptions and add users at different levels like VM Contributor and admin.
https://channel9.msdn.com/azure

Once you have your images/networks set the way you want, and users still wish to have the environments in-house instead of the cloud, they can install the Azure Pack, which allows the "Azure" features to exist on a physical (or local VM) datacenter. https://technet.microsoft.com/en-us/library/Dn296435.aspx

Or just use the VM images you have and put copies up on their VLAN if they are a completely non-Microsoft shop and still want in-house.


问:
Should I, and if so how do I, learn to favour upfront design with abstraction over retrospective removal of repetition?
I am often in a situation where I have to design and code a process/algorithm, and there are different variants on that algorithm.  For example, I am currently writing some database sychronisation code that has methods for download and upload.  Those methods are similar, but not identical.

Having written the code, and got it to work, I am now refactoring it to remove the repetition.

I am not so bad at writing classes which mainly hold data, in those cases I find it easier at the beginning to apply entity-relationship modelling, break the data down into classes, and I can fairly quickly see common elements that can be put into base/abstract classes.

But I find it harder with algorithms/processes.

My questions are: is it better to take more time to design it up-front, thus avoiding the need for refactoring? And, if so, how do you get good at doing this?

I find that when I design up-front, because there is no way to test the design, I often go way off tangent and as soon as I start writing the code the design gets discarded.  In contrast, with incremental development, you can regularly test your code to ensure it works.  But the disadvantage of the way I do incremental development, is the extra time spent refactoring at the end so that I write "DRY" code.

答:
You are pretty much pointing at the issue yourself: "...is the extra time spent refactoring at the end so that I write "DRY" code"

The point of writing incremental code and coding under test is to achieve the so-called 'red-green-refactor' cycle:

Red: write a failing test that shows a shortcoming in your code

Green: write the code to make the new test, along with the other existing tests, pass

Refactor: get rid of code smells, duplication, things like that. While doing this, keep the tests running and make sure they pass

It feels to me like you are doing the entire coding and, only when you are finished, you get to shoring up the code. Don't do that. Write a well-defined piece of your code, get it under test and then start refactoring it. The tests you just wrote will help you and prevent you from breaking the code while refactoring.


问:
GUI functional acceptance tests, making them less brittle / obstacle to further development
(Background - skip to bold statement for the crux)

I'm working through the book "Growing Object-Oriented Software, Guided by Tests" by Freeman & Pryce, while applying it to a project I'm starting. My app is a web app in PHP that manages a user's eBay interactions.

I'm using Behat/Mink to write the end-to-end tests. I'm stuck on the very first test.

In the book, they stress the importance of first writing tests that then guide the writing of the code to make them pass. And that the tests should not get in the way of development, including changes to requirements, refactoring, and so on.

They stress that the first test should exercise the system end-to-end; e.g. commanding the user interface, using a database, to interacting with an external system such as eBay; and that this feature should be minimal.

But this means that the GUI for the first test is unlikely to remain as-is for future tests, and therefore the first (and subsequent) tests should be as flexible as possible so that inevitable changes to the GUI won't break the tests (which would have at least two major side effects: time re-writing the tests, AND risking that those re-written tests fail to catch bugs that the originals would have caught). The latter is what really worries me - In the book "The Pragmatic Programmer" they emphasize "Find bugs once".

So that's the abstract problem. Applying it to my project, I was thinking of first writing a slice of the system that accumulates records of purchases made from the user. This would involve setting up notifications on eBay that make a call to my application each time a customer commits to buy something from the user. The functional test would simulate that, and then check via the GUI that the order appears in the list (which I'd implement initially as a simple, single HTML table) visible to the user.

But once the customer commits to buying, they then need to pay for it via Paypal. The records that the app handles then become complex, since some users may never pay at all, some will pay, some will have full refunds, partial refunds, multiple refunds, messages may be exchanged between the user and customer, the user might want to print postage labels from the interface, etc etc.

So in all likelyhood the GUI will become unrecognisable from that written to satisfy the first test feature.

How can these two problem best be dealt with?

Time involved in adapting the GUI test code

Risk of re-written old tests failing to catch bugs for an old feature that previous tests would have caught

I've come up with some ideas, but it feels like a pandora's box that has overwhelmed me, and I'm wondering if anyone can point me in the right direction, possibly with reference to other books etc:

First idea: write the Behat tests (Gherkin) which would remain unchanged, but modify the Mink code that interpret those statements each time the GUI is changed. This solves very few problems, but at least the Gherkin statements would likely need no modifications.

(Extremely vague idea) Make the GUI layer as thin as possible, possibly multiple wafer-thin layers of abstractions just for the GUI, with matching abstractions in the tests, some how in such a way that would prevent changes in the GUI from affecting much of the tests. (Honestly, I don't have a clue how this would work).

Freeman/Pryce give a hint: "Make changes in the smallest possible steps". This makes it easier to correlate changes in the requirements/GUI design with changes in the tests. But ultimately as the changes in the GUI accumulate, I don't see how the risk of ineffective tests wouldn't also accumulate.

Apologies for the long question.

答:
Don't write GUI tests to match the GUI. Write acceptance tests that match requirements

You could write your tests like this:

Given I enter "user" into the username field and "pass" into the password field

And I click the "Login" button

When I click the Find User button

And I enter "foo" into the username field

And I click "Search"

Then I should see a table with a user "Johnny Foo" in row "1"

And I should see a table with a user "Manny Foo" in row "2"

Or you could write them like this:

Given I am logged in as "user" with password "pass"

And I look for users called "foo"

Then the searchresults should show "Johnny Foo" on row "1"

And the searchresults should show "Manny Foo" on row "2"

The first one completely couples you to the GUI. The second one only couples you to what you need in terms of functionality, stories and requirements.

This way, you write code that becomes re-usable. The lines in your tests are functional expressions and there is code that matches these to the concrete GUI-implementation, but if something changes in your GUI you only have to make a change in one location, which is the place where you map things like "I look for users called 'foo'" to concrete GUI code.

Case-in-point: yesterday I switched a page for an application I work on from being loaded with a submit to fetching and displaying data using JSON and Knockout. That means that, instead of clicking a button and waiting for a submit I was now displaying a loading-animation which goes away when the data is loaded. Try this with the example above: in the first example you'll need to add that wait as a step, in the second you just tag that along with the "I look for users called 'foo'"-implementation. Now if you have three tests that look like my first example, no sweat. But what if you have ten? Or a hundred?

By the way, if you look at the examples for Behat/Mink and the Gherkin DSL it uses, you'll see these are very general, human-readable examples. This is not by accident, it serves as a very good example of how you should think when writing tests at this level.


答:
I find that when I design up-front, because there is no way to test
  the design, I often go way off tangent and as soon as I start writing
  the code the design gets discarded.

The difference between and up-front (waterfall) type of design compared to incremental, is the amount of requirements you approach. To help you solve your current problems, you need to be able take a design (start small) and build it without going off tangent. Once you realize the design has flaws, stop coding, and redesign.

The goal is not to be able to come up with a perfect design up-front nor to be able to blindly code a flawed design, but to come to some sort of happy medium. The extreme to your current practice would be to create an over-all design, but then just cowboy code the project. When the design isn't going to work, stop coding and fix the design.

Some of the refactoring and/or code sharing may get recognized when creating that second class or even later. As you improve, you'll not only get better at up-front designing, but also better at recognizing how much up-front design is possible or even practical. When you work with a team and they assume everyone agrees on the current design, there is going to be trouble if one programmer goes off on a tangent. Don't let it be you. Stop the team if necessary and redesign.

Title: Should I, and if so how do I, learn to favour upfront design with abstraction over retrospective removal of repetition?

Body:
I am often in a situation where I have to design and code a process/algorithm, and there are different variants on that algorithm.  For example, I am currently writing some database sychronisation code that has methods for download and upload.  Those methods are similar, but not identical.

Having written the code, and got it to work, I am now refactoring it to remove the repetition.

I am not so bad at writing classes which mainly hold data, in those cases I find it easier at the beginning to apply entity-relationship modelling, break the data down into classes, and I can fairly quickly see common elements that can be put into base/abstract classes.

But I find it harder with algorithms/processes.

My questions are: is it better to take more time to design it up-front, thus avoiding the need for refactoring? And, if so, how do you get good at doing this?

I find that when I design up-front, because there is no way to test the design, I often go way off tangent and as soon as I start writing the code the design gets discarded.  In contrast, with incremental development, you can regularly test your code to ensure it works.  But the disadvantage of the way I do incremental development, is the extra time spent refactoring at the end so that I write "DRY" code.


问:
Appropriate to put known issues directly in software?
I've taken over maintenance of an Android app, and there are a few residual problems that I've more or less fixed, but still have issues because of different Android OS versions.

For example, sending a web request with the MediaPlayer class has custom HTTP headers stripped by the OS before the request is sent out, but only on Android 4.X (I exhaustively tested), and that causes this particular feature to fail because it relies on those headers.

This is a known issue and I'm trying to work around it, but would it be a good idea to have a conditional check like

```<code>if (OS.VERSION == 4) {
    knownIssueDialog(This feature will not work on your Android version... etc.");
}
</code>```

Obviously we would have this noted on our support channel, but I'm wondering if it would be a good idea (assuming everything is kept track of) to have these known issues also embedded in software, and to present them when and where necessary, such as what I described above.

We keep getting multiple bad reviews and a lot of support emails based on these kinds of issues, so in my mind it would save everyone a lot of time and headache by simply blocking a feature where it is known not to work properly.

I see two potential problems:

Users have probably never seen anything like a "known issue" dialog before; a lot of users simply might not understand what it means.

There is a bit of development overhead - one would need to make sure to keep track of these issues somewhere in the code. Fortunately, with Java annotations, any conditional check like that could be preceded by @KnownIssue or something like that, making finding/modifying them very simple.

Would putting 'known issue' prompts in software make sense?

Edit: I'll add that this is an issue that just started occurring about a week ago. I have half-fixed the issue, and am very unlikely to be able to fix it for 4.X because it's the OS that is causing the problem. I could release a new version with the fix and make 50% of the user base happy again, and warn the other 50% (4.X users) that the issue will persist on 4.X, and to suggest an upgrade (or something). The question is whether or not to do that in software (i.e. show a dialog to 4.X users), or to just let them spam us support emails saying "your fix didn't work!!!" and then direct them to the support page that discusses the issue in further detail.

答:
Multiple bad reviews + tons of support emails == unhappy customers. Are you going to make them happy by 'failing more gracefully' for certain conditions? Maybe. However, if I were you I'd rethink whether I released the software prematurely and I should have just fixed some of those issues before it would get in front of the customer.

Update:
If this is an un-fixable issue due to environment, I'd put in the prompt to inform the users (AND also have it documented and sent out in an email). This works for an isolated issue like this, but I would not advise it as a general solution for just any 'known bug'. If there are many of these, then you are doing something wrong.


答:
For some reason, designing up front feels to our brains like it should be faster, but it rarely is.  It's much easier to factor out duplication from two working, concrete functions already in your editor than it is to factor out duplication from two ephemeral functions that haven't been written yet.

The trick is to make your refactor cycle tight.  If you're doing a refactor every few minutes, that's basically indistinguishable from being really good at up front design.  On really complex algorithms, I might go an hour or two without a refactor phase.  You're doing it wrong if you ever tell your boss something like, "It works, but I need a couple more days for refactoring."


问:
Should a method be forgiving with the arguments that are passed in?
Suppose we have a method foo(String bar) that only operates on strings that meet certain criteria; for example, it must be lowercase, must not be empty or have only whitespace, and must match the pattern [a-z0-9-_./@]+. The documentation for the method states these criteria.

Should the method reject any and all deviations from this criteria, or should the method be more forgiving about some criteria? For example, if the initial method is

```<code>public void foo(String bar) {
    if (bar == null) {
        throw new IllegalArgumentException("bar must not be null");
    }
    if (!bar.matches(BAR_PATTERN_STRING)) {
        throw new IllegalArgumentException("bar must match pattern: " + BAR_PATTERN_STRING);
    }
    this.bar = bar;
}
</code>```

And the second forgiving method is

```<code>public void foo(String bar) {
    if (bar == null) {
        throw new IllegalArgumentException("bar must not be null");
    }
    if (!bar.matches(BAR_PATTERN_STRING)) {
        bar = bar.toLowerCase().trim().replaceAll(" ", "_");
        if (!bar.matches(BAR_PATTERN_STRING) {
            throw new IllegalArgumentException("bar must match pattern: " + BAR_PATTERN_STRING);
        }
    }
    this.bar = bar;
}
</code>```

Should the documentation be changed to state that it will be transformed and set to the transformed value if possible, or should the method be kept as simple as possible and reject any and all deviations? In this case, bar could be set by the user of an application.

The primary use-case for this would be users accessing objects from a repository by a specific string identifier. Each object in the repository should have a unique string to identify it. These repositories could store the objects in various ways (sql server, json, xml, binary, etc) and so I tried to identify the lowest common denominator that would match most naming conventions.

答:
You can name a method according to the action like doSomething() , takeBackUp () .

To make it easy to maintain you can keep the common contracts and validation on different procedures . Call them as per use cases.

Defensive programming : your procedure handles wide range of input including
(Minimum things those are use cases must be covered anyway)


问:
What do you think about the Joel Test?
The Joel Test is a well known test for determining how good your team is. What do you think about the points? Do you disagree with any of them? Is there anything that you would add?</p>

答:
I have to say that it is a good "baseline", but with any measuring tool there are other factors.  For example not a single company that I have worked for has done Daily Builds (I know, I know), but some of them have been very good.

I personally have a few other items that I would add to a list.

Do you support developer education by attending conferences, purchasing books, or something of that nature?

Do you have a simple, documented process to adopt new tools if necessary to complete job functions

Do you provide developers equipment and an environment that will allow them to be productive.

More than anything these are items have have "pissed me off" from previous employers, and well they are now fast track questions that I ask about each and every opportunity.

Title: What do you think about the Joel Test?


问:
using one database connection across multiple functions in python
whats the best way to go about this in python? I have a number of like so

```<code>def test1()
    .... code .....
def test2()
    .... code .....
def test3()
    .... code .....
</code>```

how could I create one database connection and use it across all the functions? I'm connecting to my database in a test file like so:

```<code>import MySQLdb as mdb
import sys

try:
    con = mdb.connect('10.243.17.13', 'mark', '********', 'dex');

    cur = con.cursor()
    cur.execute("SELECT VERSION()")

    ver = cur.fetchone()

    print "Database version : %s " % ver

except mdb.Error, e:

    print "Error %d: %s" % (e.args[0],e.args[1])
    sys.exit(1)
</code>```

答:
The problem is well known and the keyword you may be searching for is pooling.

The idea is that opening a connection is a complicated task: is usually requires reaching the server, doing authentication, checking the rights, auditing, etc.

On the other hand, preserving the same connection through the application by either storing it in a static variable or passing it to every method which may require access to the database is usually ugly and difficult to implement. Not counting the fact that in this case, the connection may remain opened for a long time while being unused, eventually reaching the maximum number of connections allowed by the server.

Connection pooling consists of preserving the pool of connections under the hood in order to make it possible for the programmer to open the connection and close it as soon as it is not needed any longer. The actual connections are managed transparently, meaning that you don't have the overheat of a connection opened again and again and you are less at risk of using all available connections.

Further reading:

Opening and closing database connection for each query at Stack Overflow.

Pooling and performance: what benchmarks and profiling may reveal, an article from my blog.

Now, not reusing the connection doesn't mean you should duplicate database logic in every of your tests. You may put connection and disposal logic in a class with special __enter__ and __exit__ methods, and then use it as:

```<code>with DatabaseConnection() as db:
    cursor = db.connection.cursor()
    ...
</code>```

Note that since you mention tests in your code sample:

You may be interested in using a testing framework. After all, you said that you "just play with Python, learning by doing", so why not to learn a Python's testing framework as well?

As others noted, unit tests shouldn't access a database. But access to databases is perfectly fine in integration or system tests.

Body:
The problem is well known and the keyword you may be searching for is pooling.

The idea is that opening a connection is a complicated task: is usually requires reaching the server, doing authentication, checking the rights, auditing, etc.

On the other hand, preserving the same connection through the application by either storing it in a static variable or passing it to every method which may require access to the database is usually ugly and difficult to implement. Not counting the fact that in this case, the connection may remain opened for a long time while being unused, eventually reaching the maximum number of connections allowed by the server.

Connection pooling consists of preserving the pool of connections under the hood in order to make it possible for the programmer to open the connection and close it as soon as it is not needed any longer. The actual connections are managed transparently, meaning that you don't have the overheat of a connection opened again and again and you are less at risk of using all available connections.

Further reading:

Opening and closing database connection for each query at Stack Overflow.

Pooling and performance: what benchmarks and profiling may reveal, an article from my blog.

Now, not reusing the connection doesn't mean you should duplicate database logic in every of your tests. You may put connection and disposal logic in a class with special __enter__ and __exit__ methods, and then use it as:

with DatabaseConnection() as db:
    cursor = db.connection.cursor()
    ...

Note that since you mention tests in your code sample:

You may be interested in using a testing framework. After all, you said that you "just play with Python, learning by doing", so why not to learn a Python's testing framework as well?

As others noted, unit tests shouldn't access a database. But access to databases is perfectly fine in integration or system tests.


问:
Reward discounting in reinforcement learning
I've been reading the Sutton and Barto book and following David Silver's lectures on youtube. The basic principles make a lot of sense to me and I've been building a maze (an arbitrary grid where the agent can move up, down, left right unless blocked by a wall) solving agent that learns by randomly sampling paths and as it learns it weights its 'random' choice by the amount of reward received.

Because the agent can only assign a value to the state (its choice of direction when moving to next square) once it has reached the goal, the reward is delayed. When the agent gets to the goal, I have a chain of choices that led to it.

My first thought was to discount the reward assigned to each square in that chain by a percentage like 90% for each square away from the goal. So

```<code>GOAL   = 1
GOAL-1 = 1 * 0.9
GOAL-2 = 1 * 0.9^2
...
</code>```

However this results in a reward so small to be meaningless in a grid any larger than about 5x5.

The rewards have to differ of course for choices that had less influence on reaching the goal, but I can't figure out how to sensibly assign them.

答:
Disclaimer - outis is right in his comment, this isn't good
  approach. Still, I'll try to answer your question, I'm curious if
  that'll work.

OK, let's start with notation.

reward - base reward, in your example = 1

modifier(i) - modification of reward for ith step, in your example = 0.9^i

total(i) - total reward for step i, in your example reward*modifier(i)

I - length of your solution, meaning number of steps taken to solve the problem (it will vary with each solution, but that shouldn't be a problem)

total(I) - minimal wanted reward

Your problem arises because sequence modifier(i) converges to 0 in infinity.

Use something else. Choose which steps - first or last - have more impact on your solution. If most profit comes from first steps, sequence modifier(i) should be descending, and it should be ascending in other case. Let's assume that first steps are more important. If not, just use modifier(I-i) instead of modifier(i).

If you want total(0)=1 and total(I)=0.5 with geometric progress, then you know that:

```<code>reward=1
reward*(q^I)=0.5
</code>```

where q is scaling factor. Now you calculate it as:

```<code>q = 0.5^(-I)
</code>```

Voila! No matter how long your solution is - each step will have some non-zero impact on learning.

You can use other sequences too - for example linear:

```<code>total(i) = reward-i*a
reward-I*a = r
</code>```

solved for a.

Of course these aren't your only options - you could use for example sqrt or log for ascending modifier (but those are not the only options - use your imagination here). I think you'll figure the math yourself.

Body:
Disclaimer - outis is right in his comment, this isn't good
  approach. Still, I'll try to answer your question, I'm curious if
  that'll work.

OK, let's start with notation.

reward - base reward, in your example = 1

modifier(i) - modification of reward for ith step, in your example = 0.9^i

total(i) - total reward for step i, in your example reward*modifier(i)

I - length of your solution, meaning number of steps taken to solve the problem (it will vary with each solution, but that shouldn't be a problem)

total(I) - minimal wanted reward

Your problem arises because sequence modifier(i) converges to 0 in infinity.

Use something else. Choose which steps - first or last - have more impact on your solution. If most profit comes from first steps, sequence modifier(i) should be descending, and it should be ascending in other case. Let's assume that first steps are more important. If not, just use modifier(I-i) instead of modifier(i).

If you want total(0)=1 and total(I)=0.5 with geometric progress, then you know that:

reward=1
reward*(q^I)=0.5

where q is scaling factor. Now you calculate it as:

q = 0.5^(-I)

Voila! No matter how long your solution is - each step will have some non-zero impact on learning.

You can use other sequences too - for example linear:

total(i) = reward-i*a
reward-I*a = r

solved for a.

Of course these aren't your only options - you could use for example sqrt or log for ascending modifier (but those are not the only options - use your imagination here). I think you'll figure the math yourself.


问:
Field level permission checks for REST API - is this validation?
Let's say that we have some sort of "schema" for a rest resource, something like (pseudocode):

```<code> ExampleResource:
     field1 = field(validate=is_string())
     field2 = field(validate=is_int())
     field3 = field(validate=is_string(max_length(200))
     creator_id = field(validate=is_int())
</code>```

Depending on the permissions the user has, his access should be limited. For example, we might have a user that can POST new resources, but can only PATCH the resources he has created (creator_id is equal to his unique id), we might have another user that can GET all resources, but only has permissions to view field1 and field2 on the resources, we might have a user who only has permissions to PATCH field2 on all resource, etc.

So my question is - would checking the users permissions be part of validating? Something like this:

```<code>ExampleResource2:
    field = field(validate=[is_string(), check_permission(create=permission1, edit=permission2, view=permission3)])
</code>```

I am currently working on a project where permission checks are implemented this way, and I am looking for some input on this - is this good practice? Does it make sense? How else would you implement this?

My own thoughts: On the one hand, since each field is checked for validity anyway, it kind of feels efficient to also check for permissions at the same time - otherwise, you would first have to go through all the fields and check all the permissions, and then go through all the fields again to validate them. On the other hand, this kind of design doesn't feel very SOLID to me.

答:
Since permission should be on a resource level you generally check permissions on a resource before you start validating data, since what is the point of starting validation of the data if the user lacks the permission to change it.

This is how most web frameworks work, permission checking happens right after routing. Once the user is granted access to update the resource then you start validating the data they sent to the server, or constructing a particular view based on the users permission level or group.


问:
Class structure for Entity Framework
I'm using EF (Code first) and I'd like to isolate the properties from the methods (many of the methods reference other libraries that I don't want my database project to have to reference).

As an example, say I have this class

```<code>public class Person
{
  public string Name { get; set; }
  public void SayName()
  {
    SomeExternalAssembly.Say(Name)
  }
}
</code>```

Because SomeExternalAssembly has nothing to do with the database I'd like to move the SayName method to another assembly while maintaining it in a "version" of Person.

In my ideal world (which doesn't work and is probably a bad idea) I'd inherit Person to DerivedPerson then just cast it back to Person when I need to save it to the DB.  While I can perform the cast, when I attempt to add it to the DB I get a System.InvalidOperationException: Mapping and meta data information could not be found for EntityType 'DerivedPerson'.

Since that didn't work the next best solution I can come up with is just adding a Person property to my new class:

```<code>public class PersonB
{
  public Person Data;
  public void SayName()
  {
    SomeExternalAssembly.Say(Data.Name)
  }
}
</code>```

While this would work, I'm looking for something a little cleaner (and ideally less code changes).  The next thought I had was to go with inheriting then add a conversion method using reflection.

Does anyone have a better approach?

答:
If you are 100% sure you want to "bolt on" methods onto these EF table/classes, then just open them up as partial class in a separate file and add the methods needed:

```<code>// location -> /EntityPartials/Person.cs

public partial class Person
{
  public void SayName()
  {
    SomeExternalAssembly.Say(this.Name);
    // 'this.*' above is optional but could be used to quickly identify EF data-properties.
  }
}
</code>```

For the record, I would NOT recommend using partials like this that need to talk to external components that require any kind of class state, since you can't really control constructors easily in EF and therefor lose your power to inject dependencies. However, I have a LINQ-2-SQL project that makes lots of use of the pattern above to do various things like string formatting, conditional validation, etc.

Title: Class structure for Entity Framework

Body:
If you are 100% sure you want to "bolt on" methods onto these EF table/classes, then just open them up as partial class in a separate file and add the methods needed:

// location -> /EntityPartials/Person.cs

public partial class Person
{
  public void SayName()
  {
    SomeExternalAssembly.Say(this.Name);
    // 'this.*' above is optional but could be used to quickly identify EF data-properties.
  }
}

For the record, I would NOT recommend using partials like this that need to talk to external components that require any kind of class state, since you can't really control constructors easily in EF and therefor lose your power to inject dependencies. However, I have a LINQ-2-SQL project that makes lots of use of the pattern above to do various things like string formatting, conditional validation, etc.


问:
Is this OOP class hierarchy too deep?
So I am making a Super Mario Bros NES clone in pygame and for all enemies that are drawn to the window, I have a class hierarchy that is 5 classes deep. Going in the order of:

Object (A base class for all things drawn on the screen)

Character (A class for any type of character, playable or not)

Enemy (A class for any enemy in the game)

BasicEnemy (A class for any enemy that only moves horizontally, as they both act the same, just different visuals. This includes Goombas and Koopas).

Then the deepest classes are Goomba and Koopa, with the class structure stated above. I am doing it this way because all objects that are drawn to the screen all have common properties, as well as all characters, enemies and basic enemies. For example, all enemies move horizontally through the exact same method (adding their x velocity to their x position). I have read in many places that too much inheritance is bad. I'm not sure if what I am doing is too much. And if it is too much, how should I be doing it?

答:
I would have your objects implement interfaces like ICharacter, IEnemy, IHorizontalMover.  The relevant design guideline is known as Favor Composition over Inheritance, and it should allow your design to be more flexible. One difference is that interfaces tend to specify behavior and any given object can implement as much or as little as it needs.

If you feel that this causes code duplication that you did not have when a base class just handled mostly non-overridden methods, then you should be using forwarding methods, where your implementing classes forward method calls to a private class (or stateless static class) that provides a function common to several implementations.  This keeps the codebase DRY (meaning Don't Repeat Yourself).  It can feel like you are writing more boilerplate lines to achieve what inheritance takes care of for you behind the scenes, but it is generally considered worth the effort, leaving the codebase more flexible and open to change than a pure inheritance design.

Title: Is this OOP class hierarchy too deep?


答:
At first glance it sounds reasonable to use inheritance to separate different types of entities: this is the "real-world" approach to OOAD that most colleges teach in CS101. In other words, classes are named based on real-world objects that we can see: desk, dresser, door, etc.

However, that makes little sense in the context of a video game. There are really two categories of concern with the objects you are modeling:

The objects appear on screen and need to be drawn, so it makes sense to model them using classes. After all they have both properties (a sprite or 3D model) and behavior (e.g. movement) which make them candidates for classes.

The objects interact. A player object might interact with a brick block (this is a Mario clone, after all) by standing on it or smashing it. The object might interact with an enemy by stomping on it.

When I analyze these potential classes, I see a lot of the same concerns. Some object move, some do not. Some have "intelligence" behind them (AI or human), some do not. I do not see much value in the hierarchy you presented: the concerns are spread out too much.

I recommend moving the concerns about object control outside of the objects themselves. Here is how I would design it, based loosely on MVC.

Actor would replace Object in your hierarchy. The idea is an actor has some role on the game field. That role might be "do nothing" in the case of a brick that is unsmashable and performs no actions. It might be able to remove itself from the game field (brick gets smashed). It might move: this could be a platform that patrols on a loop, an enemy with an AI, or a player that receives input from a hardware device.

ActorView is passed in to an Actor and controls how it is displayed. This could be as simple as "always display this sprite" or "render this 3D model based on certain criteria."

ActorController is the "brain" of the Actor. One could have a "do nothing" implementation that never changes state (e.g. an unbreakable brick), a simple implementation that can remove the actor (e.g. a breakable brick), a more complex implementation (e.g. a platform that patrols back and forth), an AI implementation (e.g. an enemy), or a player (use hardware input).

Now you can use composition: Actor should really just be one class that takes a view and a controller. The ActorView might have a small number of subclasses that can be reused. Do you really need a different view for each static brick? No, you can simply reuse one class and pass a different bitmap in each time. ActorController could have a small number of subclasses for each broad type of Actor: static, scripted (moves, breaks), AI, player.

Title: Is this OOP class hierarchy too deep?

Body:
So I am making a Super Mario Bros NES clone in pygame and for all enemies that are drawn to the window, I have a class hierarchy that is 5 classes deep. Going in the order of:

Object (A base class for all things drawn on the screen)

Character (A class for any type of character, playable or not)

Enemy (A class for any enemy in the game)

BasicEnemy (A class for any enemy that only moves horizontally, as they both act the same, just different visuals. This includes Goombas and Koopas).

Then the deepest classes are Goomba and Koopa, with the class structure stated above. I am doing it this way because all objects that are drawn to the screen all have common properties, as well as all characters, enemies and basic enemies. For example, all enemies move horizontally through the exact same method (adding their x velocity to their x position). I have read in many places that too much inheritance is bad. I'm not sure if what I am doing is too much. And if it is too much, how should I be doing it?


答:
Instead of trying to figure out the exact class hierarchy you need, how about letting it grow organically?

The big advantage of inheritance is avoiding repetition.  When you put functionality in a base class, you can share that functionality among many different classes without having to put the same code in each one.

So just inherit from Object, write your code, and then start creating intermediary classes where it makes sense to avoid repetition.  When you find two objects doing the same thing, create an abstract class between them and Object and pull the common behavior into that abstract class.

If your hierarchy begins to get too complex, with common behavior among objects that aren't that closely related, that's when you can start to pull behavior out into separate objects and use composition to achieve that behavior...again, in order to avoid repetition.

Title: Is this OOP class hierarchy too deep?


问:
Is there any reason to write delegates/events for one class?
I have a game with such events as GameOver, GameStart, PlayerWin, etc. I only have one class that is listening on these events, for the purpose of sending these events as TCP json messages to a client (player).

But for every important game function I write, I have to write an event and then call

```<code>if(MyEvent != null)
   MyEvent(this, new GameEventArgs("gameover"));
</code>```

I could as easily avoid writing an event for each important action and instead include the listener as an instantiated class and simply send messages that way.

```<code>private GameListener gameListner = new GameListener();

private void GameOver(){
    this.turnTimer.enabled = false;
    this.winner = player; //etc
    gameListener.GameOver(player);
}

class GameListener{
    public void GameOver(Player player){
        JSON json = EncodeJson(GAME_OVER, player);
        SendClientData(json);
    }
}
</code>```

Is there any reason I should stick to events and delegates?

答:
The benefit of events compared to your approach is that more than one or less than one objects can listen to an event. In your case, there could be one and one only game listener.

You may stick with YAGNI and KISS: right now, you have only one object listening to the event, so why bothering?

On the other hand, using events, especially if you consider EventHandler<TEventArgs> generic, is:

Very easy to implement,

Very common in C# world, so other programmers will probably know how to use your code,

Supports from scratch the case when you don't need to listen to the event at all or when multiple listeners exist (for instance, one will send a message over TCP while other will store the new score of the user in the database.)


答:
The main benefit of using events/delegates is Loose Coupling.

When you code the listener into the event-publisher class you are tightly coupling both classes.

Initially this might not be a bad thing, but if your application needs to grow and be extended then tight coupling can make maintenance difficult.

Delegates/events allow the event-publisher to be completely unaware of the event consumer(s).

Of course, as MainMa has already point out, if your current needs are simple then it's perfectly reasonably to apply KISS and YAGNI and put off switching to events/delegates until they are needed.

Title: Is there any reason to write delegates/events for one class?

Body:
I have a game with such events as GameOver, GameStart, PlayerWin, etc. I only have one class that is listening on these events, for the purpose of sending these events as TCP json messages to a client (player).

But for every important game function I write, I have to write an event and then call

```<code>if(MyEvent != null)
   MyEvent(this, new GameEventArgs("gameover"));
</code>```

I could as easily avoid writing an event for each important action and instead include the listener as an instantiated class and simply send messages that way.

```<code>private GameListener gameListner = new GameListener();

private void GameOver(){
    this.turnTimer.enabled = false;
    this.winner = player; //etc
    gameListener.GameOver(player);
}

class GameListener{
    public void GameOver(Player player){
        JSON json = EncodeJson(GAME_OVER, player);
        SendClientData(json);
    }
}
</code>```

Is there any reason I should stick to events and delegates?


问:
A secondary "type system" for references?
I'm designing a language and was wondering how to incorporate C++-like references with regards to their place in the type system. I think they're useful for operations like indexing and dereferencing (v[i] returns a reference that can be assigned to, *pointer_type returns a reference to an a that behaves like an a).

Nominally in C++, a reference type like int& and its original type int are two distinct types. However, I believe that this is inconsistent with the rest of the type system: an int& can be substituted for int and they sometimes behave as they were the same type, and sometimes they don't, without explicit conversions (which is one of the reasons why references are used in the first place).

My solution would be for bindings and function arguments to essentially have a "secondary type", or rather another qualification with special rules, determining whether they are references or not. There would be two types in this secondary type system: ref and non-ref (default), and these labels would be written in places where other similar labels like const (or mut) would be -- mainly when introducing new bindings or in function types.

Thus, along with classical type mismatch errors, the compiler would report something like mismatched binding mechanism as well. For example this would happen if the programmer attempted to place a function which accepts a single integer by-reference into a list of functions which accept it by-copy (ref a -> b vs. a -> b). Although the functions would have the same type: a -> b, the binding mechanisms are incompatible (because if passed lvalues that are later assigned to, unexpected incompatible behaviour could occur).

Does this solution make sense or is it better to just wrap it in the type system and suffer inconsistencies? Are there some negative side-effects that I'm not anticipating?

To clarify: the touching points between these two type systems would have special rules. For example, there would be implicit conversions from ref to non-ref while keeping the type invariant.

答:
they sometimes behave as they were the same type, and sometimes they
  don't, without explicit conversions (which is one of the reasons why
  references are used in the first place).

No they don't. An int & (basically an int lvalue) can be implicitly converted to an int (an rvalue), but not the other way around.


答:
There are certain things that cannot be considered separately. In other words, there are certain things that are not orthogonal at all.

Firstly, think about how your type system will allow the implementation of pure functions.

A pure function shouldn't care about whether the inputs are values, ref's, or other pure functions that promise to provide the same type of values.

A pure function won't be able to call any non-pure functions. Don't allow any way around this.

Secondly, think about how your type system will provide useful information to your compiler to enable it to deduce the lifetime of objects - to check that it is valid throughout a function call, to borrow it, to extend it outside the current scope, to garbage-collect or reference-count it, or something else. In the case of multithreading, you may also need to track whether there might be concurrent (overlapping) modifications to it.

The C++ type system is the result of taking most of the above into consideration (excluding threading). It is the result of observing what would make sense and what would not. Still, many people can find out and complain about ways in which the safety of C++ type system can be defeated.

Once you have made some decisions about these two aspects, you can think about the type system for the handling of arguments for non-pure functions.

Title: A secondary "type system" for references?

Body:
I'm designing a language and was wondering how to incorporate C++-like references with regards to their place in the type system. I think they're useful for operations like indexing and dereferencing (v[i] returns a reference that can be assigned to, *pointer_type returns a reference to an a that behaves like an a).

Nominally in C++, a reference type like int& and its original type int are two distinct types. However, I believe that this is inconsistent with the rest of the type system: an int& can be substituted for int and they sometimes behave as they were the same type, and sometimes they don't, without explicit conversions (which is one of the reasons why references are used in the first place).

My solution would be for bindings and function arguments to essentially have a "secondary type", or rather another qualification with special rules, determining whether they are references or not. There would be two types in this secondary type system: ref and non-ref (default), and these labels would be written in places where other similar labels like const (or mut) would be -- mainly when introducing new bindings or in function types.

Thus, along with classical type mismatch errors, the compiler would report something like mismatched binding mechanism as well. For example this would happen if the programmer attempted to place a function which accepts a single integer by-reference into a list of functions which accept it by-copy (ref a -> b vs. a -> b). Although the functions would have the same type: a -> b, the binding mechanisms are incompatible (because if passed lvalues that are later assigned to, unexpected incompatible behaviour could occur).

Does this solution make sense or is it better to just wrap it in the type system and suffer inconsistencies? Are there some negative side-effects that I'm not anticipating?

To clarify: the touching points between these two type systems would have special rules. For example, there would be implicit conversions from ref to non-ref while keeping the type invariant.


问:
Do you actually write 'clean code'?
I have seen some programmers tweaking their code over and over again not only to make it 'work good', but also to make it 'look good'.

IMO, 'clean code' is actually a compliment indicating your code is elegant, perfectly understandable and maintainable. And the difference comes out when you have to choose between an aesthetically appealing code vs. code that's stressful to look at.

So, how many of you actually write 'clean code'? Is it a good practice? What are the other benefits or drawbacks of this?

答: I admit to doing that; and the benefit is not getting annoyed every time I see it. I guess it's also easier to read, and therefore bugs become more obvious; but the real reason is that I can't stand ugly code.</p>

Title: Do you actually write 'clean code'?


问:
Simple (hand-drawn) shape recognition
As the input, program would get a set of point (x,y), along with the time a certain point was drawn. (suppose on a tablet).

Let's restrict ourselves to simple polygons.

I implemented Hough transform, in polar coordinates.

Mapping points from (x,y) space to curves (r,fi) space.

```<code>P:(x,y)->(r,y), Re->Re^2
</code>```

Define function F

F: (r,fi)->Re which takes each point in (r,fi) space and returns the number of intersecting curves at that point. Interpret the image of F as a surface in 3space, we construct a set E, containing its "peaks".

Problem: When the input is drawn, because of human error, lines are wavy. This causes scattered "peaks". Even when drawing one line, cases occur, where the maximum element of E, poorly approximates the general direction of the drawn line.

My ways of trying to fix it:

Firstly I tried to smooth out the input before the algorithm gets it.

- Point(i)=(Point(i-1)+Point(i)+Point(i+1))/3 -> by averaging

- I tried smoothing it out by gluing Besier curves, I took all the input points, and then treating each two neighbours as the boundary points of a Besier curve, and calculating the missing two. 2n by 2n system. The problem with this is that I should reduce the points for it to have effect.

-Currently I'm writing a Mean curvature flow implementation, to try to use it for smoothing

Two pictures. Black is Before Red is after

答:
Firstly, please post some images and their corresponding plots from your implementation of Hough transform. Without images and their plots, it is difficult to tell what is going on - especially since there is no source code to critique.

My suspicion is that your understanding of Hough transform may not be correct. When the input is a single point in the (x, y) space (spatial), the resulting Hough transform accumulation should be a sinusoidal graph.

Remember that Hough transform is not merely a coordinate-space transform. It is an integral transform (note that Hough transform and Radon transform are related), therefore the value at a single point in the transformed space depends on an integral that runs on every point in the input (x, y) space.

https://en.wikipedia.org/wiki/Hough_transform

A positive detection of a single line always shows up as a signature "bowtie" shape in the Hough transform space, when rendered as an image where the gray level intensity is proportional to the number of votes received (i.e. the integral). Please refer to the sample plot in the Wikipedia article linked above.

Your attempt to smooth the Hough transform space is on the right track, but the amount of smoothing depends on a lot of factors. It is necessary to make an image plot of the Hough transform plot in order to fine-tune the amount of smoothing needed. It is very likely that the smoothing needs to be performed on a larger window e.g. a Gaussian smooth function with sigma of 5 - 10 pixels is sometimes needed, depending on input characteristics.

You can also compare your implementation's output with that of MATLAB's output or OpenCV's.

Make sure the bins used for Hough Transform accumulation have enough precision to avoid value overflow. Put simply, if the Hough Transform values are stored in "8-bit unsigned integer", it is very likely to overflow. Any other data types should be fine.

Title: Simple (hand-drawn) shape recognition


答: One important thing you can do is to skeletonize or erode your wide lines to get narrow ones. Look at imageJ for some implementations of erode/skeletonize. If you do this, then the amount by which the angle of the line can vary will be reduced. This followed by a mild Gaussian blur can help to make your peaks easier to detect.</p>

Title: Simple (hand-drawn) shape recognition

Body:
As the input, program would get a set of point (x,y), along with the time a certain point was drawn. (suppose on a tablet).

Let's restrict ourselves to simple polygons.

I implemented Hough transform, in polar coordinates.

Mapping points from (x,y) space to curves (r,fi) space.

```<code>P:(x,y)->(r,y), Re->Re^2
</code>```

Define function F

F: (r,fi)->Re which takes each point in (r,fi) space and returns the number of intersecting curves at that point. Interpret the image of F as a surface in 3space, we construct a set E, containing its "peaks".

Problem: When the input is drawn, because of human error, lines are wavy. This causes scattered "peaks". Even when drawing one line, cases occur, where the maximum element of E, poorly approximates the general direction of the drawn line.

My ways of trying to fix it:

Firstly I tried to smooth out the input before the algorithm gets it.

- Point(i)=(Point(i-1)+Point(i)+Point(i+1))/3 -> by averaging

- I tried smoothing it out by gluing Besier curves, I took all the input points, and then treating each two neighbours as the boundary points of a Besier curve, and calculating the missing two. 2n by 2n system. The problem with this is that I should reduce the points for it to have effect.

-Currently I'm writing a Mean curvature flow implementation, to try to use it for smoothing

Two pictures. Black is Before Red is after