问:
Documentation in OOP should avoid specifying whether or not a "getter" performs any computation?
My school's CS program avoids any mention of object oriented programming, so I've been doing some reading on my own to supplement it -- specifically, Object Oriented Software Construction by Bertrand Meyer.

Meyer makes the point repeatedly that classes should hide as much information about their implementation as possible, which makes sense. In particular, he argues repeatedly that attributes (i.e., static, non-computed properties of classes) and routines (properties of classes that correspond to function/procedure calls) should be indistinguishable from each other.

For example, if a class Person has the attribute age, he asserts that it should be impossible to tell, from the notation, whether Person.age corresponds internally to something like return current_year - self.birth_date or simply return self.age, where self.age has been defined as a constant attribute. This makes sense to me. However, he goes on to claim the following:

The standard client documentation for a class, known as the short form of the class, will be devised so as not to reveal whether a given feature is an attribute or a function (in cases for which it could be either).

i.e., he claims that even the documentation for the class should avoid specifying whether or not a "getter" performs any computation.

This, I don't follow. Isn't the documentation the one place where it would be important to inform users of this distinction? If I were to design a database filled with Person objects, wouldn't it be important to know whether or not Person.age is an expensive call, so I could decide whether or not to implement some sort of cache for it? Have I misunderstood what he's saying, or is he just a particularly extreme example of OOP design philosophy?

答:
All these rules about how to hide information in classes make perfect sense on the assumption of needing to protect against that someone among the users of the class who will make the mistake of creating a dependency on the internal implementation.

It's fine to build in such protection, if the class has such an audience.
But when the user writes a call to a function in your class, they are trusting you with their execution-time bank account.

Here's the sort of thing I see a lot:

Objects have a "modified" bit saying if they are, in some sense, out-of-date.
Simple enough, but then they have subordinate objects, so it's straightforward to let "modified" be a function that sums over all the subordinate objects.
Then if there are multiple layers of subordinate objects (sometimes sharing the same object more than once) simple "Get"s of the "modified" property can end up taking a healthy fraction of execution time.

When an object is in some way modified, it is assumed that other objects scattered around the software need to be "notified".
This can take place over multiple layers of data structure, windows, etc. written by different programmers, and sometimes repeating in infinite recursions that need to be guarded against. Even if all the writers of those notification handlers are reasonably careful not to waste time, the entire composite interaction can end up using an unpredicted and painfully large fraction of execution time, and the assumption that it is simply "necessary" is blithely made.

SO, I like to see classes that present a nice clean abstract interface to the outside world, but I do like to have some notion of how they work, if only to understand what work they are saving me. But beyond that, I tend to feel that "less is more". People are so enamored of data structure that they think more is better, and when I do performance tuning the universal massive reason for performance problems is slavish adherence to bloated data structures built the way people are taught.

So go figure.


问:
Will having ClassA extend ClassB slow down my runtime performance compared to having classC which contains all the members of ClassC?
I have a class with a lot of methods. I would like to group similar methods together in their own class, but all of the methods need to extend another class, ClassC. So I was thinking of having ClassA, which contains the first group of methods, extend ClassB, which extends Class_C, etc.

Is this inefficient in terms of runtime performance, or are they virtually the same?

Note: there will be hundreds of instances of this class running at once, so I would really not want to waste memory.

答:
Technically virtual methods will slow a program down because a runtime check is performed to decide which method to use. However you should consider these things before worrying about it:

I have very little info on your classes so if the extending doesn't make the code more readable you shouldn't do it.

All methods must be virtual in java so I would guess they have highly optimized the runtime dispatching of them.

Lastly you won't know how much the program is slowed down until you actually try it, generally worrying about small optimizations before you need to optimize is a bad idea

A couple more things that require some assumption on my part:

"100's" is a very small number in software engineering, you likely won't see any performance slowdown at that few objects

While multiple extension might not slow down your program in general programmers like to save inheritance for is-a relationships, in your situation it might be better to use composition instead of inheritance

ContentLicense: CC BY-SA 3.0


问:
Test driven development when implementing a flexible length list
According to the commonly used TDD strategy, to implement something, you write a test that fail the code first, write the simplest code, refactor, and then repeat. I am trying to imagine this scenario with implementing a flexible length list (e.g. List<T> in .net.

Let's say I first test by inserting one item. Probably the simplest way to achieve this is by backing the list with an array with length 1 (which will pass the test). Nothing to refactor here, so I'll go ahead and write another test that insert 2 items. I'll simply change the array length to 2, and the test pass again. Then I write test with 3 items, expand the array, and repeat again. I will end up forever doing this until I'm tired.

Is this an exception to the fail-test-first strategy? Or am I missing something in the above strategy?

PS: The actual implementation backs the list with an array which grows twice as large every time the number of elements exceed the array length.

答:
If flexible length matters, the best way I can think is to write a general test as function with argument the number of entries.
Then the nature of your problem should tell you which numbers are important to test for. Good candidates are numbers 0 and 1.
In general, you want to test what Robert Martin calls "Boundary conditions" in his great book "Clean Code", described as:

Boundary is what separates the known from the unknown

The other side of the boundary in your case would be a large number entries, say the largest you can expect, to see that your system can cope with it.


问:
Why is Python written in C and not in C++?
In Python's tutorial one can read that Python's original implementation is in C;

On the other hand, the Python implementation, written in C, (...)

I'm very curious why was Python written in C and not C++?

I'd like to know the reasoning behind this decision and the answer should be supported by historical references (and not opinion based).

答:
From everything I've seen, it's a combination of practical and historical reasons. The (mostly) historical reason is that CPython 1.0 was released in 1989. At that time, C was just recently standardized. C++ was almost unknown and decidedly non-portable, because almost nobody had a C++ compiler.

Although C++ is much more widespread and easily available today, it would still take a fair amount of work to rewrite CPython into the subset of C that's compatible with C++. By itself, that work would provide little or no real benefit.

It's a bit like Joel's blog post about starting over and doing a complete rewrite being the worst mistake a software company can make. I'd counter that by pointing to Microsoft's conversion from the Windows 3.0 core to the Windows NT core, and Apple's conversion from MacOS 9 to Mac OS/X. Neither one killed the company -- but both were definitely large, expensive, long-term projects. Both also point to something that's crucial to success: maintaining both code bases for long enough that (most) users can switch to the new code base at their leisure, based on (at least perceived) benefits.

For a development team the size of Python's, however, that kind of change is much more difficult. Even the change from Python 2 to 3 has taken quite a bit of work, and required a similar overlap. At least in that case, however, there are direct benefits to the changes, which rewriting into C++ (by itself) wouldn't (at least immediately) provide.

Linus Torvalds's rant against C++ was brought up, so I'll mention that as well. Nothing I've seen from Guido indicates that he has that sort of strong, negative feelings toward C++. About the worst I've seen him say is that teaching C++ is often a disaster -- but he immediately went on to say that this is largely because the teachers didn't/don't know C++.

I also think that while it's possible to convert a lot of C code to C++ with relative ease, that getting much real advantage from C++ requires not only quite a bit more rewriting than that, but also requires substantial re-education of most developers involved. Most well-written C++ is substantially different from well-written C to do the same things. It's not just a matter of changing malloc to new and printf to cout, by any stretch of the imagination.

ContentLicense: CC BY-SA 4.0


问:
Can a daily scrum meeting be replaced by a status email?
If an agile team has members like Developers, Testers, and Automation Testers from different geographical regions, how can the daily scrum meeting can happen?
Obviously they have to work in different time zones. Can this be successfully managed? Do you think the daily scrum meeting can be replaced by sending status emails at the end of day, or by answering the three Scrum questions in an email?</p>

答:
While not ideal, you can make it work. The difficulty depends on how many time zones and how flexible the work day is for each of the locations. In the USA, most often it is done by holding the daily Scrum as early as possible for workers in the US and having overseas (Europe, western Asia) folks work a workday that is shifted slightly later, where they attend at the end of their workday. It is most challenging when the time difference is around 12 hours. For work in Australia and the US, the reverse is true.

Alternatively, I've also worked where there are a few representatives from the remote group involved in the Scrum, instead of everyone. This is less ideal but can still work pretty well, when supplemented by additional means of communication and good process and requirements gathering / communication (such as very good acceptance criteria definitions).

It's generally about the quality of the team members. Face-to-face is great, but you can make the remote work with smart people with good communication skills and positive attitudes.


答: In my experience nothing beats a meeting face to face - even if it's over a video conference link. In my current project, we have developers and Scrum team members all over the UK and we conference call in for a daily scrum. it works relatively well. I don't think emails status works as well because Scrum is supposed to be an arena for back and forth interaction. Save email status reports for project management updates. In projects where emails were the main focus for clearing issues, the delays became longer, people 'missed' emails, and eventually it slowed the project to a crawl.</p>

Title: Can a daily scrum meeting be replaced by a status email?

Body:
If an agile team has members like Developers, Testers, and Automation Testers from different geographical regions, how can the daily scrum meeting can happen?
Obviously they have to work in different time zones. Can this be successfully managed? Do you think the daily scrum meeting can be replaced by sending status emails at the end of day, or by answering the three Scrum questions in an email?</p>


答:
TL;DR

Testing is more of an art than a science. How to construct a test is actually less important than knowing what's useful to test.

Test Behavior

Test behavior, not implementation details. What behavior are you actually trying to test? In all likelihood, your feature needs to do just two things: create a list, and extract data from the list.

From a pragmatic point of view, it doesn't really matter how your list is implemented. What you really want to know is whether your inputs result in some expected output. For example:

List Creation

Given data elements x, y, and z

When I call the create method with those elements

Then the method returns a list that matches my fixture object.

List Extraction

Given a list containing 50 fixture elements

When I look at the 43rd element

Then I should find my expected value.

In most cases, non-functional requirements can be described in behavioral terms, too.

Test Boundary Conditions

It's not generally useful to test infinity, or to exhaustively test every possible input or intermediate value in a system. On the other hand, it is often useful to think about boundary conditions like:

A list with no data elements.

A list with a very small number of data elements.

A list with a very large number of data elements.

A test is really a hypothesis that you're validating, so it's fine to make documented assumptions. If you're unlikely to ever have more than 500 elements in your list, then you might define boundaries at elements 499, 500, and 501 that are worth testing; however, there's almost no value in explicitly testing 13,756 elements in this scenario because it's already covered by your boundary tests.

Title: Test driven development when implementing a flexible length list

Body:
According to the commonly used TDD strategy, to implement something, you write a test that fail the code first, write the simplest code, refactor, and then repeat. I am trying to imagine this scenario with implementing a flexible length list (e.g. List<T> in .net.

Let's say I first test by inserting one item. Probably the simplest way to achieve this is by backing the list with an array with length 1 (which will pass the test). Nothing to refactor here, so I'll go ahead and write another test that insert 2 items. I'll simply change the array length to 2, and the test pass again. Then I write test with 3 items, expand the array, and repeat again. I will end up forever doing this until I'm tired.

Is this an exception to the fail-test-first strategy? Or am I missing something in the above strategy?

PS: The actual implementation backs the list with an array which grows twice as large every time the number of elements exceed the array length.


答:
"I'll go ahead and write another test that insert 2 items. (…) Then I write test with 3 items, expand the array, and repeat again. I will end up forever doing this until I'm tired."

The problem here is not that your implementation of List<T> is flawed, but that your unit tests are specifying the wrong kind of implementation.

If you consider these unit tests a specification for your List<T> implementation, then you have just specified something like the following:

Can insert 1 item into the empty list, after which it will contain 1 item.

Can insert 2 items into the empty list, after which it will contain 2 items.

Can insert 3 items into the empty list, after which it will contain 3 items.

etc.

And once your tests pass, your list will be able to fulfill exactly that specification. But is this really what you want?

Or would you perhaps prefer a more general specification, such as the following?:

Can insert 1 item into the empty list, after which it will contain 1 item.

Can insert 1 item into a list with n items, after which it will contain n+1 items.

If so, write different unit tests that encode that specification instead (and you will find that you no longer need infinitely many tests, but that you're actually done after two).


答:
Purpose of the Stand-Up

You're misunderstanding the purpose and intent of Scrum's daily stand-up. It's a task synchronization and coordination meeting between members of the development team, which requires n-way communications between team members in real time. You can't replace this with a daily email update and still expect to the team to remain agile.

Face-to-Face Isn't a Scrum Requirement

On the other hand, there's no actual framework requirement that everyone be in the same room, or even the same time zone. The underlying agile principle says:

The most efficient and effective method of conveying information to and within a development team is face-to-face conversation.

While in-person meetings provide the most communications bandwidth, it is still perfectly legitimate to substitute the most effective means of communication at the team's disposal. A video conference still provides plenty of opportunities for visual communication, and even a live teleconference allows for more socially-nuanced communication than online chats or emails.


答:
Adding implementation details like "calculate or not" or "performance info" make it more difficuilt to keep code and doc in sync.

Example:

If you have an "performance-expensive" method do you want to document "expensive" also to all classes that use the method? what if you change the implementation to be not expensive any more. Do you want to update this info to all consumers, too?

Of course it is nice for a code maintainer to get all important infos from the code documentation, but i donot like documentation that claims something that is not valid anymore (out of sync with the code)

Title: Documentation in OOP should avoid specifying whether or not a "getter" performs any computation?

Body:
My school's CS program avoids any mention of object oriented programming, so I've been doing some reading on my own to supplement it -- specifically, Object Oriented Software Construction by Bertrand Meyer.

Meyer makes the point repeatedly that classes should hide as much information about their implementation as possible, which makes sense. In particular, he argues repeatedly that attributes (i.e., static, non-computed properties of classes) and routines (properties of classes that correspond to function/procedure calls) should be indistinguishable from each other.

For example, if a class Person has the attribute age, he asserts that it should be impossible to tell, from the notation, whether Person.age corresponds internally to something like return current_year - self.birth_date or simply return self.age, where self.age has been defined as a constant attribute. This makes sense to me. However, he goes on to claim the following:

The standard client documentation for a class, known as the short form of the class, will be devised so as not to reveal whether a given feature is an attribute or a function (in cases for which it could be either).

i.e., he claims that even the documentation for the class should avoid specifying whether or not a "getter" performs any computation.

This, I don't follow. Isn't the documentation the one place where it would be important to inform users of this distinction? If I were to design a database filled with Person objects, wouldn't it be important to know whether or not Person.age is an expensive call, so I could decide whether or not to implement some sort of cache for it? Have I misunderstood what he's saying, or is he just a particularly extreme example of OOP design philosophy?


问:
What justifies the use of an IDE versus a standard editor?
I find myself using my text editor of choice (vim, nano, gedit, pick your poison) much more often than any IDE as of late.

After noticing my ide shortcuts getting dusty I started to think about this and wonder: what justifies use of an IDE for you opposed to a text editor?

For that matter what rationale would you have for not using an IDE and merely relying on an editor?

答:
```<code>[To the IDE] You had me at intellisense/autocomplete
</code>```

ContentLicense: CC BY-SA 2.5


问:
ado.net or EF for a point-of-sale system
We have a point-of-sale system that was developed using ado.net, our current concern is to make the application real fast in creating transactions (sales). Usually there are no performance concerns with high end PCs but with with low end PCs, the transactions take really slow.

The main concern is on saving transactions which usually calls a lot of stored procedures for inserting records within a single transaction. This usually takes time on low end PCs. We need to improve the performance since most clients will only use low end PCs to act as cashier machines. One solution we are thinking is to use entity framework for data access. The entire project is written using ado.net and development time if we shift to entity framework would be alot. Any suggestions?

答:
How necessary is it that each transaction require a database call?

At what point is the db insertion being performed? Is there one call per transaction or is it inserting with every addition to the order causing a major lag throughout the user's interaction?

Can the db call be handled through private HTTP requests to a dedicated server on the client's own LAN?

Perhaps a better approach would be to save the transactions in a repository and post them to the server all at once using the Unit of Work pattern that is triggered as soon as there is a pause of more than 5 seconds. Or perhaps the slow client machines could post to a service that can handle the database insertions.

What else could be slowing the machine? Is the GUI processor intensive? It's a POS, not a graphic designer's portfolio piece.


问:
collection naming - singular or plural
This is related to this question but not quite the same. BTW, I'm not a native English speaker.

I keep having a hard time choosing a proper name for collections - Lets say that we have a collection of item s and that each item has a name. How will we call the collection of names such that the collection's name will be the most understandable under standard naming conventions?

```<code>var itemNames = GetItemNames(); // Might be interpreted as a single item with many names
var itemsNames = GetItemsNames(); // No ambiguity but doesn't look like proper English
var itemsName = GetItemsName(); // Also sounds strange, and doesn't seem to fit in e.g. a loop:
foreach( itemName in itemsName){...}
</code>```

As native English speakers, how would you name your collections, and how would you expect them to be named?

答:
What about GetNamesOfItems?

Otherwise, GetItemNames can be a good alternative, if the documentation is clear about what is being returned. This also depends on the items itself:

GetPersonNames is not clear, since a person can have multiple names,

GetProductNames is more explicit in a context where a product can have one and one only name.

GetItemsNames looks indeed quite strange.

GetItemsName is simply incorrect: we expect as a result a common name shared by multiple items, not a sequence of names.

As an example, take a method which returns the prices of products in a category:

```<code>public Money[] NameHere(CategoryId categoryId) { ... }
</code>```

GetProductPrices could have been interpreted in two ways: either it returns the prices of products, or several prices of a product, one price per currency. In practice, given that the parameter of the method is a category, and not a single product, it is obvious that the first alternative is true.

GetPricesOfProducts appears the most clear alternative. There are zero or more products in a category, and for each, we return its price. The only issue is the case when there are actually several prices per product, one price per currency.

GetProductsPrices looks strange, but is still clear.

GetProductsPrice looks totally wrong: we expect such method to return Money, not Money[].

Also note that in the example above, it may be even better to slightly change the signature itself:

```<code>public Tuple(ProductId, Money)[] GetPricesOfProducts(CategoryId categoryId) { ... }
</code>```

appears easier to understand and removes the ambiguity described in the second point.

Title: collection naming - singular or plural

Body:
What about GetNamesOfItems?

Otherwise, GetItemNames can be a good alternative, if the documentation is clear about what is being returned. This also depends on the items itself:

GetPersonNames is not clear, since a person can have multiple names,

GetProductNames is more explicit in a context where a product can have one and one only name.

GetItemsNames looks indeed quite strange.

GetItemsName is simply incorrect: we expect as a result a common name shared by multiple items, not a sequence of names.

As an example, take a method which returns the prices of products in a category:

public Money[] NameHere(CategoryId categoryId) { ... }

GetProductPrices could have been interpreted in two ways: either it returns the prices of products, or several prices of a product, one price per currency. In practice, given that the parameter of the method is a category, and not a single product, it is obvious that the first alternative is true.

GetPricesOfProducts appears the most clear alternative. There are zero or more products in a category, and for each, we return its price. The only issue is the case when there are actually several prices per product, one price per currency.

GetProductsPrices looks strange, but is still clear.

GetProductsPrice looks totally wrong: we expect such method to return Money, not Money[].

Also note that in the example above, it may be even better to slightly change the signature itself:

public Tuple(ProductId, Money)[] GetPricesOfProducts(CategoryId categoryId) { ... }

appears easier to understand and removes the ambiguity described in the second point.


答: In English, this would be "get the items' names". If you want to think of an "item name" as an independent thing, then "get the item names" would also be acceptable. Here I would have used GetItemNames() without a second thought, so I would recommend either that or GetNames(items) or items.GetNames().

Title: collection naming - singular or plural

Body:
This is related to this question but not quite the same. BTW, I'm not a native English speaker.

I keep having a hard time choosing a proper name for collections - Lets say that we have a collection of item s and that each item has a name. How will we call the collection of names such that the collection's name will be the most understandable under standard naming conventions?

```<code>var itemNames = GetItemNames(); // Might be interpreted as a single item with many names
var itemsNames = GetItemsNames(); // No ambiguity but doesn't look like proper English
var itemsName = GetItemsName(); // Also sounds strange, and doesn't seem to fit in e.g. a loop:
foreach( itemName in itemsName){...}
</code>```

As native English speakers, how would you name your collections, and how would you expect them to be named?


问:
Is OOP hard because it is not natural?
One can often hear that OOP naturally corresponds to the way people think about the world. But I would strongly disagree with this statement: We (or at least I) conceptualize the world in terms of relationships between things we encounter, but the focus of OOP is designing individual classes and their hierarchies.

Note that, in everyday life, relationships and actions exist mostly between objects that would have been instances of unrelated classes in OOP. Examples of such relationships are: "my screen is on top of the table"; "I (a human being) am sitting on a chair"; "a car is on the road"; "I am typing on the keyboard"; "the coffee machine boils water", "the text is shown in the terminal window."

We think in terms of bivalent (sometimes trivalent, as, for example in, "I gave you flowers") verbs where the verb is the action (relation) that operates on two objects to produce some result/action. The focus is on action, and the two (or three) [grammatical] objects have equal importance.

Contrast that with OOP where you first have to find one object (noun) and tell it to perform some action on another object. The way of thinking is shifted from actions/verbs operating on nouns to nouns operating on nouns -- it is as if everything is being said in passive or reflexive voice, e.g., "the text is being shown by the terminal window". Or maybe "the text draws itself on the terminal window".

Not only is the focus shifted to nouns, but one of the nouns (let's call it grammatical subject) is given higher "importance" than the other (grammatical object). Thus one must decide whether one will say terminalWindow.show(someText) or someText.show(terminalWindow). But why burden people with such trivial decisions with no operational consequences when one really means show(terminalWindow, someText)? [Consequences are operationally insignificant -- in both cases the text is shown on the terminal window -- but can be very serious in the design of class hierarchies and a "wrong" choice can lead to convoluted and hard to maintain code.]

I would therefore argue that the mainstream way of doing OOP (class-based, single-dispatch) is hard because it IS UNNATURAL and does not correspond to how humans think about the world. Generic methods from CLOS are closer to my way of thinking, but, alas, this is not widespread approach.

Given these problems, how/why did it happen that the currently mainstream way of doing OOP became so popular? And what, if anything, can be done to dethrone it?

答:
One can often hear that OOP naturally corresponds to the way people
  think about the world. But I would strongly disagree with this
  statement (...)

As it is evangelized in books and elsewhere for decades, I disagree with it too. Nevertheless, I think Nygaard and Dahl were the ones that put it that way, and I think they were focusing on how easier it was to think about designing simulations compared with the alternatives of the time.

(...) but the focus of OOP is designing
  individual classes and their hierarchies.

This assertion enters sensible territory given how popular misconceptions of OOP are, and how sensitive OO is to definition. I have more than ten years in the field, doing both industry work and academic research on prog. languages, and I can tell you I spent many years unlearning "mainstream OO" because I started noticing how different (and inferior) it is from what the earlier creators were aiming at. For a modern, up to date treatment of the subject I would refer to W. Cook's recent effort:

"A Proposal for Simplified, Modern Definitions of "Object" and "Object Oriented"
http://wcook.blogspot.com.br/2012/07/proposal-for-simplified-modern.html

Given these problems, how/why did it happen that the currently
  mainstream way of doing OOP became so popular?

Maybe the same reason QWERTY keyboards came to be popular or the same reason DOS operating system became popular. Things just get a ride on popular vehicles, despite their properties, and become popular themselves. And sometimes, similar but worse versions of something are taken to be the actual thing.

And what, if anything, can be done to dethrone it?

Write a program using a superior approach. Write the same program using an OO approach. Show the former has better properties than the latter in every aspect that is significant (both properties of the system itself and engineering properties). Show that the program chosen is relevant and the proposed approach sustains the high quality of properties if applied to other kinds of programs. Be rigorous in your analysis and use precise and accepted definitions when necessary.

Finally, share your findings with us.

Title: Is OOP hard because it is not natural?


问:
Is there any way to detect on a website if the mouse has not been moved for awhile?
I want an element to appear in case the website has not been used for a while and make it disappear after it is being used again. Is there any way to detect on a website if the mouse has not been moved for awhile?</p>

答:
Put an event handler that takes mouse position whenever mouse is moved store it in variable and store the exact time that happened.

Make a timer that runs each lets say each minute and checks if the last stored mouse position and time is older than a minute then make that element you want to appear
else make sure the hide that element.


问:
How does Mercurial determine which changesets I need when I pull?
This is a question about the internal workings of Mercurial.

I vaguely remember a fellow programmer explaining to me how mercurial works out which changesets differ between two repositories and that it had a speedy solution to the problem.

Does anyone know how this works or can point me towards a document describing the details?

答:
Algorithm works in the following way. You have two repository: local and remote. They both contains a DAG of changelists.

The goal of the discovery protocol is to find one set of node common, the set of nodes shared by local and remote.

One of the issue with the original protocol was latency, it could potentially require lots of roundtrips to discover that the local repo was a subset of remote (which is a very common case, you usually have few changes compared to upstream, while upstream probably had lots of development).

The new protocol only requires one interface for the remote repo: known(), which given a set of changelists tells you if they are present in the DAG.

The algorithm then works as follow:

We will be using three sets, common, missing, unknown. Originally all nodes are in unknown.

Take a sample from unknown, call remote.known(sample)

For each node that remote knows, move it and all its ancestors to common

For each node that remote doesn't know, move it and all its descendants to missing

Iterate until unknown is empty

There are a couple optimizations, first is instead of starting with a random sample of missing, start by sending all heads, in the case where the local repo is a subset, you computed the answer in one round trip.

Then you can do something similar to the bisecting strategy used when finding faulty changesets. Instead of random samples, you can try picking nodes that will maximize the number of nodes that will be classified with it (since all ancestors or descendants will be marked as well).

The end result worked pretty well.

The code is pretty readable if you're curious: http://selenic.com/hg/file/tip/mercurial/setdiscovery.py


问:
ASP.Net or WPF(C#)?
Our team is divided on this and I wanted to get some third-party opinions.

We are building an application and cannot decide if we want to use .Net WPF Desktop Application with a WCF server, or ASP.Net web app using jQuery. I thought I'd ask the question here, with some specs, and see what the pros/cons of using either side would be. I have my own favorite and feel I am biased.

Ideally we want to build the initial release of the software as fast as we can, then slow down and take time to build in the additional features/components we want later on. Above all we want the software to be fast. Users go through records all day long and delays in loading records or refreshing screens kills their productivity.

Application Details:

I'm estimating around 100 different screens for initial version, with plans for a lot of additional screens being added on later after the initial release.

We are looking to use two-way communication for reminder and event systems

Currently has to support around 100 users, although we've been told to allow for growth up to 500 users

We have multiple locations

Items to consider (maybe not initially in some cases but in future releases):

Room for additional components to be added after initial release (there are a lot of of these... perhaps work here than the initial application)

Keyboard navigation

Performance is a must

Production Speed to initial version

Low maintenance overhead

Future support

Softphone/Scanner integration

Our Developers:

We have 1 programmer who has been learning WPF the past few months and was the one who suggested we use WPF for this.

We have a 2nd programmer who is familiar with ASP.Net and who may help with the project in the future, although he will not be working on it much up until the initial release since his time is spent maintaining our current software.

There is me, who has worked with both and am comfortable in either

We have an outside company doing the project management, and they are an ASP.Net company.

We plan on hiring 1-2 others, however we need to know what direction we are going in first

Environment:

General users are on Windows 2003 server with Terminal Services. They connect using WYSE thin-clients over an RDP connection. Admin staff has their own PCs with XP or higher. Users are allowed to specify their own resolution although they are limited to using IE as the web browser.

Other locations connects to our network over a MPLS connection

Based on that, what would you choose and why?

答:
Interesting. That sounds strikingly familiar to an app that we've just started at my company (sip phone and scanner integration and all).

We chose silverlight with a focus on SOA so that a WPF app could be made afterward if the need arises.

Room for additional components to be added after initial release (there are a lot of of these... perhaps work here than the initial application)

We're using MEF in the service layer, and constructing extension points (plugin interfaces describing certain points where we plan extensibility or integration with other systems)

Keyboard navigation

Not a problem.

Performance is a must

What kind of performance? Perceived performance (snappy-ness) or number crunching performance? The latter could be a problem with a web/silverlight app. For the former, our app goes through lots of records, like yours, but we are able to predict them and pre-fetch records while the users are working on current ones. 'Load' times are zero for that section of our app.

Production Speed to initial version

Depends on the skillset. But realistically, everyone always wants to get to market as fast as possible, so it's a non-argument.

Low maintenance overhead

Like production speed, it's also a non argument and it's going to come down to design and coding practices. If you are speaking in terms of hardware maintenance, you might want to go with a cloud app.

Future support

I'm not sure what that means.

Softphone/Scanner integration

Silverlight 4 allows webcam/mic access now (we're hoping to do inter-application video conferencing as well as sip integration), so if you are using a phone server, you can write one yourself. I don't know of any existing ones, but this might help.

Otherwise, you might have to do some ugly hacking (don't have a reference to the article/s anymore, sorry) or you have no choice but to have a WPF app that can interact with the file system. SL4 can go out-of-browser, but it can only access certain parts of the file-system. None of them are likely going to be the parts that you need to interact with a sip phone.

Do you mean, document scanner? I'm not sure about that. We're using hand/barcode scanners, and they operate just like any other input device and are a non-issue.

Title: ASP.Net or WPF(C#)?


问:
Python dynamic attributes creation, a blessing or a curse?
Consider this code:

```<code>>>> class Foo():
        pass
...
>>> foo = Foo()
>>> foo.a = 'test'
>>> foo.a
'test'
</code>```

One can just override __setattr__ to make attributes read only and prevent their creation at runtime, however:

Why is this the default Python behavior (any good reasons)?

Is there any practice to prevent this without altering each class?

Would you worry about this behavior in serious projects? don't you consider it error prone? or you can just ignore it (relying on new IDEs code completion)

答:
As others already mentioned, preventing this would require a special case for __init__, and one of the design principles of Python is to avoid special cases, see the Zen of Python:

Special cases aren't special enough to break the rules.

This design is also in line with other design decisions, e.g, the lack of static type checking or access control modifiers. Python tends to empower its users, not to enforce things.

You can easily prevent this for any particular class by using __slots__. However, there is no way to change this globally.

While this can in theory cause errors, I wouldn't worry about it much. For example, a typo could mean that you are by accident create a new attribute when you meant to assign to an existing attribute. However, good unit testing coverage will usually catch this.


问:
Display error message with jQuery without reloading page
I created login form. When user clicks on login button this form shows up with some fade effect (jQuery). What I want to do is to display error message in this form when user inputs invalid data. Before showing any messages, PHP must read data from database, therefore page must be reloaded and when page is reloaded this form fade away. How can I display error message in this login form without reloading page?

(I have lots of code so if you need any part of code I will provide)

答:
Here's my login jQuery/AJAX proccess script.
You just need to create a few divs/spans in your form for error message and loading and to make this work, in your login PHP script you must add if login is correct echo'1'; or whatever is your success echo in your PHP script change that in this part of jQuery code

```<code>if(result === '1' ) {  // This is PHP success echo, in my case is number 1

  window.location='index.php';  // Uppon successfull login in my case redirects to index.php
}
</code>```

```<code>$(function() {

  $( '.login' ).submit(function(e) { // My form has class login, dont forget to change this to your form class or id

    e.preventDefault();

    var error   = 0;

    var lForm   = $( this ),
        lName   = $( '.login input[name="login"]' ).val(),
        lPass   = $( '.login input[name="password"]' ).val(),
        errMsg  = $( '.login-err' ); // Create div or span with class login-err or whatever class you wish

    if ( lName == 'Username' ) {  // Username in this case is default value
      error = 1;
      errMsg.html( '<p>Enter User Name and Password.</p>' ); //Here insted .html you could use .text
    }

    if ( lName.length > 32 || lName.length < 3 ) {
      error = 1;
      errMsg.html( '<p>Name must be between 3-32 characters.</p>' );
    }

    if ( lPass == 'Password' ) {  // Password in this case is default value
      error = 1;
      errMsg.html( '<p>Enter User Name and Password.</p>' );
    }

    if ( error ) {
      errMsg
        .fadeIn( 'slow' )
        .delay( 1800 )
        .fadeOut( 'slow' );

        return false;
    }
    else {

      $( this ).fadeOut(function() {

        $( '.loading' ).fadeIn(function() { // For this create div or span with class "loading" or whatever class you wish and put some pretty loader gif in it

          $.ajax({
            type: 'POST',
            url: lForm.attr( 'action' ),
            data: lForm.serialize(),
            success: function(result) {

              if(result === '1' ) {
                window.location='index.php';
              }
              else {

                $( '.loading' ).fadeOut(function() {

                  lForm.fadeOut( 'slow' );

                   errMsg
                     .fadeIn( 'slow' )
                     .delay( 1800 )
                     .fadeOut( 'slow' )
                     .html( '<p>Incorrect User Name or Password.</p>' );

                   lForm.delay( 2400 ).fadeIn( 'slow' );

                 });
                }
              }
            });
          });
        });
      }
    });

});
</code>```

Body:
Here's my login jQuery/AJAX proccess script.
You just need to create a few divs/spans in your form for error message and loading and to make this work, in your login PHP script you must add if login is correct echo'1'; or whatever is your success echo in your PHP script change that in this part of jQuery code

if(result === '1' ) {  // This is PHP success echo, in my case is number 1

  window.location='index.php';  // Uppon successfull login in my case redirects to index.php
}

$(function() {

  $( '.login' ).submit(function(e) { // My form has class login, dont forget to change this to your form class or id

    e.preventDefault();

    var error   = 0;

    var lForm   = $( this ),
        lName   = $( '.login input[name="login"]' ).val(),
        lPass   = $( '.login input[name="password"]' ).val(),
        errMsg  = $( '.login-err' ); // Create div or span with class login-err or whatever class you wish

    if ( lName == 'Username' ) {  // Username in this case is default value
      error = 1;
      errMsg.html( '<p>Enter User Name and Password.</p>' ); //Here insted .html you could use .text
    }

    if ( lName.length > 32 || lName.length < 3 ) {
      error = 1;
      errMsg.html( '<p>Name must be between 3-32 characters.</p>' );
    }

    if ( lPass == 'Password' ) {  // Password in this case is default value
      error = 1;
      errMsg.html( '<p>Enter User Name and Password.</p>' );
    }

    if ( error ) {
      errMsg
        .fadeIn( 'slow' )
        .delay( 1800 )
        .fadeOut( 'slow' );

        return false;
    }
    else {

      $( this ).fadeOut(function() {

        $( '.loading' ).fadeIn(function() { // For this create div or span with class "loading" or whatever class you wish and put some pretty loader gif in it

          $.ajax({
            type: 'POST',
            url: lForm.attr( 'action' ),
            data: lForm.serialize(),
            success: function(result) {

              if(result === '1' ) {
                window.location='index.php';
              }
              else {

                $( '.loading' ).fadeOut(function() {

                  lForm.fadeOut( 'slow' );

                   errMsg
                     .fadeIn( 'slow' )
                     .delay( 1800 )
                     .fadeOut( 'slow' )
                     .html( '<p>Incorrect User Name or Password.</p>' );

                   lForm.delay( 2400 ).fadeIn( 'slow' );

                 });
                }
              }
            });
          });
        });
      }
    });

});


答:
You can set up a timer that expires after the desired amount of time of mouse inactivity, and reinitialize it whenever the mouse is moved.

See this question for an example (clearTimeout followed by setTimeout).

Body: I want an element to appear in case the website has not been used for a while and make it disappear after it is being used again. Is there any way to detect on a website if the mouse has not been moved for awhile?</p>


问:
More Accurate Random in C
I have 3 IPs and every IP has a weight, I want to return the IP's according to its weights using the random function. For example if we have 3 IP's

X with weight 3

Y with weight 3

and Z with weight 3

I want to return X in 33.3% of cases and Y in 33.3% of cases and Z in 33.3% of cases, depending on random function in C.

I have tried this code :

```<code>double r = rand() / (double)RAND_MAX;
double denom = 3 + 3 + 3;
if (r < 3 / denom) {
// choose X
} else if (r < (3 + 3) / denom) {
// choose Y
} else {
// choose Z
}
</code>```

I repeat the function 1000 and I get: Choose x 495 times and Choose y 189 times and choose z 316 times. But what I want is to get X:333  y:333  Z:334 How can the weighted random be more accurate?

答:
I would usually do something like this:

```<code>int r = rand();
if (r % 3 == 0) {
// choose X
} else if (r % 3 == 1) {
// choose Y
} else {
// choose Z
}
</code>```

It's probably not perfect (I think RAND_MAX might give a Y instead of Z or something like that), but if the random number generator works properly, you'd expect to see a good distribution of X, Y and Z. The expected deviance from a uniform distribution would be less than the sample size you're using now.

Title: More Accurate Random in C

Body:
I would usually do something like this:

int r = rand();
if (r % 3 == 0) {
// choose X
} else if (r % 3 == 1) {
// choose Y
} else {
// choose Z
}

It's probably not perfect (I think RAND_MAX might give a Y instead of Z or something like that), but if the random number generator works properly, you'd expect to see a good distribution of X, Y and Z. The expected deviance from a uniform distribution would be less than the sample size you're using now.


答:
(This part of the question was associated with revision 2 and is still quite applicable to that problem)

The standard approach to doing this is to populate an array with the appropriate weights:

```<code>[x, x, x, x, x, x, y, y, y, y, z, z]
 1  2  3  4  5  6  1  2  3  4  1  2
</code>```

and then pick one at random.

Please note that random is random.  It is very unlikely that you will ever a perfect distribution.

If you want to guarantee the distribution, you need to do (mostly) away with the random.

Instead, shuffle the above array.  For example, one shuffling would give you:

```<code>[x, y, z, y, x, x, y, x, z, y, x, x]
</code>```

And then loop over the array again and again returning the current index.  It isn't random anymore, but it will guarantee the distribution remains what you are looking for always.  This is just a slightly more 'random' version of a round robin distribution.

If this is attempting to load balance something, the round robin is a better approach and you might want to consider a evenly distributed round robin:

```<code>[x, y, x, y, x, z]
</code>```

This has the same distribution as above and tries to keep everything at an even distance so not as to saturate any one resource.

As an aside, to the question of rand being poor, you may be dealing with an older standard library.  From rand3 man page

The versions of rand() and srand() in the Linux C Library use the
same random number generator as random(3) and srandom(3), so the
lower-order bits should be as random as the higher-order bits.
However, on older rand() implementations, and on current
implementations on different systems, the lower-order bits are much
less random than the higher-order bits.  Do not use this function in
applications intended to be portable when good randomness is needed.
(Use random(3) instead.)
```

<p>This can be demonstrated using the following C program that spits out the consecutive low byte and low nybbles from <code>rand()</code>.  I happen to have a more modern system and don't have access to anything that might demonstrate this low order less randomness.</p>

<p>You can test it on your system with the following code which looks at the low byte, low 4 bits, and low 2 bits.</p>

```#include <stdlib.h>
#include <stdio.h>

int main (int argc, char** argv) {
    int i, r;
    int a8, a4, a2;

    srand(0);
    FILE *fp0xff = fopen("low8.out", "w");
    FILE *fp0x0f = fopen("low4.out", "w");
    FILE *fp0x03 = fopen("low2.out", "w");
    for(i = 0; i < 10000; i++) {
        /* 1 of 4 */
        r = rand();
        a8 = r & 0xff;
        a4 = r & 0x0f;
        a2 = r & 0x03;

        fprintf(fp0xff, "%c",a8);

        /* 2 of 4 */
        r = rand();
        a8 = r & 0xff;
        a4 = (a4 << 4) | (r & 0x0f);
        a2 = (a2 << 2) | (r & 0x03);

        fprintf(fp0xff, "%c",a8);
        fprintf(fp0x0f, "%c",a4);

        /* 3 of 4 */
        r = rand();
        a8 = r & 0xff;
        a4 = r & 0x0f;
        a2 = (a2 << 2) | (r & 0x03);

        fprintf(fp0xff, "%c",a8);

        /* 4 of 4 */
        r = rand();
        a8 = r & 0xff;
        a4 = (a4 << 4) | (r & 0x0f);
        a2 = (a2 << 2) | (r & 0x03);

        fprintf(fp0xff, "%c",a8);
        fprintf(fp0x0f, "%c",a4);
        fprintf(fp0x03, "%c",a2);
    }
    fclose(fp0xff);
    fclose(fp0x0f);
    return 0;
}
```

<p>The output of this program can then be examined using ent which runs a number of tests of randomness against a stream of bytes.</p>

<p>Running this against the low2.out <em>on my system</em> produces:</p>

<blockquote>
  <p>Entropy = 7.982762 bits per byte.</p>

  <p>Optimum compression would reduce the size <br />
  of this 10000 byte file by 0 percent.</p>

  <p>Chi square distribution for 10000 samples is 240.46, and randomly <br />
  would exceed this value 73.46 percent of the times.</p>

  <p>Arithmetic mean value of data bytes is 127.6318 (127.5 = random). <br />
  Monte Carlo value for Pi is 3.150060024 (error 0.27 percent).  <br />
  Serial correlation coefficient is -0.002842 (totally uncorrelated = 0.0).</p>
</blockquote>

<p>Which is frankly, a reasonably good random stream.</p>

<p>The reason I am testing the low two bytes is that you are doing things with <code>% 9</code> which works only with these low bits.  You may find that your random number generator is old and might need to implement your own (if that degree of randomness is something that you need to work with).</p>

<p>One approach would be, well, to implement your own.  The Mersenne twister is quite well regarded and you can find implementations for a wide range of languages quite easily.</p>

<p>The other thing to do would be to shift the random number you get down 8 bits to get rid of any low order less randomness and use those bits.</p>

<p>You can get an idea of the poor quality of rand in some generators from Random.org.</p>

<p>For, example, <code>rand()</code> called by php on Windows produces the following:</p>

<p><img src="https://i.stack.imgur.com/FOGPc.png" alt="enter image description here"></p>

<p>(from Random.org)</p>

<p>Which is quite certainly, not a good random.</p>

<hr>

<p>There's a bit more to this and math that can cause some uneven distribution even with even distributions.</p>

<p>The code:</p>

```double r = rand() / (double)RAND_MAX;
```

<p><code>rand()</code> returns a number in the range <code>[0,32767]</code>.  This range isn't evenly divisible by 9 (or 3).  Thus, some values will be over sampled.  Assume we are dealing with <code>% 100</code>.  The values from <code>[0,67]</code> will be found more frequently than the values from <code>[68,99]</code>.  This is introducing a bias to the random which is problematic.</p>

<p>Yep.  The code isn't using <code>% n</code> instead uses a floating point. Now you have 2.000001 problems.</p>

<p>You've got code that is approximately:</p>

```int dst = (rand() * 1.0 / RAND_MAX) * 99
```

<p>This can be described as hilariously non-uniform.  There is only one input that can produce the maximum value because of truncation.</p>

<pre class="lang-none prettyprint-override"><code>(32765 * 1.0 / 32767) * 99 = 98
(32766 * 1.0 / 32767) * 99 = 98
(32767 * 1.0 / 32767) * 99 = 99
</code>```

No matter how you try to fix this with rand, you will have this problem you will run into the pigeonhole principle which states that if you try to put n items into m containers where n > m, at least one container will have more than one item.  This seems obvious but its what you are running into with trying to map rand into another range.

If you really only want a range of [0,2], there are appropriate calls with that can give you the uniform distribution that you are after.

The following ode (from video linked below) uses the Mersenne twister to produce a uniform distribution:

```<code>#include <iostream>
#include <random>

int main() {
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_int_distribution<int> dist(0, 99);
    for (int i = 0; i < 16; ++i) {
        std::cout << dist(mt) << " ";
    }
    std::cout << std::endl;
}
</code>```

Note that this is using a deterministic engine with a random seed.  It is not cryptographically secure, but it does have high quality fast random data.  The key is that you are using the distribution correctly.  You could use random_device for all your data, but thats consuming entropy from your system that you probably don't need to spend there (running out of entropy on ServerFault).  The twister is good enough for random load balancing.

A really good watch on this is the video rand() Considered Harmful which addresses lots of things about rand.  I've borrowed much of this section from that video.

Particular points from the video:

Non-uniform distribution (3:56 .. 5:50 )

(src * 1.0 / RAND_MAX) * 99 is hilariously non-uniform (6:12 .. 7:29)

2.0000001 problems (10:40)

Hello, Random World (12:58 .. 15:30)

If you really want things to be perfectly balanced ((333, 333, 334) events for each of three choices 1000 times), this isn't random.  Use a round robin instead.

Title: More Accurate Random in C

Body:
I have 3 IPs and every IP has a weight, I want to return the IP's according to its weights using the random function. For example if we have 3 IP's

X with weight 3

Y with weight 3

and Z with weight 3

I want to return X in 33.3% of cases and Y in 33.3% of cases and Z in 33.3% of cases, depending on random function in C.

I have tried this code :

```<code>double r = rand() / (double)RAND_MAX;
double denom = 3 + 3 + 3;
if (r < 3 / denom) {
// choose X
} else if (r < (3 + 3) / denom) {
// choose Y
} else {
// choose Z
}
</code>```

I repeat the function 1000 and I get: Choose x 495 times and Choose y 189 times and choose z 316 times. But what I want is to get X:333  y:333  Z:334 How can the weighted random be more accurate?

Body:
(This part of the question was associated with revision 2 and is still quite applicable to that problem)

The standard approach to doing this is to populate an array with the appropriate weights:

[x, x, x, x, x, x, y, y, y, y, z, z]
 1  2  3  4  5  6  1  2  3  4  1  2

and then pick one at random.

Please note that random is random.  It is very unlikely that you will ever a perfect distribution.

If you want to guarantee the distribution, you need to do (mostly) away with the random.

Instead, shuffle the above array.  For example, one shuffling would give you:

[x, y, z, y, x, x, y, x, z, y, x, x]

And then loop over the array again and again returning the current index.  It isn't random anymore, but it will guarantee the distribution remains what you are looking for always.  This is just a slightly more 'random' version of a round robin distribution.

If this is attempting to load balance something, the round robin is a better approach and you might want to consider a evenly distributed round robin:

[x, y, x, y, x, z]

This has the same distribution as above and tries to keep everything at an even distance so not as to saturate any one resource.

As an aside, to the question of rand being poor, you may be dealing with an older standard library.  From rand3 man page

The versions of rand() and srand() in the Linux C Library use the
same random number generator as random(3) and srandom(3), so the
lower-order bits should be as random as the higher-order bits.
However, on older rand() implementations, and on current
implementations on different systems, the lower-order bits are much
less random than the higher-order bits.  Do not use this function in
applications intended to be portable when good randomness is needed.
(Use random(3) instead.)

This can be demonstrated using the following C program that spits out the consecutive low byte and low nybbles from rand().  I happen to have a more modern system and don't have access to anything that might demonstrate this low order less randomness.

You can test it on your system with the following code which looks at the low byte, low 4 bits, and low 2 bits.

#include <stdlib.h>
#include <stdio.h>

int main (int argc, char** argv) {
    int i, r;
    int a8, a4, a2;

    srand(0);
    FILE *fp0xff = fopen("low8.out", "w");
    FILE *fp0x0f = fopen("low4.out", "w");
    FILE *fp0x03 = fopen("low2.out", "w");
    for(i = 0; i < 10000; i++) {
        /* 1 of 4 */
        r = rand();
        a8 = r & 0xff;
        a4 = r & 0x0f;
        a2 = r & 0x03;

        fprintf(fp0xff, "%c",a8);

        /* 2 of 4 */
        r = rand();
        a8 = r & 0xff;
        a4 = (a4 << 4) | (r & 0x0f);
        a2 = (a2 << 2) | (r & 0x03);

        fprintf(fp0xff, "%c",a8);
        fprintf(fp0x0f, "%c",a4);

        /* 3 of 4 */
        r = rand();
        a8 = r & 0xff;
        a4 = r & 0x0f;
        a2 = (a2 << 2) | (r & 0x03);

        fprintf(fp0xff, "%c",a8);

        /* 4 of 4 */
        r = rand();
        a8 = r & 0xff;
        a4 = (a4 << 4) | (r & 0x0f);
        a2 = (a2 << 2) | (r & 0x03);

        fprintf(fp0xff, "%c",a8);
        fprintf(fp0x0f, "%c",a4);
        fprintf(fp0x03, "%c",a2);
    }
    fclose(fp0xff);
    fclose(fp0x0f);
    return 0;
}

The output of this program can then be examined using ent which runs a number of tests of randomness against a stream of bytes.

Running this against the low2.out on my system produces:

Entropy = 7.982762 bits per byte.

Optimum compression would reduce the size

  of this 10000 byte file by 0 percent.

Chi square distribution for 10000 samples is 240.46, and randomly

  would exceed this value 73.46 percent of the times.

Arithmetic mean value of data bytes is 127.6318 (127.5 = random).

  Monte Carlo value for Pi is 3.150060024 (error 0.27 percent).

  Serial correlation coefficient is -0.002842 (totally uncorrelated = 0.0).

Which is frankly, a reasonably good random stream.

The reason I am testing the low two bytes is that you are doing things with % 9 which works only with these low bits.  You may find that your random number generator is old and might need to implement your own (if that degree of randomness is something that you need to work with).

One approach would be, well, to implement your own.  The Mersenne twister is quite well regarded and you can find implementations for a wide range of languages quite easily.

The other thing to do would be to shift the random number you get down 8 bits to get rid of any low order less randomness and use those bits.

You can get an idea of the poor quality of rand in some generators from Random.org.

For, example, rand() called by php on Windows produces the following:

(from Random.org)

Which is quite certainly, not a good random.

There's a bit more to this and math that can cause some uneven distribution even with even distributions.

The code:

double r = rand() / (double)RAND_MAX;

rand() returns a number in the range [0,32767].  This range isn't evenly divisible by 9 (or 3).  Thus, some values will be over sampled.  Assume we are dealing with % 100.  The values from [0,67] will be found more frequently than the values from [68,99].  This is introducing a bias to the random which is problematic.

Yep.  The code isn't using % n instead uses a floating point. Now you have 2.000001 problems.

You've got code that is approximately:

int dst = (rand() * 1.0 / RAND_MAX) * 99

This can be described as hilariously non-uniform.  There is only one input that can produce the maximum value because of truncation.

(32765 * 1.0 / 32767) * 99 = 98
(32766 * 1.0 / 32767) * 99 = 98
(32767 * 1.0 / 32767) * 99 = 99

No matter how you try to fix this with rand, you will have this problem you will run into the pigeonhole principle which states that if you try to put n items into m containers where n > m, at least one container will have more than one item.  This seems obvious but its what you are running into with trying to map rand into another range.

If you really only want a range of [0,2], there are appropriate calls with that can give you the uniform distribution that you are after.

The following ode (from video linked below) uses the Mersenne twister to produce a uniform distribution:

#include <iostream>
#include <random>

int main() {
    std::random_device rd;
    std::mt19937 mt(rd());
    std::uniform_int_distribution<int> dist(0, 99);
    for (int i = 0; i < 16; ++i) {
        std::cout << dist(mt) << " ";
    }
    std::cout << std::endl;
}

Note that this is using a deterministic engine with a random seed.  It is not cryptographically secure, but it does have high quality fast random data.  The key is that you are using the distribution correctly.  You could use random_device for all your data, but thats consuming entropy from your system that you probably don't need to spend there (running out of entropy on ServerFault).  The twister is good enough for random load balancing.

A really good watch on this is the video rand() Considered Harmful which addresses lots of things about rand.  I've borrowed much of this section from that video.

Particular points from the video:

Non-uniform distribution (3:56 .. 5:50 )

(src * 1.0 / RAND_MAX) * 99 is hilariously non-uniform (6:12 .. 7:29)

2.0000001 problems (10:40)

Hello, Random World (12:58 .. 15:30)

If you really want things to be perfectly balanced ((333, 333, 334) events for each of three choices 1000 times), this isn't random.  Use a round robin instead.


问:
What is the history of the use of "foo" and "bar" in source code examples?
Why do many code examples, especially tutorials, use the names "Foo" and "Bar" so often? It is almost a standard.

For example:

```<code>void foo(char* bar) {
  printf("%s", bar);
}
</code>```

答:
These are nonsense words that in most cases can be substituted with more relevant example words.  The words "foo" and "bar" are frequently used in programming when someone can't think of a good example.

If "foo" and "bar" are derived from FUBAR, why is it they are used by so many professionals in instruction examples when the examples resemble nothing being f'd up beyond recognition?

To me, the common use of these words inappropriately is what's so f'd up beyond recognition.


问:
Should I commit my generated parser to source control?
I'm using a parser generator to build a compiler.  Should I commit the source files produced by the parser generator?

I want to commit them to avoid a dependency on the parser generator during the build process and tests.

However, if I commit them, it is tempting never to update the parser generator for fear of backwards-incompatible changes.

Are there other advantages or disadvantages that I have not thought of?

References:

Do I check generated code in to source control or not?

What Part of Your Project Should be in Source Code Control?

答:
My suggestion is no, you should not commit machine generated files. Source control should be reserved for original (source) material only, not intermediate files. Do you commit compiled objects to source in case the compiler changes? You problem almost certainly lies in configuration management (of the tool chain), not source management. Unfortunately source control is too often used to achieve both.

In the first instance I would look closely at build configuration. Is it possible to treat the parser outputs as another tool the build process used, and have a project to build the parser outputs. Look for solutions in this space first

If other options have been explored and deemed too expensive or technically difficult etc, it is not the worst evil in the world to commit the files to source control - the sun will still rise in the east tomorrow morning.


答:
If you want to truly guarantee that you'll get exactly the distribution you want, you can create a pool of values that you pull from:

```<code>int xpool = 333;
int ypool = 333;
int zpool = 334;

int x = 0;
int y = 0;
int z = 0;

for(unsigned int trial=0;trial<1000;trial++) {

    unsigned int r = rand() % (xpool + ypool + zpool);

    if(r < xpool) {
        x++;
        xpool--;
    }
    else if(r < xpool + ypool ) {
        y++;
        ypool--;
    }
    else {
        z++;
        zpool--;
    }
}
cout << "x: " << x << " y:" << y << " z:" << z << endl;
</code>```

This will guarantee that you always have an exact distribution, but the order will be as random as rand() can make it.  This works well if the number of choices is low, and you know how many trials you will have ahead of time.

It depends on what you want.  If you want something to give a good weighted distribution with infinite trials, use @MichaelT's answer.  If you want to guarantee an exact distribution and know the number of trials, the do something like this.

Title: More Accurate Random in C

Body:
If you want to truly guarantee that you'll get exactly the distribution you want, you can create a pool of values that you pull from:

int xpool = 333;
int ypool = 333;
int zpool = 334;

int x = 0;
int y = 0;
int z = 0;

for(unsigned int trial=0;trial<1000;trial++) {

    unsigned int r = rand() % (xpool + ypool + zpool);

    if(r < xpool) {
        x++;
        xpool--;
    }
    else if(r < xpool + ypool ) {
        y++;
        ypool--;
    }
    else {
        z++;
        zpool--;
    }
}
cout << "x: " << x << " y:" << y << " z:" << z << endl;

This will guarantee that you always have an exact distribution, but the order will be as random as rand() can make it.  This works well if the number of choices is low, and you know how many trials you will have ahead of time.

It depends on what you want.  If you want something to give a good weighted distribution with infinite trials, use @MichaelT's answer.  If you want to guarantee an exact distribution and know the number of trials, the do something like this.


问:
Beautiful user interface vs. more and more technical features?
I will understand if you find this is more a discussion than a technical question and if you close the topic (then, where would be an appropriate place to discuss about that? thank you in advance).

The question : how do you decide between improving the user interface with a great design or adding more and more technical features?

I would like to meet people interested in Windows coding beautiful user interfaces in order to improve an existing (very powerful but not good-looking) open-source project, which has a lot of potentiality!

I know this is probably not the appropriate place for such a question, but maybe you would know a better place?

答:
Make the UI complicated and users will:

not use your application as it'll appear too daunting

find the learning curve to steep (but may really like it once they know how to use it)

You will also find it incredibly difficult to sell to potential clients.

Making the UI clear probably means that the application will become more appealing to existing and prospect clients, but if the functionality isn't there, then nobody will use it anyway.

I think the answer is: both are equally important and you have to find a way to produce an application which is both user friendly and adds value to the end user.


答:
For me that choice comes down to the purpose of the app.

As a designer turned developer, I always tend to lean on beautiful design that is functional. And any technical features that are added should serve a purpose that makes things easier on the user. Rather then overcomplicating things.

It's hard for me to imagine a scenario where lot's of technical features are needed just for the sake of it.

Title: Beautiful user interface vs. more and more technical features?

Body:
I will understand if you find this is more a discussion than a technical question and if you close the topic (then, where would be an appropriate place to discuss about that? thank you in advance).

The question : how do you decide between improving the user interface with a great design or adding more and more technical features?

I would like to meet people interested in Windows coding beautiful user interfaces in order to improve an existing (very powerful but not good-looking) open-source project, which has a lot of potentiality!

I know this is probably not the appropriate place for such a question, but maybe you would know a better place?


答:
If there are usability issues with the current software, then the argument is an easy one. If a significant part of your target users can not complete key tasks or take more time or energy than expected, then you should probably fix that before adding more features.
Only a usability test can reveal such issues. Without objective data you will just get endless discussions about taste or gut feeling.

If the UX testing revealed that usability is okay, and this question is more about aesthetics, then it becomes a matter of strategy. Do you want to be the Swiss Army knife, or the designer cork screw?


问:
Can AspectJ or AOP in general be used to test exception handling?
I'm reading a book's chapter ("Controlled Exception Test" in "Testing Object-Oriented Testing") about testing exception handling in a running system (not at unit level). The conclusion is that it is hard to automatically trigger an exception at a given layer in the system other then simulate a cause for an exception.

Wouldn't usage of AspectJ or any other AOP approach solve the problem?

With AOP I can create an aspect that will throw an expected exception and attach it to the method called before exception handling.

答:
AOP frameworks normally address cross-cutting concerns. Exception handling is one of them. I may say that I want to log invocation of every method in my business layer and I also want to intercept and log every exception thrown by any method in that business layer.

When it comes to unit testing, I don't want to test that aspect oriented framework intercepts the method call and logs the exception. People who wrote the aspect oriented framework did this testing already and they know that it works.

What you probably want to test is how the code behaves when the exception is thrown. You normally achieve this with mocking frameworks. For example, in my business layer I have a method that returns me latest films:

```<code>[LogExceptionThroughAOPFramework]
public IEnumerable<FilmSummary> GetLatestFilms()
{
   var latestFilms = _repository.GetLatestFilms();
   var latestFilmsDTO = Mapper.Map<FilmSummaryDTO>(latestFilms);
   return latestFilmsDTO;
}
</code>```

Now, above method may fail when it calls _repository.GetLatestFilms();

There is also an imaginary attribute called LogExceptionThroughAOPFramework - it intercepts a method call and logs the exception.

When it comes to testing this method, you don't want to check that AOP framework logs the exception. It's a third party dependency and you don't want to rely on that dependency. Interception has already been tested by people who wrote the framework. If all your exception handling/logging is done by AOP framework, then you don't need to test it. Instead, test logic of LogExceptionThroughAOPFramework and that should be enough.

If you don't use AOP framework, then use a mocking framework. For example:

```<code>[TestMethod]
[ExpectedException(typeof(RelevantTypeOfException)]
public void GetLatestFilms_RepositoryThrowsException_ExpectExceptionToBePropagated
{
   var repository = new Mock<ILatestFilmsRepository>();
   repository.Expect(call => call.GetLatestFilms()).Throws(new RelevantTypeOfException());

   var client = new FilmClient(repository);
   // Throws exception
   client.GetLatestFilms();
}
</code>```

In above test I say that I expect exception to be thrown (attribute above test method). I then configure my repository (mock) to throw an exception when I try to get latest films. Finally, I make a client object and attempt to get a list of latest films. In the constructor I pass a mock repository, which then throws an exception. The test will pass as the exception will be thrown.

Also, you said:

With AOP I can create an aspect that will throw an expected exception
  and attach it to the method called before exception handling.

If you do that, then what will you be testing? If exception is thrown by aspect, then you won't be testing your business logic. You will be testing aspect throwing exceptions. I don't see any value in that.

Update

You could potentially add an aspect to whatever it is that you are testing.

You would have to add an aspect for each test. Your aspect must be aware of the context its being executed in, i.e. it needs to know that code is executing in a test context.

So if I wanted to test how the system behaves if repository throws an exception, I'd have to write something on the lines of:

```<code>[ThrowExceptionOnlyDuringTest("TestScenario")]
[ThrowExceptionOnlyDuringTest("DifferentTestScenario")]
public IEnumerable<FilmSummary> GetLatestFilms()
{
   // Logic to retrieve films
}
</code>```

I don't know how you would then wire up your test to this aspect. As far as I can see it, this is not much different to setting expectations on mocks. Aspect will create a proxy for method execution and will throw an exception. Mocking framework will do exactly the same, but in a simpler way.

Update 2

I'm assuming that in your case, you are testing integration of the entire system. You have access to all the components and you are trying to find a nice way of making these components fail during integration tests. AOP approach might work here, I'm still not sure.

What happens in the scenario where you don't have control over components that you are integrating with? For example, if your system talks to currency exchange service in another country, there will be no way you'll get it to fail. In this instance you will simply mock this service and make it throw an exception during integration testing. Because of this, I think it makes sense to have an integration tests with a mock that throws an exception in certain scenario.

Body:
AOP frameworks normally address cross-cutting concerns. Exception handling is one of them. I may say that I want to log invocation of every method in my business layer and I also want to intercept and log every exception thrown by any method in that business layer.

When it comes to unit testing, I don't want to test that aspect oriented framework intercepts the method call and logs the exception. People who wrote the aspect oriented framework did this testing already and they know that it works.

What you probably want to test is how the code behaves when the exception is thrown. You normally achieve this with mocking frameworks. For example, in my business layer I have a method that returns me latest films:

[LogExceptionThroughAOPFramework]
public IEnumerable<FilmSummary> GetLatestFilms()
{
   var latestFilms = _repository.GetLatestFilms();
   var latestFilmsDTO = Mapper.Map<FilmSummaryDTO>(latestFilms);
   return latestFilmsDTO;
}

Now, above method may fail when it calls _repository.GetLatestFilms();

There is also an imaginary attribute called LogExceptionThroughAOPFramework - it intercepts a method call and logs the exception.

When it comes to testing this method, you don't want to check that AOP framework logs the exception. It's a third party dependency and you don't want to rely on that dependency. Interception has already been tested by people who wrote the framework. If all your exception handling/logging is done by AOP framework, then you don't need to test it. Instead, test logic of LogExceptionThroughAOPFramework and that should be enough.

If you don't use AOP framework, then use a mocking framework. For example:

[TestMethod]
[ExpectedException(typeof(RelevantTypeOfException)]
public void GetLatestFilms_RepositoryThrowsException_ExpectExceptionToBePropagated
{
   var repository = new Mock<ILatestFilmsRepository>();
   repository.Expect(call => call.GetLatestFilms()).Throws(new RelevantTypeOfException());

   var client = new FilmClient(repository);
   // Throws exception
   client.GetLatestFilms();
}

In above test I say that I expect exception to be thrown (attribute above test method). I then configure my repository (mock) to throw an exception when I try to get latest films. Finally, I make a client object and attempt to get a list of latest films. In the constructor I pass a mock repository, which then throws an exception. The test will pass as the exception will be thrown.

Also, you said:

With AOP I can create an aspect that will throw an expected exception
  and attach it to the method called before exception handling.

If you do that, then what will you be testing? If exception is thrown by aspect, then you won't be testing your business logic. You will be testing aspect throwing exceptions. I don't see any value in that.

Update

You could potentially add an aspect to whatever it is that you are testing.

You would have to add an aspect for each test. Your aspect must be aware of the context its being executed in, i.e. it needs to know that code is executing in a test context.

So if I wanted to test how the system behaves if repository throws an exception, I'd have to write something on the lines of:

[ThrowExceptionOnlyDuringTest("TestScenario")]
[ThrowExceptionOnlyDuringTest("DifferentTestScenario")]
public IEnumerable<FilmSummary> GetLatestFilms()
{
   // Logic to retrieve films
}

I don't know how you would then wire up your test to this aspect. As far as I can see it, this is not much different to setting expectations on mocks. Aspect will create a proxy for method execution and will throw an exception. Mocking framework will do exactly the same, but in a simpler way.

Update 2

I'm assuming that in your case, you are testing integration of the entire system. You have access to all the components and you are trying to find a nice way of making these components fail during integration tests. AOP approach might work here, I'm still not sure.

What happens in the scenario where you don't have control over components that you are integrating with? For example, if your system talks to currency exchange service in another country, there will be no way you'll get it to fail. In this instance you will simply mock this service and make it throw an exception during integration testing. Because of this, I think it makes sense to have an integration tests with a mock that throws an exception in certain scenario.


答:
How do you decide? You ask your users. Everything we do in developing software should be about meeting the needs of the users. You shouldn't redesign just for the sake of redesign, and you shouldn't add features that the users don't need.

So, when faced with the opportunity to either add more features or improve the design, the first question you should answer is "what will make the product more useful to the end user?".   And by useful, make sure you focus on making them more productive, rather than giving them more features that few will use.

Of course, the world isn't always that simple. For example, you may have a very functional product, but because it is ugly you can't get any users to buy it. So, you might need to consider that the business as a whole is also your customer, and you may need to address cosmetic concerns to improve sales. Even when that is true, however, the bottom line still needs to be focused on the end user.


问:
Is it possible to compile a higher level language to readable C++?
C++ is a great language in many ways, but some things in particular are cumbersome to write without an IDE. As a VIM user, it would be very interesting if I had access to a higher level language which enabled me to write C++ with S-Expressions and possibly with Lisp-like macros, allowing for the generation of clean code while avoiding rewriting the same patters over and over again.

I've asked on freenode and tested several ideas, such as compiling Lisp->C with compilers such as ECL and Bigloo, but none of those generated particularly clean C code.

Are there any works on this issue?

答:
Compiling higher level languages to lower level ones is cake.  There's countless examples of it being done.  Without going off on much of a tangent, we can point to early C++ compilers that compiled down to C.

When you start throwing "clean" and "readable" into the mix, however, things get really tough.  Clean, readable code expresses the meaning and intent of what you were writing.  Computers are notoriously bad at interpreting & creating meaning.  You're more likely to end up with variables named int_147 than input_buffer_length.  Sure, if you really wanted to make this project work, you could engage in a massive AI project to handle converting your Lisp to some sort of decently readable C++ but, to be perfectly honest, Common Lisp compilers are pretty fucking good at what they do.

More important than the difficulty of generating C++ from a Lisp is the usefulness of this.  What purpose would it serve for the generated C++ to be readable?  If the Lisp is your source code, intermediate representations should be irrelevant.  If you want to be able to hand the C++ over to programmers that don't understand your original Lisp, you've now got another problem.  What happens when they want to modify your generated C++?  What happens if they write things in C++ that don't cleanly translate to your Lisp?

Let's say we've solved that.  It's a decade later and, after burning through hundreds of millions of dollars of DoD grant money, we've build this massive, complex (but flawless) language translation engine that can turn Lisp into idiomatic C++ and vice versa. What have we really gained that wouldn't be better accomplished by either teaching people a new programming language or just developing a new compiler that lets us link the two languages?

Oh, right.  Your boss wants you to write C++ and you'd rather not.  Update your resume & find a new job.


答:
Short answer, there is nothing out there currently that will help you convert Lisp to READABLE C++. Sure you can convert anything to C++ or C but readable code is written by humans, not programs. Sure you can output C++ code with proper formatting, indents, nice class names, and maybe even somehow get perfect translation from Lisp class objects to C++ classes. Maybe you can get your library dependencies linked just right, and maybe you can compile binaries that are very close to what the C language would have produced had you written the whole thing in C. But ultimately, readable code is a beauty that is not understood by anyone, at least not just yet, and possibly never considering that the term readable is quite subjective to begin with and what might be considered readable among one group of developers may be considered atrocious by others.

To make C++ readable, you have to write in C++, not in Lisp. You also have to be able to change your coding style according to what the people who will read your code will best understand. Just like books, programs are written with a specific audience in mind and can be beautiful and touching if written well, and obfuscated and tedious if not. And if we can't come up with a program to write beautiful fiction novels for us, then we won't be able to come up with something to convert to readable C++.

Title: Is it possible to compile a higher level language to readable C++?

Body:
C++ is a great language in many ways, but some things in particular are cumbersome to write without an IDE. As a VIM user, it would be very interesting if I had access to a higher level language which enabled me to write C++ with S-Expressions and possibly with Lisp-like macros, allowing for the generation of clean code while avoiding rewriting the same patters over and over again.

I've asked on freenode and tested several ideas, such as compiling Lisp->C with compilers such as ECL and Bigloo, but none of those generated particularly clean C code.

Are there any works on this issue?


答:
There is another option that is the best of both worlds. Allow your users to modify the UI to fit their workflow. Every user is different and if you ask your users what they want, you'll learn that if you set the UI in stone, you're going to anger one group or the other. For instance, some will prefer using a keyboard, others will prefer touch screens, still more will prefer a mouse and pointer. Optimize your UI to just one and the other 2/3 of your clients will be raising hell.

Some Best Practices

Users should be enabled to customize the UI. This can be enterprise-level or set with user profiles. Being able to trim unused features or bring features into a higher priority location or view is key to having a UI that pleases a wide client base.
Exception: The secondary views should probably remain uniform across the spectrum. If someone needs to find something, they should be able to go to the secondary view state and get directly to their destination, regardless of who's UI they are using. Everything should still be familiar. Same goes for the location of key navigation elements such as top-level menus. Keep them in a consistent location on the screen.

Lesser-used features should be relegated to a secondary view. The most-used features should be at the opening screen and be afforded more screen space.

The UI should be very simple. Easy on the use of heavy graphics, images, and animations. Animations should be rapid and limited to indicating an input was received (i.e. onclick color change), to indicated sending/receiving state, but never to entertain the user. Background animations should be subtle and slow to not distract the user. Or non-existent.

Keystrokes that jump to a desired state can save as many levels of clicks as you wish. Clicks are the Antichrist.

Be explicit. Don't assume something is obvious because it's got an icon. Design your UI for a child. Give hints, labels, and direction. If a child can figure it out intuitively, it will be a breeze for an adult.

Use inactive states. If it doesn't make sense to use a button prematurely, gray it out and focus the attention on what needs to be done first.

Individual users could opt for preferred states to appear on start-up that might be different than another user because their role in the business is slightly different. This could save them clicks to get there every time.
Exception: The user should easily be able to navigate from anywhere with clarity and a consistent navigation system that is uniform and familiar.

Color-code UI elements. Make certain colors have meaning. Red usually means danger. Green usually means OK. Yellow is caution. Blue is action. Black is information. Gray is inactive.  Exception: Do not go overboard with colors. The UI should remain uniform in appearance. Group similar items both in location and in color (i.e. breakfast menu with a yellow border, lunch in blue, dinner in red). Exception: Color schemes for functional components should not alter between users, but allowing the user to alter the color of a background element or overall appearance is OK. We see color before we read words, though, and having consistent colors for the same component can eliminate confusion when changing terminals when the same button is blue in one terminal and red in another.

Consider modules and extensions for users with specific needs.


答: You should commit all three components (parser generator, input language, and output language) to source control, to help disentangle the blame when unexpected problems arise.</p>

Title: Should I commit my generated parser to source control?

Body:
I'm using a parser generator to build a compiler.  Should I commit the source files produced by the parser generator?

I want to commit them to avoid a dependency on the parser generator during the build process and tests.

However, if I commit them, it is tempting never to update the parser generator for fear of backwards-incompatible changes.

Are there other advantages or disadvantages that I have not thought of?

References:

Do I check generated code in to source control or not?

What Part of Your Project Should be in Source Code Control?


问:
How would I make a compiler in C++?
This probably been asked for but I can't google "How to make a  compiler in C++" because I will just get "How to compile C++" as the results. Anyway, for my question, I'd like to make a simple programming language in C++. Now I understand basic file IO stuff but what I don't get is how to build a EXE. The problem here is I don't know how EXEs exactly are "planned out", granted that most people don't. I was going to simply parse the language into assembly and assemble it using an assembler. But I don't want to do that, I want to actually compile it directly into a EXE. Does anyone know how  this would be done? PS: To all you people who say making a compiler is virtually impossible, it's a fairly fast process, it's just implementing OOP features that's hard</p>

答:
There is not much difference between understanding assembly and understanding the machine code that it creates.  You should create your own assembler or at least study the disassembly of asm that has been assembled by some toolchain, such that you can create your own machine code.  Again not a stretch if you are proficient in assembly.  The next issue is the EXE file format.  Googling should make that quite easy.  As far as planning out what goes in the EXE, that is basic programming, not specific to an EXE.  </p>

<p>You will most likely be successful if you start by having your language compiler output assembly language, then use an existing toolchain (assembler and linker) to turn that assembly language into an EXE.  Create and debug your language and compiler.  Then replace the assembler and linker by generating the machine code directly.  </p>

Title: How would I make a compiler in C++?

Body:
There is not much difference between understanding assembly and understanding the machine code that it creates.  You should create your own assembler or at least study the disassembly of asm that has been assembled by some toolchain, such that you can create your own machine code.  Again not a stretch if you are proficient in assembly.  The next issue is the EXE file format.  Googling should make that quite easy.  As far as planning out what goes in the EXE, that is basic programming, not specific to an EXE.

You will most likely be successful if you start by having your language compiler output assembly language, then use an existing toolchain (assembler and linker) to turn that assembly language into an EXE.  Create and debug your language and compiler.  Then replace the assembler and linker by generating the machine code directly.


问:
Checking for cross-site scripting vulnerabilities in Perl web applications
I'm putting together some notes for a dev team on how to write secure Perl code - especially taking into account the current OWASP top 10 web application vulnerabilities. For cross-site scripting I've included information on ensuring that all output to the browser is checked and escaped where necessary, but I'm looking for more automated mechanisms that would mean a developer doesn't have to think about every output statement and, potentially, miss one. Perl's 'taint' function sounds like it should be a help because it distrusts all user input, but it doesn't complain on tainted data being output to the browser. Apart from checking all output statements individually (probably by calling a generic sanitizing function) does anyone have any ideas on how Perl can help with this with existing libraries or techniques?</p>

答: You might want to take a look at the article CERT Secure Coding Initiative Tackles Standard for Perl, the slides about Perl::Critic for Security Audits, and Perl::Critic in general.</p>


问:
Is allowing voting without sign-in always a bad idea?
I have a mobile app from which I'd like to allow voting on Things. I don't want to force all the users to have to sign up using email/Facebook/etc. just so that I can properly limit voting.

Is it really a bad idea to leave voting to be an "open" process where anyone can vote? I know theoretically that this allows improper voting techniques, etc. but on the other hand getting more votes really don't offer any kind of financial motivation.

--Edit--

Perhaps there are some ways to limit vote-faking? I know theoretically nothing is unbreakable, but maybe I can limit the amount of votes something can get in a minute/hour/day?

--Edit 2 --

Think of it as "views" on a video. It is a simple measure of popularity that requires no login. What are ways to limit view tampering, and when is it necessary?

答:
Of course it's not always a bad idea. It's always a trade-off between effort expended on one thing and effort expended on another, and between effort and gain. You've obviously thought about this, and think that in your case the effort of programming checks isn't justified by the added value. That's fine.

A problem will arise when you go live with this solution under the assumption that ballot-stuffing isn't a problem and don't communicate this assumption to the users. Eventually, your app will be used by people who don't share that assumption and feel betrayed when the system behaves differently from how they assume an online vote should behave. This can be a terrible shock to people, and you will lose users about it. So the more appropriate perspective is: "Is programming anti-cheating checks more effort than adding language to the project which informs users of their absence?" The answer may still be "yes", but you can decide that better than we can.


答:
if you dont autheticate the user, you can not guarantee he/she will not vote a hundred times .. just for the fun of manipulation ... or other motives. Some people even write small voting scripts. It might "hammer" your vote-counter just for the fun of it.

You can save the IP-Adress for the votes and just dont let them vote for 10 Minutes BUT there are whole corporations/schools ... behind a single IP Adress. You end up blocking them as a whole.

What you could to is submit some encrypted id with the vote. Encryption in your app must create a unique id for your user you would have to verify in the vote script on your server.

One way to do this is a md5('someuniqueuseridstuff'+$yoursecretpassintheapp) and transmit the md5 with the plain userid ('someuniqueuseridstuff') so you can verify the uniqueid on the server. Its by far not unbreakable(use a looong $yoursecretpassintheapp)  but defies some level of tempering.

Edit: do you have client local storage ? you could hand out ids and save them to client local storage ...

Title: Is allowing voting without sign-in always a bad idea?

Body:
I have a mobile app from which I'd like to allow voting on Things. I don't want to force all the users to have to sign up using email/Facebook/etc. just so that I can properly limit voting.

Is it really a bad idea to leave voting to be an "open" process where anyone can vote? I know theoretically that this allows improper voting techniques, etc. but on the other hand getting more votes really don't offer any kind of financial motivation.

--Edit--

Perhaps there are some ways to limit vote-faking? I know theoretically nothing is unbreakable, but maybe I can limit the amount of votes something can get in a minute/hour/day?

--Edit 2 --

Think of it as "views" on a video. It is a simple measure of popularity that requires no login. What are ways to limit view tampering, and when is it necessary?