What are the reasons for not supporting constructive mathematics?

Question: It is obvious that in constructive mathematics, you cannot use the law of excluded middle. What else would be the reasons for not adopting the constructive stance in mathematics?
Comment: Because it requires more work, and mathematicians are by nature lazy?
Comment: Because it's incompatible with much of the mathematics that I like.
Comment: @DonAntonio: "The Axiom of Choice is clearly true, the well-ordering principle is clearly false, and nobody really knows about Zorn's lemma" is an old math joke.
Comment: Because proofs by contradiction are always fun!
Comment: I tend to believe that things can exist, even if we are unable to describe them explicitly.
Comment: I wholeheartedly agree with the commented by Marc and Brian, yet there's one further reason important to me: the excluded middle makes a lot of sense in my mind. For me, it is a completely sound and "logical" assumption and I've no problem at all with it. Just as AC, but even easier to grasp.
Comment: I find the wording of the question a little strange.  I have no *stance* myself on any of these issues.  I request different kinds of proofs of facts depending on what I want.  Sometimes I want a constructive procedure, sometimes I don't care.   It really depends on the purpose of the proposition as to which type of proof you want or which kind of formalism you want to live in.
Comment: @Brian M. Scott: most constructive logics have the property that the things they prove are a proper subset of the things provable classically. These logics are not in any way incompatible with usual mathematics, they are just weaker.
Comment: Because those truths that we intuit outstrip those that we can prove, and even more so those, truths that we do actually prove.
Comment: Because classical logic doesn't lead to falsehoods. (On which even ituitionists would agree, though they may dispute whether all it leads to is truth).
Comment: @DonAntonio: I don't understand what you mean - the axiom of choice is obviously true! (On the other hand, the well-ordering principle is obviously false, and I personally don't believe Zorn's Lemma. It is silly.)
Comment: @Brian M. Scott: many constructive systems include the axiom of choice, it's a completely separate issue.
Comment: Well @user1729, if AC was "obviously true" why then there are *mathematicians* who don't accept it? Perhaps what's "obvious" to you isn't to others...? OTOH, in ZF, the well-ordering principle is equivalent with, oh paradox!, both AC and Zorn's Lemma, so your calling the last one "silly" doesn't make you look specially sharp, does it? Now, if you want to throw away ZF and work under other system go ahead and be anyone's guest.
Comment: @DonAntonio: Deadpan humour is the best kind of humour. I was in a talk last week where Martin Bridson nonchalantly described studying the Nilpotent Genus, I believe it was, of a group as "a disease he caught from Baumslag". Que shock then laughter from us graduate students hiding at the back...
Comment: @BrianM.Scott: I think that holds true for much of what i done under the banner of constructivism, especially the things in the tradition of Bishop. But Brouwers intuitionism was very different.
Comment: @Marc van Leeuwen : Some of us are by nature masochists, and those of us who are actually do constructive mathematics. But there are a few of them, not so many, fair enough... =)
Comment: @MichaelGreinecker, I know that, thanks. Yet user 1729 changed in such a way (in particular the adding "it is silly") that made it look, at least in my eyes, as no particularly "jokely". Anyway I shall have my irony-sarcasm glands checked next week.
Comment: @Carl: Weak enough to be incompatible with what I want to do. I like non-constructive existence proofs. I insist on the axiom of choice.
Comment: @Carl: Not in the sense of *constructive* with which I'm familiar and was using the term. (And I certainly wouldn't apply the term to anything that permitted the use of AC.)
Comment: @Carl, or arguably sometimes stronger since we can interpret classical logic in intuitionistic logic. It is a more expressive language so there are more distinctions and more unprovable equivalences. (I sometimes wonder what would have happened if constructivists used new logical symbols in place of classical ones. :)
Comment: what is constructive mathematics?
Comment: i think by constructive (and excluded middle) you refer to intuitionism specifically, which accepts excluded middle but not un-critically. For example for very large sets where it is not at all obvious or inferable that this holds..
Comment: "Supporting" and "adopting" are not synonyms. It would be helpful if you could reconcile the title of your question with the question. I support constructive mathematics, but I don't adopt constructivism as a dogma.
Comment: you mean HAXiom of Choice
Answer: This is a philosophical question rather than a mathematical one, although mathematical results can provide significant insight.
On its own, not being able to use excluded middle is not a justification for constructive logic any more than being able to use excluded middle is a justification for classical logic. The justification comes in the benefits that are derived from avoiding excluded middle, or are derived from using it.
Classical logic is the logic of structures - of things that "exist" in some sense, or at least have objective properties independent of whether we can verify those properties. Thus, for example, if I have a function that assigns each real number either "red" or "blue", then either every real number is assigned "red" or some real number is assigned "blue". That latter fact is not "constructively provable" - because constructive mathematics is not about what is true as much as it is about what we can verify (of course, anything we can verify to be true is true). Just because I know that "not every real number is assigned red" does not mean that I actually know a specific real number that is assigned "blue", and thus I have no way to verify that some real number is assigned "blue" even though I know, classically, that there must be one.
Thus, in a sense, classical logic is the logic of truth and constructive logics are logics of verification. By verification I mean more than just "proof"; I mean the sort of thing that is captured in the BHK interpretation. In settings where we are interested in that sort of verification - for example, in computable mathematics - a constructive logic will work well. In settings where we simply want to reason about truth, rather than about concrete verification, classical logic is better. Most mathematicians are interested in reasoning about mathematical objects, and because of this they use classical logic.
Comment: @Brian M. Scott: that's like saying a fork is better than a spoon because a fork has tines. It's not a justification, it's just a description.
Comment: As far as I'm concerned, being able to use excluded middle **is** a justification for classical logic.
Comment: your comment above: "because constructive mathematics is not about what is true as much as it is about what we can verify" is equally valid in nonconstructive mathematics. Classical statements also have to be verified; classical theorems are accompanied by proofs which are the verifications of the statements contingent the on assumptions.
Comment: My point is that classical logic is designed to reason about truth values of statements (its rules preserve truth) while constructive logics reason about verification (their rules preserve not only truth [usually], but various kinds of concrete verifiability). By "verifiability" I mean more than just provability; the BHK interpretation gives one precise sense of what I mean.
Comment: I don't know what BHK is, but there are truth values in Boolean algebras and truth values in Heyting algebras. The former model classical logic, while the latter constructive logic. Both evolve in the same way, but the latter only use Modus Ponens as axiom - that's the only difference. They are both about reasoning about truth values.
Comment: Obviously I don't see it that way.
Comment: I'm no expert in the field, but the whole intuitionist program seems to me to be a gross over-reaction to contradictions of naive set theory -- throwing the baby (LEM) out with the bathwater.
Comment: @Dan Christensen: I think the end of Kaveh's answer is relevant to that.
Comment: You do not mention that exactly this classical logic in mathematics results in many paradoxes which are not present in constructive mathematics in general (and this to a large extend) beats the purpose of classical maths.
Answer: Historically the main reason that Hilbert and others have rejected constructive mathematics was because it mean that they have to use more restricted ways of reasoning and some felt that forbidding PEM in mathematics is to tie the hands of mathematician. Or in another colorful language due to Hilbert, it felt as being expelled from "Cantorian Paradise" of set theory (Mathematicians are very conservative people regarding mathematics).
It also seemed that by accepting constructivism one needs to throwing away a considerable amount of mathematics developed by that time. Even more troubling for them was the fact that some classical results become not just unprovable but false in their literal constructive reading! (Not very surprising after all, you can't expect much if you try to read an English sentence as if it is written in French.)
For that matter, the rejection was not as philosophical as it might seem. Hilbert himself was a finitist. He saw ideal objects as means that help one prove results, but he thought that they are not really needed. One of the goals of his proof theory program was to make sure that using "ideal" objects like abstract sets and real numbers does not lead to incorrect results about "real" objects like natural numbers.
In addition, stating or proving results in a constructive way is often not straight forward. The constructive language takes into account information when we talk about mathematical objects. How an object is represented and given becomes important. Classically equivalent concepts (e.g. $\lnot (\lnot p \land \lnot q)$ vs. $p \lor q$, Dedekind real numbers vs. Cauchy real numbers, etc.) become distinct.
I would suggest having a look at Bishop style constructive mathematics. Bishop tried to address these issues and obtain a constructive mathematics which is compatible with classical mathematics and would be more acceptable for classically minded mathematicians.
Another issue, as mentioned in the comments, was that at some point Godel proved that from the perspective of security of mathematical foundations, there is not much difference between classical and constructive. Simplified, this means that proving a result classically is the same as proving the Godel translation of the result constructively. So the main original supportive argument for constructive mathematics (i.e. it is more secure) became useless.
Constructive mathematics suffered a continuous decline among mathematicians until its relevance to computers become clear. It seems to me that eventually the relation with computational mathematics (e.g. Martin-Löf style type-theory) was a more important factor in revival of constructive mathematics that philosophical issues. (Bishop style constructivism also had a considerable effect).
Comment: I am satisfied with my answer as it is. I don't have time to reply of your misunderstandings or get into a debate with you right now, sorry. (Please feel free to "do science" wherever you please.)
Comment: unf. cannot link, copy-pasting. *You do not mention that exactly this classical logic in mathematics results in many paradoxes which are not present in constructive mathematics in general (and this to a large extend) beats the purpose of classical maths*
Comment: Goedel provided a translation ("Dialectica Interpretation") of classical logic *inside* intuitionistic logic. Importantly the negative translation is **not** applicable in all cases. In fact the answer seems to forget that some classical results are false in intuitionism.
Comment: FYI, there are no known paradoxes in classical logic, you are confusing naïve set theory with classical logic.
Comment: @Nikos M.: the Russell paradox applies equally well to constructive systems; cf. http://publish.uwo.ca/~jbell/russ.pdf
Comment: How about the [Banach–Tarski paradox](http://en.wikipedia.org/wiki/Banach%E2%80%93Tarski_paradox), and other related to (classical concepts of) infinity
Comment: Since you mention classical logic, how about [Russell's paradox](http://en.wikipedia.org/wiki/Russell%27s_paradox)? A classical non-constructive paradox
Comment: But you have a point, if classical logic is taken out of context, by itself has no paradoxes. But in classical mathematics there are many non-constructive paradoxes, and this was my initlal point. Setting the record straight.
Comment: Quoting your answer "*It also seemed that by accepting constructivism one needs to throwing away a considerable amount of mathematics developed by that time*". This was what my comment was about. Lets not leave traces of misunderstanding, based on shades of meaning.
Comment: Thank you. Yet, still bypassing Kaveh. Anyway i dont want to get personal, have a nice time.
Comment: PS. in a strictly friendly way, whenever you want and have time we can always have a chat about maths (and whatelse). No hard feelings
Answer: One justification I've heard goes something like this: one of the purposes of constructive mathematics is that it is closer to being applicable in the real world. But non-constructive methods are useful for getting to results more expediently. Once a result is proven non-constructively, its constructive content (and hence is real-world applicability) can be investigated.
Comment: This is indeed a justification that some give, but it relies on a very reductive meaning of "real world" that would not be shared by e.g. mathematical realists.
Comment: This is exaclty opposite to Archimedes' method of finding a mathematical proof (*On the mechanical theorems*). Archimedes used to construct a physical/mechanical model which "proved" by its construction and operation the needed principle and then used as guide to formalize it to mathematical symbolism.
Answer: Since:

classical mathematics seems to work, and
its a lot simpler than constructive mathematics, and
its still not clear to me how and in what sense my mathematics would be better if it were constructive,

for these reasons I'm sticking with classical mathematics for the moment.
On the other hand, I support constructive mathematics, in the sense that I think its great that people are working these things out.
Comment: classical maths = lots of paradoxes, here is one reason for you :)
Comment: @Nikos M.: there are no paradoxes in classical mathematics, as it's usually practiced, that aren't also present in constructive mathematics (e.g. Curry's paradox).
Answer: I think the only reason to not be a constructivist is that it is more restrictive methodologically and that the restriction isn't worth the trouble. I think the better question is what are the positive arguments in favor being a non-constructivist--besides that it is easier. For example, trivial mathematics (one in which every mathematical statement is a theorem) is easier than classical mathematics, but no one argues in it's favor. (There are certainly better examples than this but they escape me at the moment.)
There are lots of positive arguments in favor of constructive mathematics, which seem point to the the hassell being worth it.
I would check out: https://plato.stanford.edu/entries/mathematics-constructive/ and take a look at Brouwerian counterexamples.


Unit testing...should it be used here?

Question: Duplicate: https://stackoverflow.com/questions/135651/learning-unit-testing

I'm trying to develop some software for my research group to analyze and plot experimental data.  I would like to make it where it's pretty error free.  Would this be a situation for unit testing?  If so could you possibly point me to some good references for unit testing?
Comment: duplicate: http://stackoverflow.com/questions/135651/learning-unit-testing
Comment: Gortok, I would like to think its not a duplicate because I'm not asking just how to do it but more on if this is an applicable situation for it to be used.
Comment: I don't think its a dupe, its specific to Casey's problem.
Comment: @Casey: Your question 'some good references for unit testing' is a duplicate. You'll find your answer there.
Answer: Pretty much any code is a good candidate for unit testing; it will help you document the intent of your code, and prove that your code works as intended.  It will definitely help you find bugs before releasing your code to the rest of your group.  You don't say what platform you're using, so I can't recommend a testing framework, but I can recommend Kent Beck's excellent Test Driven Development: By Example as a good general starting place.
Comment: MattK, its going to be for windows.  Doing it in Python.  Thanks for your help :)
Answer: From my experience, unit tests are a great idea for any functionality that is not UI-related (like "is the number displayed in red if it's a negative value") in helping you to find bugs as early as possible. Thus I'd recommend writing unit tests whenever possible (and have them run automatically, e.g. nightly or even after each build, to see if some new piece of code broke anything).
Comment: even as required step before 'SVN-checkins'
Answer: So your application needs to analyze data? Well that sounds like a test can be writen.
e.g. if you data always scores 5.25 on a Wednesday.
You could write a test.
void CheckScoreOnWeds()
{
     Assert.AreEqual( 5.25, DataAnalyzer.CalcScore(Day.Wednesday));
}

and then write your class
class DataAnalyzer
{
    public double CalcScore( DayOfWeek Day)
    {
          //complex stuff
          return 5.25
    }
}

There you have a unit test.

Unit testing...should it be used here?


finding the Y coordinate of a dot on a linear-function straight line

Question: I have a straight line on a graph and three dots: A, B and C.
I know that dot A's coordinates are A (3,5; 5), and the dot C's coordinates are C (7; 6).
However, I only know the first coordinate of dot B: B (5; ?).
How can I find out the dot B's second coordinate?
Comment: What do the semicolons mean? Why is $A$ $3$-dimensional but $C$ is 2-dimensional, yet you claim there is a line between $A$ and $C$? Do you mean $A=(3,5)$ and $C=(7,6)$?
Comment: @Dastur I meant that A's x is 3,5 and A's y is 5. Sorry, I am not a native English speaker. I used notations accepted in my first language.
Answer: I suppose that $A,B,C$ are points on the line with the equation $y=mx+b.$
From $A$ amd $C$ we get the equations
$5=3.5m+b$ amd $6=7m+b.$
Now compute $m$ and $b$.
Then we get the second coordinate of $B$ by $?=5m+b.$


Is it a good idea to chmod my Python site-packages directory to 777?

Question: I use Python on Linux and OS X, and I'm trying to think of a good reason not to chmod my Python site-packages directory to 777.  It seems like that is better to do than sudoing every time I want to make the slightest modification.  Or have I gone crazy?  Note that this is primarily for my development machines and not any kind of production servers.
Disclaimer:  Yes, I know the caveats.  It's bad to pip install or easy_install things that are provided by a package manager.  And it's better to use a virtualenv than modify the global Python installation in most cases.
Answer: If that's your machine then you may as well do whatever suits you.  My main reason for leaving permissions like they are is that it means I'm less likely to destroy something by accident.
It's really down to what level of responsibility you want to take, if it's your own box and you're happy that you won't run malware and won't trash anything by accident there's no decent reason not to.
The only other concern I'd have is that if I were developing a package and wanted to test it and its deployment in real life conditions I wouldn't be able to since everything's writable.
I do know some security experts who'd disagree, but ultimately security should be balanced with usability.  At one talk I was at a security guy was insisting that the operating system should be changed to simply not allow users to do certain things.  Luckily at that point someone piped up with 'I'm sorry Dave, I can't let you do that'...
Comment: My concern is that setting everything to 777 could lead to goofy things down the road due to installer and permission fix assumptions, and altering them can create troubleshooting issues on my own machine...altering permissions can be a nightmare to move back to a known-good state unless the built-in repair permissions will fix it.
Comment: I agree. I'd have similar worries and that's the another reason that I haven't done it myself.
Answer: It's not really a good idea. 777 means any user can write modules, including, say, a web server user being controlled by a compromised webapp script. If that user can write a py or pyc to site-packages which then gets imported by another user such as root, your low-privilege compromise is escalated to a serious machine-level compromise. If you're so sure that your machine is safe from all attack that this is acceptable, fine... but if that's the case then you might as well just be running everything as root really!
Better: if you want modules that only your user has access to and can update without having to sudo, add a user-specific module path. You can do this with PYTHONPATH or by modifying sys.path, but from Python 2.6 that isn't necessary as you get one by default, ~/.local/lib/python2.6/site-packages. See PEP 370 for details.
Comment: I've tried going the local packages route before, but it ended up causing too much confusion as far as what package was installed where.  If I want to isolate things, I'll just use a virtualenv instead.


Trouble joining Windows Server 2008 to Domain

Question: When I try to join my new server to my existing domain I get the following error:
"An attempt to resolve the DNS name of a DC in the domain being joined has failed.  Please verify this client is configured to reach a DNS server that can resove DNS names in the target domain."
I have tried all of the following already:
Successfully pinged the domain controller.
Ping the new server from the domain controller by IP address and by DNS name.
Ping the DC server from the new server by IP address and by DNS name.
Changed the network to DHCP (it was originally static).  No joy as static or DHCP.
Turned off all firewall settings.
Added the domain name to 'hosts' file.
Added the server name of the primary domain controller to the 'hosts' file in the new server.
Any ideas?  Thanks in advance for any help!
Jim
Update:  With help from J. Brian Kelly (Thanks) I have managed to narrow down the problem to a DNS issue.  Specifically, UDP/53 packets are being sent (they are seen in Network Monitor), but are not getting to the DNS server.  But, I do not yet know why.
Update: The quested output from IPCONFIG for the HyperV host and the virtual machine.
IPCONFIG from HyperV Server
<code> Windows IP Configuration
 Host Name . . . . . . . . . . . . : HYPER
 Primary Dns Suffix  . . . . . . . : sfi-wfc.com
 Node Type . . . . . . . . . . . . : Hybrid
 IP Routing Enabled. . . . . . . . : No
 WINS Proxy Enabled. . . . . . . . : No
 DNS Suffix Search List. . . . . . : sfi-wfc.com

 Ethernet adapter Local Area Connection 4:

 Connection-specific DNS Suffix  . :
 Description . . . . . . . . . . . : Primary Network
 Physical Address. . . . . . . . . : 00-30-48-CA-CC-7A
 DHCP Enabled. . . . . . . . . . . : No
 Autoconfiguration Enabled . . . . : Yes
 Link-local IPv6 Address . . . . . : fe80::cd16:3ac2:3d4f:e275%679(Preferred)
 IPv4 Address. . . . . . . . . . . : 192.168.100.1(Preferred)
 Subnet Mask . . . . . . . . . . . : 255.255.255.0
 Default Gateway . . . . . . . . . : 192.168.100.10
 DHCPv6 IAID . . . . . . . . . . . : -1476382648
 DHCPv6 Client DUID. . . . . . . . : 00-01-00-01-12-10-20-E9-00-30-48-CA-CC-7A
 DNS Servers . . . . . . . . . . . : 192.168.100.5
 NetBIOS over Tcpip. . . . . . . . : Enabled

 Ethernet adapter Local Area Connection 3:

 Media State . . . . . . . . . . . : Media disconnected
 Connection-specific DNS Suffix  . : sfi
 Description . . . . . . . . . . . : Intel(R) 82576 Gigabit Dual Port Network Connection #2
 Physical Address. . . . . . . . . : 00-30-48-CA-CC-7B
 DHCP Enabled. . . . . . . . . . . : Yes
 Autoconfiguration Enabled . . . . : Yes
</code>
IPCONFIG from Virtual Machine
<code> Windows IP Configuration
 Host Name . . . . . . . . . . . . : DB
 Primary Dns Suffix  . . . . . . . :
 Node Type . . . . . . . . . . . . : Hybrid
 IP Routing Enabled. . . . . . . . : No
 WINS Proxy Enabled. . . . . . . . : No
 DNS Suffix Search List. . . . . . : sfi

 Ethernet adapter Local Area Connection 2:

 Connection-specific DNS Suffix  . : sfi
 Description . . . . . . . . . . . : Microsoft Virtual Machine Bus Network Adapter
 Physical Address. . . . . . . . . : 00-15-5D-66-03-02
 DHCP Enabled. . . . . . . . . . . : Yes
 Autoconfiguration Enabled . . . . : Yes
 IPv4 Address. . . . . . . . . . . : 192.168.100.128(Preferred)
 Subnet Mask . . . . . . . . . . . : 255.255.255.0
 Lease Obtained. . . . . . . . . . : Saturday, August 29, 2009 10:44:45 AM
 Lease Expires . . . . . . . . . . : Tuesday, September 01, 2009 3:08:33 PM
 Default Gateway . . . . . . . . . : 192.168.100.10
 DHCP Server . . . . . . . . . . . : 192.168.100.5
 DNS Servers . . . . . . . . . . . : 192.168.102.5
 Primary WINS Server . . . . . . . : 192.168.100.5
 NetBIOS over Tcpip. . . . . . . . : Enabled

 Tunnel adapter Local Area Connection* 8:

 Media State . . . . . . . . . . . : Media disconnected
 Connection-specific DNS Suffix  . : sfi
 Description . . . . . . . . . . . : isatap.sfi
 Physical Address. . . . . . . . . : 00-00-00-00-00-00-00-E0
 DHCP Enabled. . . . . . . . . . . : No
 Autoconfiguration Enabled . . . . : Yes

 Tunnel adapter Local Area Connection* 9:

 Media State . . . . . . . . . . . : Media disconnected
 Connection-specific DNS Suffix  . :
 Description . . . . . . . . . . . : Teredo Tunneling Pseudo-Interface
 Physical Address. . . . . . . . . : 02-00-54-55-4E-01
 DHCP Enabled. . . . . . . . . . . : No
 Autoconfiguration Enabled . . . . : Yes
</code>
Comment: Please post output of command "ipconfig /all" on DC and server.
Answer: On Virtual Machine:

Change the network to static and type in these settings:
IPv4 - 192.168.100.128
Subnet Mask - 255.255.255.0
Default Gateway - 192.168.100.10
Preferred DNS Server - 192.168.100.5
In system properties, you must field the Primary DNS suffix of this computer with your domain name sfi-wfc.com and than tick the box Change primary DNS suffix when domain membership changes.
Restart Virtual Machine.
Use Fully Qualified Domain Name (sfi-wfc.com) instead of NetBIOS name when joining a domain.
Comment: I think this is right - the big issue is that your host and VM are pointed to different DNS servers - they should all point at the domain controller. Maybe you typo'd it but the VM's DNS is 102.5 instead of 100.5.
Answer: Can you ping the domain name itself? For instance, if your DC is MyDC.MyDomain.net, can you ping MyDomain.net? Do you see any errors in the DC's or server's system event log corresponding to when you attempt to join the server to the domain?
Comment: I can ping the domain name and the DNS server by name if I have them in the hosts file.
When I remove the entries fro the host file I can ping the DNS server by name, but not the domain name.
When I do nslookup on the DNS server by name it timesout, but gives me the address.
Comment: Neglected to say.. there are no error messeges in the Domain Controller.
Comment: Remove all entries from the hosts file. Verify your DNS settings for the NIC. If all that is right, I would do a network trace on both your server and the DNS server to figure out why DNS resolution is failing.
Comment: Entries are removed from host file.  Removed them as soon as I proved it did not help.
I can ping and tracert from the new server to the DC and the reverse with no trouble.
Current configuration is DHCP and I verified that all settings and addresses are good.
By network trace do yuo mean get Wireshark and do a capture?
Comment: Possible relavent fact..  New server is running as virtual under Hyper-V.  I had no trouble joining the Hyper-V host machine to the domain.
Comment: Yup, or Network Monitor. It'll do, too, and doesn't require the WinPCap driver install. That way you can see if your server is sending outbound udp/53 to the DNS server, if the DNS server is receiving and responding, and if your server is receiving the response.
Comment: When I went to download Network Monitor I was unable to use IE because it appears DNS not working for IE either.  I did manage to get NM loaded however.  Have not figured out filters yet, so I am seeing a lot of noise.  However, I am seeing a serveral UDP/53 message and have not seen response.
Comment: Next steop, I am in stalling NM on DNS machine to see if requests are reaching there.  But why on earth would they not?
Comment: I am seeing the UDP/53 packets leaving the new server.  Not seeing them coming into the DNS server.  Cannot imagine what that might be other than something on the Hyper-V Server.  Maybe a firewall setting, but why on earth would it block DNS?
Answer: Make sure that the new machine's virtual switch is properly set up.  If the firewall is off on all machines, (and it should be by this time) then the only thing left in the way (so to speak) is the vswitch.  the physical nic should have only the hyper v switch protocol enabled and the virtual port should not.
Answer: I had a similar issue. To resolve I had to change Virtual Network connection of the Hyper-V to use a Legacy Network Adapter.

Shut down VM
Open Hyper-V manager
on the VM settings remove the Network Adapter.
Add a Legacy Network Adapter
Restart VM and retry.


Do we have a problem of "pity upvotes"?

Question: I know, this may sound like it is off-topic, but hear me out.
At Stack Overflow and here we get votes on posts, this is all stored in a tabular form.
E.g.:

post id     voter id    vote type     datetime
-------     --------    ---------     --------
10          1           2             2000-1-1 10:00:01
11          3           3             2000-1-1 10:00:01
10          5           2             2000-1-1 10:00:01

... and so on. Vote type 2 is an upvote, vote type 3 is a downvote. You can query an anonymized version of this data at http://data.stackexchange.com
There is a perception that if a post reaches the score of -1 or lower it is more likely to be upvoted. This may be simply confirmation bias or it may be rooted in fact.
How would we analyze this data to confirm or deny this hypothesis? How would we measure the effect of this bias?
Comment: can we get an example of the query? Not everybody is well versed in writing SQL statements. Having sample data might encourage people to try to play with it. +1 for the question.
Comment: I've seen other kinds of sites obfuscate votes (i.e. add noise before displaying them) and sometimes even completely hide up- and down-votes for a short period, in order to avoid various forms of bandwagonning, pity  votes and other 'social' elements of voting.
Comment: @Jeff votes are anonymized you can only get partial info from the data dump, it does include all transitions though here is a quick sample http://data.stackexchange.com/stackoverflow/q/101738/ full anonymized data is available in the public data dump
Comment: Why just upvotes? How the probability of up- or down-voting splits around each particular value would be interesting surely?
Comment: @Bob, sure agree they would
Comment: What'd be even more interested would be to see if this effect (assuming it exists) still occurred if http://meta.stackexchange.com/questions/747/show-total-votes-or-up-down-votes was extended to all users who could down vote.
Comment: http://www.eecs.harvard.edu/cs286r/papers/DW08.pdf Could this (BTS Bayesian Truth Serum) be something to consider in the long run to improve the quality of votes? It might be too complicated though.
Answer: You could use a multistate model or Markov chain (the msm package in R is one way to fit these).  You could then look to see if the transition probability from -1 to 0 is greater than from 0 to 1, 1 to 2, etc.  You can also look at the average time at -1 compared to the others to see if it is shorter.
Comment: +1 great reference. There is an [article](http://www.jstatsoft.org/v38/i08/paper) in Journal of Statistical Software about msm package. The model seems ideally fitted for this kind of task.
Comment: The Markov chain model idea looks like a good one, but the average time at -1 won't give the whole story. It's possible (and plausible - think bad questions) that one is more likely to get downvoted at -1 than elsewhere too.
Comment: I guess what one may want to do first is cluster the vote-trajectories - those that get (almost) only up/downvoted (very popular/very bad questions), and those that are more contentious. Then you can do Markov chains on the three classes.
Answer: Summary of my answer. I like the Markov chain modeling but it misses the "temporal" aspect. On the other end, focusing on the temporal aspect (e.g. average time at $-1$) misses the "transition" aspect. I would go into the following general modelling (which with suitable assumption can lead to [markov process][1]). Also there is a lot of "censored" statistic behind this problem (which is certainly a classical problem of Software reliability ? ).  The last equation of my answer gives the maximum likelihood estimator of voting intensity (up with "+" and dow with "-") for a given state of vote. As we can see from the equation, it is an intermediate from the case when you only estimate transition probability and the case when you only measure time spent at a given state. Hope this help.
General Modelling (to restate the question and assumptions).
Let $(VD_i)_{i\geq 1}$ and $(S_{i})_{i\geq 1}$ be random variables modelling respectively the voting dates and the associated vote sign (+1 for upvote, -1 for downvote). The voting process is simply
$$Y_{t}=Y^+_t-Y^-_t$$ where
$$Y^+_t=\sum_{i=0}^{\infty}1_{VD_i\leq t,S_i=1} \;\text{ and } \;Y^-_t=\sum_{i=0}^{\infty}1_{VD_i\leq t,S_i=-1}$$
The important quantity here is the intentity of $\epsilon$-jump
$$\lambda^{\epsilon}_t=\lim_{dt\rightarrow 0} \frac{1}{dt} P(Y^{\epsilon}_{t+dt}-Y^{\epsilon}_t=1|\mathcal{F}_t) $$
where $\epsilon$ can be $-$ or $+$ and  $\mathcal{F}_t$ is a good filtration, in the genera case, without other knowledge it would be:
$$\mathcal{F}_t=\sigma \left (Y^+_t,Y^-_t,VD_1,\dots,VD_{Y^+_t+Y^-_t},S_{1},\dots,S_{Y^+_t+Y^-_t} \right )$$.
but along the lines of your question, I think you implicitly assume that
$$ P \left ( Y^{\epsilon}_{t+dt}-Y^{\epsilon}_t=1 | \mathcal{F}_t \right )= P \left (Y^{\epsilon}_{t+dt}-Y^{\epsilon}_t=1| Y_t \right ) $$
 This means that for $\epsilon=+,-$ there exists a deterministic sequence $(\mu^{\epsilon}_i)_{i\in \mathbb{Z}}$ such that $\lambda^{\epsilon}_t=\mu^{\epsilon}_{Y_t}$.
Within this formalism, you question can be restated as: "it likely that $ \mu^{+}_{-1} -\mu^{+}_{0}>0$ " (or at least is the difference larger than a given threshold).
Under this assumption, it is easy to show that $Y_t$ is an [homogeneous markov process][3] on $\mathbb{Z}$ with generator $Q$ given by
$$\forall i,j \in \mathbb{Z}\;\;\; Q_{i,i+1}=\mu^{+}_{i}\;\;  Q_{i,i-1}=\mu^{-}_{i}\;\; Q_{ii}=1-(\mu^{+}_{i}+\mu^{-}_{i}) \;\; Q_{ij}=0 \text{ if } |i-j|>1$$
Answering the question (through proposing a maximum likelihood estimatior for the statistical problem)
From this reformulation, solving the problem is done by estimating $(\mu^{+}_i)$ and building a test uppon its values. Let us fix and forget the $i$ index without loss of generality.  Estimation of $\mu^+$ (and $\mu^-$) can be done uppon the observation of
$(T^{1},\eta^1),\dots,(T^{p},\eta^p)$ where $T^j$ are the lengths of the $j^{th}$ of the $p$ periods spent in state $i$ (i.e. successive times with $Y_t=i$) and $\eta^j$ is $+1$ if the question was upvoted, $-1$ if it was downvoted and $0$ if it was the last state of observation.
If you forget the case with the last state of observation, the mentionned couples are iid from a distribution that depends on $\mu_i^+$ and $\mu_i^-$: it is distributed as $(\min(Exp(\mu_i^+),Exp(\mu_i^-)),\eta)$ (where Exp is a random var from an exponential distribution and $\eta$ is + or -1 depending on who realizes the max).
Then, you can use the following simple lemma (the proof is straightforward):
Lemma If $X_+\leadsto Exp(\mu_+)$ and $X_{-} \leadsto Exp(\mu_{-})$ then, $T=\min(X_+,X_-)\leadsto Exp(\mu_++\mu_-)$ and $P(X_+1<X_-)=\frac{\mu_+}{\mu_++\mu_-}$.
This implies that the density $f(t,\epsilon)$ of $(T,\eta)$ is given by:
$$ f(t,\epsilon)=g_{\mu_++\mu_-}\left ( \frac{1(\epsilon=+1)*\mu_++1(\epsilon=-1)*\mu_-}{\mu_++\mu_-}\right )$$
where $g_a$ for $a>0$ is the density function of an exponential random variable with parameter $a$. From this expression, it is easy to derive the maximum likelihood estimator of $\mu_+$ and $\mu_-$:
$$(\hat{\mu}_+,\hat{\mu}_-)=argmin \ln (\mu_-+\mu_+)\left ( (\mu_-+\mu_+)\sum_{i=1}^p T^i+p\right )-  p_-\ln\left (\mu_-\right ) -p_+ \ln \left (\mu_+\right )$$
where $p_-=|{i:\delta_i=-1}|$ and $p_+=|{i:\delta_i=+1}|$.
Comments for more advanced approaches
If you want to take into acount cases when $i$ is the last observed state (certainly smarter because when you go through  $-1$, it is often your last score...) you have to modify a little bit the reasonning. The corresponding censoring is relatively classical...
Possible other approache may include the possibility of

Having an intensity that decreases in with time
Having an intensity that decreases with the time spent since the last vote (I prefer this one. In this case there are classical way of modelling how the density decreases...
You may want to assume that $\mu_i^+$ is a smooth function of $i$
.... you can propose other ideas !
Answer: Conduct an experiment.  Randomly downvote half of the new posts at a particular time every day.
Comment: Actually we could do better than this ... using AB testing we could pick to display half of the -1 voted question on the site as 0 and half as -1 ... and see if either of the groups is more likely to be upvoted! Ingenious.
Comment: Cool, we should observe a significant increase in "critic" badges and probably a decrease in motivation for new users :-) Better to start with high-rep users, in this case (at risk of biasing the experiment!)
Comment: The experiment idea controls the quality of the posts, but (1) those being downgraded should agree in advance to participate in the experiment, and (2) after a brief time, the downgrades should be removed.
Comment: +1 (and +1 to all comments here, too): a controlled *reversible* experiment, communicated in advance to all users who might be affected and conducted with their approval, is one of the strongest ways to obtain this information.

Do we have a problem of "pity upvotes"?


Get the type name

Question: How i can get full right name of generic type?
For example:
This code
typeof(List<string>).Name

return

List`1

instead of
List<string>

How to get a right name?
typeof(List<string>).ToString()

returns System.Collections.Generic.List`1[System.String] but i want to get initial name:
List<string>

Is it real?
Comment: Is this specific to certain versions of .NET?
Answer: Use the FullName property.
typeof(List<string>).FullName

That will give you the namespace + class + type parameters.
What you are asking for is a C# specific syntax. As far as .NET is concerned, this is proper:
System.Collections.Generic.List`1[System.String]

So to get what you want, you'd have to write a function to build it the way you want it. Perhaps like so:
static string GetCSharpRepresentation( Type t, bool trimArgCount ) {
    if( t.IsGenericType ) {
        var genericArgs = t.GetGenericArguments().ToList();

        return GetCSharpRepresentation( t, trimArgCount, genericArgs );
    }

    return t.Name;
}

static string GetCSharpRepresentation( Type t, bool trimArgCount, List<Type> availableArguments ) {
    if( t.IsGenericType ) {
        string value = t.Name;
        if( trimArgCount && value.IndexOf("`") > -1 ) {
            value = value.Substring( 0, value.IndexOf( "`" ) );
        }

        if( t.DeclaringType != null ) {
            // This is a nested type, build the nesting type first
            value = GetCSharpRepresentation( t.DeclaringType, trimArgCount, availableArguments ) + "+" + value;
        }

        // Build the type arguments (if any)
        string argString = "";
        var thisTypeArgs = t.GetGenericArguments();
        for( int i = 0; i < thisTypeArgs.Length && availableArguments.Count > 0; i++ ) {
            if( i != 0 ) argString += ", ";

            argString += GetCSharpRepresentation( availableArguments[0], trimArgCount );
            availableArguments.RemoveAt( 0 );
        }

        // If there are type arguments, add them with < >
        if( argString.Length > 0 ) {
            value += "<" + argString + ">";
        }

        return value;
    }

    return t.Name;
}

For these types (with true as 2nd param):
typeof( List<string> ) )
typeof( List<Dictionary<int, string>> )

It returns:
List<String>
List<Dictionary<Int32, String>>

In general though, I'd bet you probably don't need to have the C# representation of your code and perhaps if you do, some format better than the C# syntax would be more appropriate.
Comment: Adam, your code is incorrect. Try it with class C { public class D { } } and GetCSharpRepresentation(typeof(C.D)).  You don't get the C# representation.
Comment: Output: System.Collections.Generic.List`1[[System.String, mscorlib, Version=18.104.22.168, Culture=neutral, PublicKeyToken=b77a5c561934e089]]
Comment: Already updated nobugz (his clarifications weren't there originally) :)
Comment: So just a nested type and a nested type where the base type has type arguments? Given an understanding of *why* he'd do this silly thing anyway, I don't doubt there's little legitimate use for this code in the first place, let alone a full functional "get c# representation of a type name" function.
Comment: Yuck. Heh, for completeness' sake I went ahead and updated the sample to handle nested types (both generic and non-generic). It appears to work in all my scenarios.
Comment: typeof( Stupid.Stupider ) gives me Stupid+Stupider and typeof( Dictionary.KeyCollection ) gives me Dictionary+KeyCollection
Comment: Though using nested types seems to defeat the original desire, which is to match a C# type definition, which this certainly does not do (w/ nested types), since there is no succinct way to represent a nested type in C#.
Answer: You could use this:
public static string GetTypeName(Type t) {
  if (!t.IsGenericType) return t.Name;
  if (t.IsNested && t.DeclaringType.IsGenericType) throw new NotImplementedException();
  string txt = t.Name.Substring(0, t.Name.IndexOf('`')) + "<";
  int cnt = 0;
  foreach (Type arg in t.GetGenericArguments()) {
    if (cnt > 0) txt += ", ";
    txt += GetTypeName(arg);
    cnt++;
  }
  return txt + ">";
}

For example:
static void Main(string[] args) {
  var obj = new Dictionary<string, Dictionary<HashSet<int>, int>>();
  string s = GetTypeName(obj.GetType());
  Console.WriteLine(s);
  Console.ReadLine();
}

Output:
Dictionary<String, Dictionary<HashSet<Int32>, Int32>>

Comment: This is incorrect for the same reason that Adam's code is incorrect; you haven't accounted for how the CLR represents nested generic types.
Comment: Doesn't work for complex generic types
Answer: If you have an instance of the list, you can call .ToString() and get the following
System.Collections.Generic.List`1[System.String]

This is in addition to the methods provided by the other answers directly against the type rather than the instance.
Edit: On your edit, I do not believe it is possible without providing your own parsing method, as List<string> is C# shorthand for how the type is implemented, sort of like if you wrote typeof(int).ToString(), what is captured is not "int" but the CTS name, System.Int32.
Answer: Here's my implementation, which benefited from @Hans's answer above and @Jack's answer on a duplicate question.
public static string GetCSharpName( this Type type )
{
    string result;
    if ( primitiveTypes.TryGetValue( type, out result ) )
        return result;
    else
        result = type.Name.Replace( '+', '.' );

    if ( !type.IsGenericType )
        return result;
    else if ( type.IsNested && type.DeclaringType.IsGenericType )
        throw new NotImplementedException();

    result = result.Substring( 0, result.IndexOf( "`" ) );
    return result + "<" + string.Join( ", ", type.GetGenericArguments().Select( GetCSharpName ) ) + ">";
}

static Dictionary<Type, string> primitiveTypes = new Dictionary<Type, string>
{
    { typeof(bool), "bool" },
    { typeof(byte), "byte" },
    { typeof(char), "char" },
    { typeof(decimal), "decimal" },
    { typeof(double), "double" },
    { typeof(float), "float" },
    { typeof(int), "int" },
    { typeof(long), "long" },
    { typeof(sbyte), "sbyte" },
    { typeof(short), "short" },
    { typeof(string), "string" },
    { typeof(uint), "uint" },
    { typeof(ulong), "ulong" },
    { typeof(ushort), "ushort" },
};

Answer: Another way to get a nice type name by using an extension:
typeof(Dictionary<string, Dictionary<decimal, List<int>>>).CSharpName();
// output is:
// Dictionary<String, Dictionary<Decimal, List<Int32>>>

The Extension Code:
public static class TypeExtensions
{
   public static string CSharpName(this Type type)
   {
       string typeName = type.Name;

       if (type.IsGenericType)
       {
           var genArgs = type.GetGenericArguments();

           if (genArgs.Count() > 0)
           {
               typeName = typeName.Substring(0, typeName.Length - 2);

               string args = "";

               foreach (var argType in genArgs)
               {
                   string argName = argType.Name;

                   if (argType.IsGenericType)
                       argName = argType.CSharpName();

                   args += argName + ", ";
               }

               typeName = string.Format("{0}<{1}>", typeName, args.Substring(0, args.Length - 2));
           }
       }

       return typeName;
   }
}

Answer: typeof(List<string>).ToString()

Comment: Output: System.Collections.Generic.List`1[System.String]
Answer: An improvement on Adam Sills's answer that works with non-generic nested types, and generic type definitions:
public class TypeNameStringExtensions
{
    public static string GetCSharpRepresentation(Type t)
    {
        return GetCSharpRepresentation(t, new Queue<Type>(t.GetGenericArguments()));
    }
    static string GetCSharpRepresentation(Type t, Queue<Type> availableArguments)
    {
        string value = t.Name;
        if (t.IsGenericParameter)
        {
            return value;
        }
        if (t.DeclaringType != null)
        {
            // This is a nested type, build the parent type first
            value = GetCSharpRepresentation(t.DeclaringType, availableArguments) + "+" + value;
        }
        if (t.IsGenericType)
        {
            value = value.Split('`')[0];

            // Build the type arguments (if any)
            string argString = "";
            var thisTypeArgs = t.GetGenericArguments();
            for (int i = 0; i < thisTypeArgs.Length && availableArguments.Count > 0; i++)
            {
                if (i != 0) argString += ", ";

                argString += GetCSharpRepresentation(availableArguments.Dequeue());
            }

            // If there are type arguments, add them with < >
            if (argString.Length > 0)
            {
                value += "<" + argString + ">";
            }
        }

        return value;
    }

    [TestCase(typeof(List<string>), "List<String>")]
    [TestCase(typeof(List<Dictionary<int, string>>), "List<Dictionary<Int32, String>>")]
    [TestCase(typeof(Stupid<int>.Stupider<int>), "Stupid<Int32>+Stupider<Int32>")]
    [TestCase(typeof(Dictionary<int, string>.KeyCollection), "Dictionary<Int32, String>+KeyCollection")]
    [TestCase(typeof(Nullable<Point>), "Nullable<Point>")]
    [TestCase(typeof(Point?), "Nullable<Point>")]
    [TestCase(typeof(TypeNameStringExtensions), "TypeNameStringExtensions")]
    [TestCase(typeof(Another), "TypeNameStringExtensions+Another")]
    [TestCase(typeof(G<>), "TypeNameStringExtensions+G<T>")]
    [TestCase(typeof(G<string>), "TypeNameStringExtensions+G<String>")]
    [TestCase(typeof(G<Another>), "TypeNameStringExtensions+G<TypeNameStringExtensions+Another>")]
    [TestCase(typeof(H<,>), "TypeNameStringExtensions+H<T1, T2>")]
    [TestCase(typeof(H<string, Another>), "TypeNameStringExtensions+H<String, TypeNameStringExtensions+Another>")]
    [TestCase(typeof(Another.I<>), "TypeNameStringExtensions+Another+I<T3>")]
    [TestCase(typeof(Another.I<int>), "TypeNameStringExtensions+Another+I<Int32>")]
    [TestCase(typeof(G<>.Nested), "TypeNameStringExtensions+G<T>+Nested")]
    [TestCase(typeof(G<string>.Nested), "TypeNameStringExtensions+G<String>+Nested")]
    [TestCase(typeof(A<>.C<>), "TypeNameStringExtensions+A+C<D>")]
    [TestCase(typeof(A<int>.C<string>), "TypeNameStringExtensions+A<Int32>+C<String>")]
    public void GetCSharpRepresentation_matches(Type type, string expected)
    {
        string actual = GetCSharpRepresentation(type);
        Assert.AreEqual(expected, actual);
    }

    public class G<T>
    {
        public class Nested { }
    }

    public class A
    {
        public class C<D> { }
    }

    public class H<T1, T2> { }

    public class Another
    {
        public class I<T3> { }
    }
}

public class Stupid<T1>
{
    public class Stupider<T2>
    {
    }
}

I also chose to forgo his trimArgCount, as I can't see when that would be useful, and to use a Queue<Type> since that was the intent (pulling items off the front while they exist).
Answer: I had problems with the other answers in some instances, i.e. with arrays, so I ended up writing yet another one. I don't use the text from Type.Name or similar except to get the plain name of the types, because I don't know if the format is guaranteed to be the same across different .Net versions or with other implementations of the libraries (I assume it isn't).
///
/// For the given type, returns its representation in C# code.
///
/// <param name="type">The type.</param>
/// <param name="genericArgs">Used internally, ignore.</param>
/// <param name="arrayBrackets">Used internally, ignore.</param>
/// <returns>The representation of the type in C# code.</returns>

public static string GetTypeCSharpRepresentation(Type type, Stack<Type> genericArgs = null, StringBuilder arrayBrackets = null)
{
    StringBuilder code = new StringBuilder();
    Type declaringType = type.DeclaringType;

    bool arrayBracketsWasNull = arrayBrackets == null;

    if (genericArgs == null)
        genericArgs = new Stack<Type>(type.GetGenericArguments());

    int currentTypeGenericArgsCount = genericArgs.Count;
    if (declaringType != null)
        currentTypeGenericArgsCount -= declaringType.GetGenericArguments().Length;

    Type[] currentTypeGenericArgs = new Type[currentTypeGenericArgsCount];
    for (int i = currentTypeGenericArgsCount - 1; i >= 0; i--)
        currentTypeGenericArgs[i] = genericArgs.Pop();

    if (declaringType != null)
        code.Append(GetTypeCSharpRepresentation(declaringType, genericArgs)).Append('.');

    if (type.IsArray)
    {
        if (arrayBrackets == null)
            arrayBrackets = new StringBuilder();

        arrayBrackets.Append('[');
        arrayBrackets.Append(',', type.GetArrayRank() - 1);
        arrayBrackets.Append(']');

        Type elementType = type.GetElementType();
        code.Insert(0, GetTypeCSharpRepresentation(elementType, arrayBrackets : arrayBrackets));
    }
    else
    {
        code.Append(new string(type.Name.TakeWhile(c => char.IsLetterOrDigit(c) || c == '_').ToArray()));

        if (currentTypeGenericArgsCount > 0)
        {
            code.Append('<');
            for (int i = 0;  i < currentTypeGenericArgsCount;  i++)
            {
                code.Append(GetTypeCSharpRepresentation(currentTypeGenericArgs[i]));
                if (i < currentTypeGenericArgsCount - 1)
                    code.Append(',');
            }
            code.Append('>');
        }

        if (declaringType == null  &&  !string.IsNullOrEmpty(type.Namespace))
        {
            code.Insert(0, '.').Insert(0, type.Namespace);
        }
    }

    if (arrayBracketsWasNull  &&  arrayBrackets != null)
        code.Append(arrayBrackets.ToString());

    return code.ToString();
}

I have tested it with crazy types like this, and so far it has worked perfectly:
class C
{
    public class D<D1, D2>
    {
        public class E
        {
            public class K<R1, R2, R3>
            {
                public class P<P1>
                {
                    public struct Q
                    {
                    }
                }
            }
        }
    }
}

type = typeof(List<Dictionary<string[], C.D<byte, short[,]>.E.K<List<int>[,][], Action<List<long[][][,]>[], double[][,]>, float>.P<string>.Q>>[][,][,,,][][,,]);

// Returns "System.Collections.Generic.List<System.Collections.Generic.Dictionary<System.String[],Test.Program.C.D<System.Byte,System.Int16[,]>.E.K<System.Collections.Generic.List<System.Int32>[,][],System.Action<System.Collections.Generic.List<System.Int64[][][,]>[],System.Double[][,]>,System.Single>.P<System.String>.Q>>[][,][,,,][][,,]":
GetTypeCSharpRepresentation(type);

There may still be some gotchas I didn't think about, but there's a known one: to retrieve the names, I only get characters that meet the condition char.IsLetterOrDigit(c) || c == '_' until one that doesn't is found, so any names of types that use allowed characters that don't meet the condition will fail.
Answer: Came across this and thought I'd share my own solution. It handles multiple generic arguments, nullables, jagged arrays, multidimensional arrays, combinations of jagged/multidimensional arrays, and any nesting combinations of any of the above. I use it mainly for logging so that it's easier to identify complicated types.
public static string GetGoodName(this Type type)
{
    var sb = new StringBuilder();

    void VisitType(Type inType)
    {
        if (inType.IsArray)
        {
            var rankDeclarations = new Queue<string>();
            Type elType = inType;

            do
            {
                rankDeclarations.Enqueue($"[{new string(',', elType.GetArrayRank() - 1)}]");
                elType = elType.GetElementType();
            } while (elType.IsArray);

            VisitType(elType);

            while (rankDeclarations.Count > 0)
            {
                sb.Append(rankDeclarations.Dequeue());
            }
        }
        else
        {
            if (inType.IsGenericType)
            {
                var isNullable = inType.IsNullable();
                var genargs = inType.GetGenericArguments().AsEnumerable();
                var numer = genargs.GetEnumerator();

                numer.MoveNext();

                if (!isNullable) sb.Append($"{inType.Name.Substring(0, inType.Name.IndexOf('`'))}<");

                VisitType(numer.Current);

                while (numer.MoveNext())
                {
                    sb.Append(",");
                    VisitType(numer.Current);
                }

                if (isNullable)
                {
                    sb.Append("?");
                }
                else
                {
                    sb.Append(">");
                }
            }
            else
            {
                sb.Append(inType.Name);
            }
        }
    }

    VisitType(type);

    var s = sb.ToString();

    return s;
}

This:
typeof(Dictionary<int?, Tuple<string[], List<string[][,,,]>>>).GetGoodName()

...returns this:
Dictionary<Int32?,Tuple<String[],List<String[][,,,]>>>

Answer: If you want the base generic type used:
List<string> lstString = new List<string>();
Type type = lstString.GetType().GetGenericTypeDefinition();

Assuming that you want to use the type do do something and that you don't really need the actual string definition which isn't all that useful.

Get the type name


Close main application if "helper" application closed

Question: I have a wrapper application, which opens an other application, let's call it helper app. This app is inside the wrapper application Resource folder.
I would like to close the main application, after the helper app was closed. How can I achieve this?
I would like to also know, how can I quit the wrapper app, after the helper opened.
Comment: Are you developing for OSX or iOS?
Comment: Sorry, I forgot to mention, I develop for OSX.
Answer: Are you developing for OSX (10.6 and later ) ?
In this case use NSRunningApplication to terminate the wrapper application.
<code>@implementation AppDelegate // Helper Application delegate
- (void)applicationWillTerminate:(NSNotification *)aNotification
{
    NSArray *apps = [NSRunningApplication runningApplicationsWithBundleIdentifier:@"com.yourApplication.Launcher"];
    if ([apps count])
        [(NSRunningApplication *)[apps objectAtIndex:0] terminate];
}
@end
</code>
And you can launch your Helper synchronously with NSWorkspace :
<code>- (void)launchHelper // Wrapper launch method
{
    NSURL *helperURL = [[NSBundle mainBundle] URLForResource:@"Helper" withExtension:@"app"];
    if (helperURL)
    {
        NSError *err = nil;

        [[NSWorkspace sharedWorkspace] launchApplicationAtURL:helprURL options:NSWorkspaceLaunchAllowingClassicStartup configuration:nil error:&err];
        // here Helper 'main' have been called
    }
}
</code>
Answer: short answer - you can't!
Every application work in sandbox mode. You can call other application but you lose control on your (of course you can use AppDelegate standard method to handle enter/back foreground/bacground actions but that's it).
Comment: Thanks for your answer. I go then with the post which I marked accepted, which quits the wrapper app after it started the helper app.


Find the number of positive integral solutions of the equation $\frac{1}{x} + \frac{2}{y} = \frac{1}{4}$

Question: Find the number of positive integral solutions of the equation
$$\frac{1}{x} + \frac{2}{y} = \frac{1}{4}$$
My attempt:
$$\begin{align}
y+2x&=\frac{xy}{4} \\
4y+8x &= xy \\
8x &= y(x-4) \\
\end{align}$$
How can i proceed?
Comment: Use [SFFT](https://artofproblemsolving.com/wiki/index.php/Simon%27s_Favorite_Factoring_Trick) to factor $xy-8x-4y = 0$.
Answer: From $4y+8x=xy$ we have $xy-4y-8x=0\implies(x-4)(y-8)=32$. Note that $-32=1\cdot32, -\cdot16, \dots,-1\cdot-32,-2\cdot-16\dots$ Use this to solve for $x$ and $y$. You will find that there are $12$ solutions in total.
Comment: You should have $-8x$, which means your equations are slightly off from then on
Comment: Please strive not to post more (dupe) answers to dupes of FAQs, cf. recent site policy announcement [here.](https://math.meta.stackexchange.com/q/33508/242)
Answer: Multiplying by $4xy$ gives $0 = xy - 8x - 4y = (x - 4)(y - 8) - 32$ so that
$$(x - 4)(y - 8) = 32 = 2^{5}.$$
There are $12$ solutions to this equation because there are $12$ solutions to the equation $a + b = 5$ (each of the two factors in the product $2^{5}$ must contribute some number of $2's$, and it must sum to $5$).
Comment: I'd say there are $6$ (nonnegative integer) solutions to $a+b=5$, and then the number of solutions $x,y$ is twice that.
Comment: Please strive not to post more (dupe) answers to dupes of FAQs, cf. recent site policy announcement [here.](https://math.meta.stackexchange.com/q/33508/242)


Taylor approximation to penalty function

Question: I'm reading through Fan's SCAD paper and I feel like I'm not getting a simple step. On page 1354 where he is talking about quadratic approximations to a penalty function he has
$$\left[\rho_\lambda(|\beta_j|)\right]' = \rho'_\lambda(|\beta_j|)\text{sgn}(\beta_j) \approx \left\{\rho'_\lambda(|\beta_{j0}|)/\beta_{j0}\right\}\beta_j$$
which I am comfortable with, but then he says $$\rho_\lambda(|\beta_j|) \approx \rho_\lambda(|\beta_{j0}|) + \dfrac{1}{2}\left\{\rho'_\lambda(|\beta_{j0}|)/\beta_{j0}\right\}(\beta_j^2-\beta_{j0}^2)$$ for $\beta_j \approx \beta_{j0}$. This looks pretty close to a 1st order taylor expansion about $\beta_{j0}$, but I'm not quite sure how the usual quadratic term (e.g. $(\beta_j - \beta_{j0})^2$) becomes the term above.
Comment: @whuber Yes, indeed. The $\approx$ sign can work miracles!
Comment: It looks like a *second* order Taylor expansion to me.
Comment: @Glen_b Hmmm, the (1/2) might be a mistake. The 1st-derivative has a $\beta_j$ at the end, so evaluated at $|\beta_{j0}|$ we get $|\beta_{j0}|\cdot (\beta_j -|\beta_{j0}|)$ and then they use $\beta_j \approx \beta_{j0}$ to get the difference of squares. But then again, why $|\beta_{j0}|\cdot \beta_j = \beta_j^2$? Where did the sign go?
Comment: @Alecos It's no mistake: it comes from $\beta_j \approx \frac{1}{2}(\beta_j + \beta_{j0}),$ whence $\beta_{j0}(\beta_j-\beta_{j0}) \approx \frac{1}{2}(\beta_j + \beta_{j0})(\beta_j-\beta_{j0}) = \frac{1}{2}(\beta_j^2 - \beta_{j0}^2).$
Comment: Ah, thank you kind sirs. That is indeed some fine trickery there.
Answer: As @Alecos_papadopoulos and @whuber pointed out in the comments:
$ \begin{align*} \rho_\lambda(|\beta_j|) &\approx \rho_\lambda(|\beta_{j0}|) + \left.\rho_\lambda(|\beta_j|)'\right|_{\beta_{j0}}(\beta_j-\beta_{j0}) \quad\text{By Taylor expansion}\\
&\approx \rho_\lambda(|\beta_{j0}|) + \left\{\rho_\lambda'(|\beta_{j0}|)/\beta_{j0}\right\}\beta_{j0}(\beta_j-\beta_{j0}) \quad\text{By above approximation}\\
&\approx \rho_\lambda(|\beta_{j0}|) + \tfrac{1}{2}\left\{\rho_\lambda'(|\beta_{j0}|)/\beta_{j0}\right\}(\beta_j^2-\beta_{j0}^2)
\end{align*}$
$\text{Where the last approximation holds because $\beta_j \approx \beta_{j0}$} \implies \beta_{j0} \approx \tfrac{1}{2}(\beta_j+\beta_{j0})\implies \beta_{j0}(\beta_j-\beta_{j0}) \approx \tfrac{1}{2}(\beta_j+\beta_{j0})(\beta_j-\beta_{j0}) = \tfrac{1}{2}(\beta_j^2-\beta_{j0}^2)$


Make a view or panel that displays image *or* video field if present

Question: My goal is to have a content type that will display an image in a certain panel pane or an embedded video, if the video is present.
I can imagine setting up two fields, one for the image and one for the video embed code. But I'm not sure how to hide the image if the video is present or to make the video field take precedence over the image field in panels.
Answer: It can be done with Views rewriting options.

Add both fields (Image before Video) to Views and exclude Image field from output.

For Video field set "NO RESULTS BEHAVIOR" to Image field token:

It means that if Video field is empty Views will get value from this textarea, which contains special placeholders (in this case [field_image]).
Available tokens for your fields can be found under "REWRITE RESULTS" fieldset:

Don't forget to uncheck "Rewrite the output of this field" flag.
Comment: Ah, that's a clever use of the rewrite field. I should have thought of that. Thanks for the detailed answer. I'll test it out soon.
Answer: Kalabro solution is good if you use a view with fields.
If you use a view with "content" you need to go to the content type -> Manage Display and hide image and video field.
Then in the node--YOURCONTENT.tpl.php you can write:
if ($field_image) {
 print $field_image;
}

if ($field_video) {
  print $field_video;
}

Of course you need to change the name of the variables I wrote.
Answer: It is done with writing the views tpl.By clicking on the theme option of view and you can check the value of your fields in your tpl files like Display Output,Style Output,etc..You can get the code of this tpl file by clicking on the output which you want to check like Display Output,Style Output,etc..Just like I click on the style Output and the code of the style output is displayed as shown in the image .Now you can save this file with the name as given in the figure1 in front of the tpl(Display Output,Style Output,etc.).Now you can save this in your enabled theme. for more information of view themeing and views tpl naming please see this. http://drupal.org/node/352970.Now you can check values of fields in this tpl and show as per your requirement. After making the tpl file and placing it in your enabled theme direcory.Now you can click on the rescan template files so that this file will be active and this filename will be shwoing in bold text.
if ($image) {
 print $image;
}
if ($video) {
  print $video;
}

you can change the name of fields($image,$video) above as you have.


Angular duplicate for milliseconds before render completely

Question: When I render my template this duplicate for milliseconds until compile cycle finish. Someone know how can solve it?
Using Angular Batarang I could see a lot of watchers (5k) and a large digest cycle.
Answer: Try the ngCloak directive.  From the docs: https://docs.angularjs.org/api/ng/directive/ngCloak

The ngCloak directive is used to prevent the Angular html template from being briefly displayed by the browser in its raw (uncompiled) form while your application is loading. Use this directive to avoid the undesirable flicker effect caused by the html template display.


Why noise in GAN's are random?

Question: I was learning about GAN's and how it can be used for creating images of cat, dog, mouse and bird. This is how I think in supervised learning system we train the features and labels to generate images.
cat,dog,mouse, bird = 0,1,2,3

X  Y
1  dog.jpg
3  bird.jpg
0  cat.jpg
0  cat1.jpg
.  .
.  .

train(X,Y)

after training for generating a image
predict(0) #generates cat image
predict(2) #generates mouse image

Because GAN is an unsupervised learning system it learns to generate images using adversarial training. What I have seen in others implementation of GANs is that they add a noise as an input to the generator. The noise is generally a continuous number between 0 and 1. Why do they add random number as noise? why cant they simply add some numbers for example cat,dog,mouse, bird = [0,1,2,3]?
Answer: The way you can think of noise is as an embedding which has information about the texture, the style, orientation etc. And the task of the generator is to use this embedding and figure out a way to map these embeddings to Image space.
As far as your questions go,if we only use label [0,1,2,3] you are making it a deterministic problem and forcing it to generate only one image. Thats not what we want from the GAN.We want to generate multiple images of the same class.
Comment: By embedding, do you also mean that in a topological sense? That would make sense how you'd take the attributes/information of the noise and to generate new images.

Why noise in GAN's are random?


Let $G$ be a finite matrix group in $GL_2(Q)$ such that every matrix $A\in G$ has integer entries. Prove $A^{12}= I$ for each $A$.

Question: Let $G$ be a finite matrix group in $GL_2(Q)$ (general linear group of $2$ by $2$ matrices with rational entries) such that every matrix $A\in G$ has integer entries. Prove that $A^{12} = I$ for every $A \in G$.
Attempt :
We have that $A^k = I$ for some natural $k$ since $G$ is finite. Then the minimal polynomial of $A$ divides $x^{k} - 1$. Also, the characteristic polynomial is of the form $x^2 + ax + b$ for some $a,b$. Thus, the minimal polynomial has either a root of the form $x-c$ where $c$ is an integer, or it is the characteristic polynomial itself. In the first case, we get $A = I$ or $A =-I$ since $1,-1$ are the only integer roots of unity. Hence $A^2 = I$.
In the second case, we have that either the roots of the characteristic polynomial are $1,-1$ in which case we get $x^2 - 1$, so $A^2 = I$ again. Otherwise, we have a complex root of unity and it's conjugate. This gives us $b = 1$ as it is the product of these roots, and $a$ is $2 *$ the real part. Hence we get $A^2 + aA + I = 0 $ so $A(A + aI) = -I$. How do I use this to show $A^{12} = I$?
Answer: We also know that $a$ is an integer. Suppose that the root of unity $\omega$ is a root of $x^2 + ax + b$. Then we know that $2 \operatorname{Re}(\omega) = a$. But we have that $-1 \leq \operatorname{Re}(\omega) \leq 1$, and so we have that $-2 \leq a \leq 2$.
We know just consider all of the possible cases.
If $a = \pm 2$, then we have that $\omega = \pm 1$, which you have already dealt with.
If $a = 0$, then we have that $\omega = i$, which is a fourth root of unity. Note that we do not have that the minimal polynomial divides $x^6 - 1$, but it does divide $x^{12} - 1$.
If $a = -1$, then the characteristic polynomial is $x^2 - x + 1$, and $\omega$ is a sixth root of unity. (We have that $x^2 - x + 1 \mid x^3 + 1 \mid x^6 - 1$.)
If $a = 1$, then the characteristic polynomial is $x^2 + x + 1$, and $\omega$ is a third root of unity.
Notice above that if the minimal polynomial is $x^2 + 1$, then we do not have that $A^6 = 1$. This can in fact occur. Consider for example the matrix
$$
  \begin{pmatrix}
    0 & -1 \\
    1 & 0
  \end{pmatrix}
$$
Thus the problem as it currently stands is not true, but your original version before you edited it was correct. The exponent does need to be $12$.
Comment: How do we know $a$ is an integer?
Edit : Sorry, I'll change it back to 12.


dataset .net cannot resolve on java web service client

Question: I have a web service built in .NET with a dataset as input parameter and another dataset as a response. I need to consume it from java but this does not work.
Eclipse show:
<code>   Description  Resource    Path    Location    Type
DsClient cannot be resolved to a type   ServiceSoap12Stub.java  /xxxx/src/org/tempuri   line 169    Java Problem
</code>
Netbeans show:
Answer: The straight and easy answer is that DataSet should never be used for data exchange in open services. So the provider of this non service should provide an API which could be used.
The fact that one can export a service with a click (or wizard, or tool ... ) does not mean that he should not plan carefully how that service will be consumed.
Even succeeding in operating such a service is a workaround in my opinion.
That being said, it seems that you are not using the full definition of the service. WSDL could be provided as single file or split in many, often keeping schema information in a separate file.
You should be certain to be able to process all files related to the service.
Analyze the WSDL, there should schemas reference on it, check if those .xsd are available and see if they to refer to other non standard schema.
If you are still stuck, publish the whole WSDL (maybe on some GIST or pastebin) so that we can check and see if something is amiss.
As I said before, the only true solution to this problem lies with the provider of the service, he should really provide a more interoperable API.
Comment: Thank for your answer, Maybe the best way to solve this is changing dataset to a class ?
Comment: Absolutely, you should use plain objects as data, only fields with possibly just getters and setters.


Prove using combinatorics $\sum\limits_{r=0}^n r^2\binom{n}{r}=n(n+1)*2^{n-2}$.

Question: Prove using combinatorics $\sum\limits_{r=0}^n  r^2\binom{n}{r}=n(n+1)*2^{n-2}$.
The left side is choosing $r$ persons from $n$ persons and make one leader and one co-leader such that the leader and the co-leader can be the same.But then the left side should be choose a leader and co-leader and  then choose the other which makes the left side $n^2*2^{n-2}$ where did I make a mistake?
Comment: If leader and co-leader are the same person, you get $2^{n-1}$ ways to build your team
Answer: It's easier if you rewrite the right side as $n(n-1)2^{n-2} + n2^{n-1}$, then count the two cases separately (leader and co-leader are same, or different.)
Answer: The reasoning for the right hand side is wrong, when you are choosing the leader and then the co-leader you are considering it as n^2 cases and then for choosing the other members you are considering 2^(n-2) ways, however if the leader and coleader are same then there are 2^(n-1) ways to choose the team and if they are different then there are 2^(n-2) ways to choose the team, so you will have to break it up into two cases as suggested by @Thomas Andrews


Perturbation Methods-Multiscale expansions

Question: I was looking at some of the problems from the chapter Multiple-scale expansion in Introduction to Perturbation Methods by Mark H. Holmes. I came across this question to find the first term expansion:
$\epsilon y''+\epsilon y'+y=cos(t)$, where
$y(0)=0=y'(0)$. I took my slow and fast scale variables as $t_1=t$ and $t_2=\sqrt{\epsilon}t$. My question arises when we have to find the $O(1)$ expansion of the term.I'm aware that I need to use Taylors expansion, but something doesn't seem to fit quiet properly.
 It would be great if someone could help me out with this.
Comment: What section is this example from and what is the stated aim this example is to demonstrate? What is the approach discussed in that section?
Comment: This is from Chapter 3, Multiple Scales method, Section 3.2, question 3.1(a). The question asks us to find the first term expansion.@LutzL
Answer: What you should get an approximation for is depicted in the following plot of numerical solutions for some perturbation parameters.

This picture corresponds to some extended understanding of "boundary layer", as there is indeed some rapid compensation for the gap between the value $1$ at $t=0$ of the outer solution $y_{\rm outer}(t)=\cos(t)$ and the initial condition $y(0)=0$. This first segment has indeed also a width of $\sim\sqrt{ϵ}$, but then overshoots the outer solution and oscillates with frequency $1/\sqrt{ϵ}$, dampened by the friction term containing the first derivative giving a uniform hull curve for the amplitude of the oscillation of $e^{-t/2}$. Taking these building blocks to first satisfy $y(0)=0$ and then also $y'(0)=0$ gives the first order approximation
$$
y(t)\approx \cos(t)-e^{-t/2}\left(\cos\left(\frac{t}{\sqrt{ϵ}}\right)+\frac{\sqrt{ϵ}}2\sin\left(\frac{t}{\sqrt{ϵ}}\right)\right)
$$
Let's be a bit more ingeniuous about it. We know that largely $y(t)=\cos(t)+u(t)$ where $u$ will be small in later times. But then
$$
ϵu''+ϵu'+u=ϵ\cos(t)+ϵ\sin(t)
$$
Adjust the decomposition of $y$ for the new right side, now $y(t)=(1+ϵ)\cos(t)+ϵ\sin(t)+u(t)$, then the differential equation reads
$$
\begin{split}
ϵ[-(1+ϵ)\cos(t)-ϵ\sin(t)+u''(t)]&+ϵ[-(1+ϵ)\sin(t)+ϵ\cos(t)+u(t)]\\&+[(1+ϵ)\cos(t)+ϵ\sin(t)+u(t)]=\cos(t)
\end{split}
\\\iff\\
ϵu''+ϵu'+u=2ϵ^2\sin(t)\iff u''+u'+\frac1ϵu=2ϵ\sin(t)
$$
which now is essentially a homogeneous equation.
Approach via parametrized sinusoid
As this is a harmonic oscillator with damping, use the form proposed in the hint at the end of the section, set $u(t)=A(t)\cos(ωt+θ(t))$ with $ω=\sqrt{\frac1ϵ}$ and  $A(t),θ(t)$ "slow" moving, in the sense that their derivatives are small against $ω$. Then
\begin{align}
u'(t)&=A'(t)\cos(ωt+θ(t))-A(t)\sin(ωt+θ(t))(ω+θ'(t))  \\
u''(t)&=A''(t)\cos(ωt+θ(t))-2A'(t)\sin(ωt+θ(t))(ω+θ'(t))  \\
& ~ ~ ~ ~- A(t)\cos(ωt+θ(t))(ω+θ'(t))^2-A(t)\sin(ωt+θ(t))θ''(t)  \\
\end{align}
Comparing coefficients in $u''(t)+u'(t)+ω^2u(t)$ results in the identies
\begin{align}
0&=A''(t)+A'(t)- A(t)(2ω+θ'(t))θ'(t)\\
0&=-A(t)θ''(t)-2A'(t)(ω+θ'(t)) -A(t)(ω+θ'(t))\\[.7em]
\implies
2A(t)θ'(t)&=\sqrt{ϵ}[A''(t)+A'(t)-2A(t)θ'(t)^2]\\
2A'(t)+A(t)&=-\sqrt{ϵ}[A(t)θ''(t)+ (2A'(t)+A(t))θ'(t)]
\end{align}
so that in first approximation $A(t)=A_0e^{-t/2}$ and $θ(t)=θ_0$. Inserting into the right side gives the next order of approximation as
\begin{align}
2θ'(t)&=\sqrt{ϵ}[\tfrac14-\tfrac12]&&\implies& θ(t)=θ_0-\frac{\sqrt{ϵ}}8t\\
2A'(t)+A(t)&=0&&\implies& \text{unchanged}
\end{align}

Now adjust the coefficients for the initial conditions in
\begin{align}
y(t)&=(1+ϵ)\cos(t)+ϵ\sin(t)+A_0e^{-t/2}\cos\left((ω-\tfrac18\sqrt{ϵ})t+θ_0\right)\\
y'(t)&=-(1+ϵ)\sin(t)+ϵ\cos(t)-\tfrac12 A_0e^{-t/2}\cos\left((ω-\tfrac18\sqrt{ϵ})t+θ_0\right)
\\&~~~~-(ω-\tfrac18\sqrt{ϵ})A_0e^{-t/2}\sin\left((ω-\tfrac18\sqrt{ϵ})t+θ_0\right)
\\\hline
0=y(0)&=(1+ϵ)+A_0\cos\left(θ_0\right)\\
0=y'(0)&=ϵ-\tfrac12 A_0\cos\left(θ_0\right)-(ω-\tfrac18\sqrt{ϵ})A_0\sin\left(θ_0\right)\\
&=\tfrac12(1+3ϵ)-ω(1-\tfrac18ϵ)A_0\sin\left(θ_0\right)
\end{align}
It remains to solve the polar decomposition $A_0(\cos(θ_0),\sin(θ_0))=(-(1+ϵ), \tfrac12\sqrtϵ+O(ϵ^{3/2}))$ giving $θ_0=\pi-\tfrac12\sqrtϵ$ and $A_0=1+\frac98ϵ$.

Approach via WKB approximation
This all follows much more easily if the basis functions are computed via a WKB expansion $u(t)=e^{S/\delta}$, allowing for complex exponents, and then the real combinations are taken. The equation $ϵu''+ϵu'+u=0$ then leads to
$$
ϵ(δS''+S'^2)+ϵδS'+δ^2=0
$$
Also here one finds balancing for $δ^2=ϵ$ so that
$$
S'^2+1=-δ(S''+S')
$$
Using an expansion in powers of $δ$ (and setting $s_k=S_k'$) gives $s_0=\pm i$, $2s_0s_1=-s_0\implies s_1=-\frac12$, $s_1^2+2s_0s_2=-s_1\implies s_2=\mp\frac{i}8$
so that the basis solutions up to that approximation order are in their real form
$$
y_1(t)=e^{-t/2}\cos\left(\left(\frac1δ-\fracδ8\right)t\right),~~
y_2(t)=e^{-t/2}\sin\left(\left(\frac1δ-\fracδ8\right)t\right).
$$
Now use shortly $ω=\left(\frac1δ-\fracδ8\right)=\sqrt{\frac1ϵ}(1-\fracϵ8)$ and match the initial conditions for
\begin{align}
y(t)&=(1+ϵ)\cos(t)+ϵ\sin(t)+e^{-t/2}[A_0\cos(ωt)+B_0\sin(ωt)]\\
y'(t)&=-(1+ϵ)\sin(t)+ϵ\cos(t)-\tfrac12 e^{-t/2}[A_0\cos(ωt)+B_0\sin(ωt)]-ωe^{-t/2}[A_0\sin(ωt)-B_0\cos(ωt)]
\\\hline
0=y(0)&=(1+ϵ)+A_0\\
0=y'(0)&=ϵ-\tfrac12 A_0+ωB_0=\tfrac12(1+3ϵ)+ωB_0
\end{align}
so that more directly $A_0=-(1+ϵ)$ and $B_0=-\tfrac12\sqrtϵ(1+O(ϵ))$.
With some slightly more computation one can get also the next terms in the expansions of $A_0,B_0$
Comment: We're actually supposed to use the multiple scale method, which is why I took $t_1=t$ and $t_2=\sqrt(\epsilon)t$. @LutzL
Comment: Ok, with the hint given at the end of the section, you are to use $y(t)=A(ϵ,t)\cos(t/\sqrtϵ+\theta(ϵ,t))$ which in the main will replicate the steps and results of the WKB approximation.
Answer: Lutzl's answers is excellent, but I wanted to add the direct multiple-scales version.
Let $t_1=t$ and $t_2=\epsilon^\alpha t$, and $y(t)=Y(t_1,t_2)$. Substituting into the differential equation gives
$$ \epsilon Y_{t_1t_2}+2\epsilon^{1+\alpha}Y_{t_1t_2}+\epsilon^{1+2\alpha}Y_{t_2t_2}+\epsilon Y_{t_1}+\epsilon^{1+\alpha}Y_{t_2}+Y=\cos(t_1). $$
If we pick $\alpha>0$ then the leading order equation will be $Y_0=\cos(t_1)$ which doesn't satisfy the initial conditions, so we must have $\alpha<0$ and hence $\alpha=-1/2$ by dominant balance (this was your error, you had $\alpha=1/2$). So the system to solve is
$$ \epsilon Y_{t_1t_2}+2\epsilon^{1/2}Y_{t_1t_2}+Y_{t_2t_2}+\epsilon Y_{t_1}+\epsilon^{1/2}Y_{t_2}+Y=\cos(t_1)\quad Y(0,0)=0,\quad \epsilon^{1/2}Y_{t_1}(0,0)+Y_{t_2}(0,0)=0. $$
Expand $Y$ as $Y_0+\epsilon^{1/2}Y_1+\ldots$ to give, at leading order,
$$ Y_{0,t_2t_2}+Y_{0}=\cos(t_1),\quad Y_0(0,0)=0,\quad Y_{0,t_2}(0,0)=0, $$
with solution $Y_0=A(t_1)\cos(t_2)+B(t_1)\sin(t_2)+\cos(t_1)$, where $A(0)+1=0$ and $B(0)=0$ to satisfy the initial conditions.
The $O(\epsilon^{1/2})$ equation is
$$ Y_{1,t_2t_2}+Y_{1}=-2Y_{0,t_1t_2}-Y_{0,t_2},\quad Y_1(0,0)=0,\quad Y_{0,t_1}+Y_{1,t_2}(0,0)=0, $$
and substituting $Y_0$,
$$ Y_{1,t_2t_2}+Y_{1}=(2A'(t_1)+A(t_1))\sin(t_2)-(2B'(t_1)+B(t_1))\cos(t_2). $$
The $\sin(t_2)$ and $\cos(t_2)$ terms are secular, so we must remove them by setting
$$ 2A'+A=0,\quad 2B'+B=0 $$
which, coupled with the initial conditions $A(0)=-1$ and $B(0)=0$, give $A(t_1)=-e^{-t_1/2}$ and $B(t_1)=0$.
So we finally get $$ Y_0(t_1,t_2) = -e^{-t_1/2}\cos(t_2)+\cos(t_1) $$
or, in terms of $y$ and $t$,
$$y(t)=-e^{-t/2}\cos\left(\frac{t}{\sqrt{\epsilon}}\right)+\cos(t)+O(\sqrt{\epsilon}).$$
Comment: Thank you so much for clearing my doubt!
Comment: If we take $\alpha=-1/2$ then wouldn't we have to get $O(\frac{1}{\sqrt\epsilon}) $instead?
Comment: Also, another question that I have is the asymptotic expansion of $Y$ as $ Y_0+\epsilon^{1/2}Y_1$.. how exactly do you get this, cause the expansion I know take $\epsilon$ to the power 1. @David
Comment: There are two separate scaling arguments. One is for the time scales, which are $O(\epsilon^{-1/2})$ and $O(1)$. The other is for the asymptotic expansion for $Y$. You can do a dominant balance argument to determine the powers, but in this case the simple thing $Y_0+\sqrt{\epsilon}Y_1+\epsilon Y_2+\ldots$ works. Since the equation has $\sqrt{\epsilon}$ terms, I guessed that the expansion for $Y$ should also include half-powers of $\epsilon$.
Comment: okay.. But the final one term expansion that is obtained at $Y(t)$ doesn't satisfy the boundary condition at $Y'(t)$.
Comment: Yes. The $Y_1$ term corrects the error though. The initial condition $y'(0)=0$ has leading-order term $O(\epsilon^{-1/2})$, and $Y_0$ satisfies that, but leaves an $O(1)$ error behind, which is corrected by $Y_1$, and so on. The initial condition is satisfied one order lower in $\sqrt{\epsilon}$ than the reset of the problem. I think that's just the way it is.
Comment: okay! Sorry to trouble you with so many questions. The system can't be solved right if we use the time scale at $O(\sqrt\epsilon)$?
Comment: That would correspond to a very slow time scale. Lutzl's answer explains quite well why there is a fast ($1/\sqrt{\epsilon}$) time scale and an $O(1)$ time scale. An $O(\sqrt{\epsilon})$ time scale would correspond to very slow changes, but we know


Why is my custom webform handler, when called via cron, doesn't load and email attachments?

Question: I created a custom webform handler that on postSave adds webform id to the queue:
public function postSave(WebformSubmissionInterface $webform_submission, $update = TRUE) {
<code>$item = array(
  'submission' => $webform_submission,
);

// Add the item to the queue.
$queue_factory = \Drupal::service('queue');
$queue = $queue_factory->get('custom_send_emails');
$queue->createItem($item);
</code>
}
}
This is the QueueWorker:
<code>/**
 * Send Emails
 *
 * @QueueWorker(
 *   id = "custom_send_emails",
 *   title = @Translation("send emails"),
 *   cron = {"time" = 120}
 * )
 */
class CustomEmailQueue extends CustomEmailQueueBase {}
</code>
and this is the QueueWorkerBase that on processItem send the email that is build by a custom mail handler:
<code>public function processItem($item) {
    $this->custom_send_emails($item['submission']);
  }

  function custom_form_send_emails(WebformSubmissionInterface $submission) {
    $webform = $submission->getWebform();
    $handler = $webform->getHandler('local_email');
    $handler->sendMessage($submission);
  }
</code>
I have tried everything! When Cron runs, it takes the first item of the queue create the message correctly and send the email with the attachments. Then it continues to the rest of the items and for all of them it doesn't build correct the message. The to_email is empty. The $attachments array of the $message is empty.
Why does it do that? Why the first item of the queue is send correctly and the rest fail?
With Debug I found that in the first queue item process, it calls from EmailWebformHandler.php the getMessageAttachments() and the getElementsInitializedAndFlattened fetches more elements(the attachments and everything) than in next calls? WHY?
Eventually I found that this segment of code in my local_email handler causes the problem and I don't understand why. In this handler I want to send the email in the language selected in one specific field. This is why I get the language from the field and then I  do this
<code>$this->languageManager->setConfigOverrideLanguage($language);
</code>
that causes the issue!!!
<code> //get communication language
    $values = $webform_submission->getData();
    $language = $this->languageManager->getLanguage($values['communication_language']);
    $this->languageManager->setConfigOverrideLanguage($language);
    $mail_config = \Drupal::config('webform.webform.sme_fund');
    $subject = $mail_config->get('handlers.local_email.settings.subject');
    $subject = $this->replaceTokens($subject, $webform_submission);
    $body = $mail_config->get('handlers.local_email.settings.body');
    $current_langcode = $values['communication_language'];
    $message['subject'] = $subject;
    $message['body'] = $body;
</code>
Answer: If your code works when you don't change langage, that could be that you just forgot to restore the original langage after processing - as it is the same process running, it means that the next item in your queue will be processed with a langage manager set from the previous item which could be different.
Try to do something like  :
<code>$original_language = $this->languageManager->getConfigOverrideLanguage();
// your processing code
$this->languageManager->setConfigOverrideLanguage($original_language);
</code>


Java HTTP Post Multipart

Question: I'm trying to send an HTTP Post Multipart request to a local server in JAVA. I'm trying to send the following:
<code>{
 "content-disposition": "form-data; name=\"metadata\"",
"content-type": "application/x-dmas+json",
 "body":         JSON.stringify(client_req)
},
{
"content-disposition": "attachment; filename=\"" + file + "\"; name=\"file\"",
"content-type": "application/octet-stream",
 "body":         [file content]
}
</code>
I've looked into Apache HTTP components, but it doesn't let me specify the content-type and disposition for each part. Here's what I've written in JAVA using the Apache HTTP API:
`CloseableHttpClient httpclient = HttpClients.createDefault();
<code>    try {
        HttpPost httppost = new HttpPost("IP");

        FileBody bin = new FileBody(new File(args[0]), "application/octet-stream");
        StringBody hash = new StringBody("{\"hash\": \"\", \"policy\": {\"retention_permitted\": true, \"distribution\": \"global\"}}", ContentType.create("application/x-dmas+json"));

        HttpEntity reqEntity = MultipartEntityBuilder.create()
                .addPart("metadata", hash)
                .addPart("file", bin)
                .build();

        httppost.setEntity(reqEntity);
</code>
`
Comment: That is not Java but JavaScript. Show us the relevant Java code.
Comment: Nonetheless, I'd like to be able to set the content-type and content-disposition for each part in JAVA.
Answer: The constructor parameters and methods of FilePart and StringPart, with which you compose a Part[] that makes up the multipart request provide this information.
Comment: Will that work with MultipartEntityBuilder? I've seen it used with the deprecated MultipartRequestEntity.
Answer: Probably it is too late but as reference for anyone looking the answer for the same question, there is several methods in the MultipartEntityBuilder class that allow you to set the  content-type and content-disposition for each part. For example,

addBinaryBody(String name, File file, ContentType contentType, String    filename)
addTextBody(String name, String text, ContentType contentType)

If we use the above methods in your example,
<code>CloseableHttpClient httpClient = HttpClients.createDefault();
HttpPost uploadFile = new HttpPost("http://url-to-post/");

MultipartEntityBuilder builder = MultipartEntityBuilder.create();
String jsonStr = "{\"hash\": \"\", \"policy\": {\"retention_permitted\": true, \"distribution\": \"global\"}}";
builder.addTextBody("metadata", jsonStr, ContentType.create("application/x-dmas+json"));
builder.addBinaryBody("file", new File("/path/to/file"),
    ContentType.APPLICATION_OCTET_STREAM, "filename");

HttpEntity multipart = builder.build();
uploadFile.setEntity(multipart);
HttpResponse response = httpClient.execute(uploadFile);
</code>

Java HTTP Post Multipart


Drupal t() function does not replace placeholders for me

Question: Why would placeholders not be replaced?
For example, in the Uninstall page for modules, it shows the following.

It happens under the revisions tab as well.
Comment: I don't think this is Twig related?
Comment: Looks like the `t()` function in your Drupal is not replacing the placeholder values for some reason.
Comment: Apparently the cause is the [https://github.com/drupal-pattern-lab/unified-twig-extensions/blob/master/example/_twig-components/functions/link.function.php]  unified twig extensions module. Still not sure how it is messing the t() function up exactly.
Comment: My guess is it might come with a dummy function that mocks t() and returns it for theming purposes? It could be overriding.
Comment: @Kevin you were right, thank you for this insight!
Comment: Thats what I thought, I will leave the answer if someone else hits this.
Answer: It looks like electrokate installed a Pattern Lab starter theme for Drupal that has a mock of the t() function that acts as a placeholder for prototyping the front end layer. It only returns the input it was sent, so it "works" under Pattern Lab - but running it inside of Drupal will cause this issue.
/**
 * @file
 * Drupal translate filter.
 */
$filter = new Twig_SimpleFilter('t', function ($string) {
  return $string;
});

This is meant to aid in making a Pattern Lab prototype outside of Drupal, but taking advantage of functions you will expect to use inside of Drupal so it is "Drupal ready".
edit: I may have linked to the wrong starter theme, but I can't navigate it on mobile.


Distribution of the time of the first point of the process, conditional on the event that exactly one point occurs in the interval $[0,t]$

Question: Let $N_t$ be a Poisson process of rate $\lambda$.
1)What is $P(N_s = 1|N_t =1)$ for $0<s<t$?
2) Find the distribution of the time of the first point of the process, conditional on the event that exactly one point occurs in the interval [0,t]?
I know $P(N_t = 1)=e^{-\lambda t}(\lambda t)$. I was wondering based on the memoryless property for Poisson processes whether $P(N_s = 1|N_t =1)=e^{-\lambda t}(\lambda t)$ as well since the distribution of $(N_t,t>t_0)$ conditional on the process $(N_t,t\ge t_0)$ depends only on the value of $N_{t_0}$
Additionally, I am not sure about part 2), would this also be a Poisson process of rate $\lambda$?
Comment: Look at http://math.stackexchange.com/a/379366/413376
Answer: Conditionally on $\{N_t=1\}$, the first jump is uniformly distributed inside $[0,\,t]$. The probability that it belongs to $[0,s]$ is the ratio of lengths:
$$P(N_s = 1|N_t =1) = \frac{s}{t}.$$
The answer to the second question is already contained here.
Comment: how is the second question contained in $s/t$? The above is the probability of the counting process, whereas the second question is asking about the distribution of the time of the first point of the process conditioned on one point occurring in the $[0,t]$ interval. I'm confused by this relation. Thank you for your help.
Comment: @z8910 The c.d.f. of the time $T_1$ of the first point of the process, conditional on the event that exactly one point occurs in the interval $[0,t]$ is $P(T_1\leq s | N_t=1)$. It is the same as the probability that exactly one point occurs in the interval $[0,s]$ given that exactly one point occurs in the interval $[0,t]$: $P(T_1\leq s | N_t=1)=P(N_s =1 | N_t=1)=s/t.$ It means that this conditional distribution is Uniform on $[0,t]$.
Answer:
I know $P(N_t = 1)=e^{-\lambda t}(\lambda t)$.

Yes.   Also written as $~\mathsf P(N_{(0;t]} = 1)~=~e^{-\lambda t}(\lambda t)~$, where $N_{(0;t]}$ is the count of point-events in the interval $(0;t]$.

I was wondering based on the memoryless property for Poisson processes whether $P(N_s = 1|N_t =1)=e^{-\lambda t}(\lambda t)$ as well since the distribution of $(N_t,t>t_0)$ conditional on the process $(N_t,t\ge t_0)$ depends only on the value of $N_{t_0}$

No.   Not in the slightest.
However, $~\mathsf P(N_{(0;s]}=1)~=~ e^{-\lambda s}\lambda s~$ and $~\mathsf P(N_{(s;t]}=0)~=~e^{-\lambda(t-s)}~$, because the counts of events in an interval depends only on the length of the interval (which is what you were thinking of).
Also the counts of Poisson point-events in disjoint intervals are independent.
Use that and the definition of conditional probability.
$$\mathsf P(N_{(0;s]}=1\mid N_{(0;t]}=1) ~=~\dfrac{\mathsf P(N_{(0;s]}=1, N_{(s;t]}=0)}{\mathsf P(N_{(0;t]}=1)}$$
This, as NCh spoils, simplifies into a nice result.


Android and website synchronization

Question: I have an issue. We have a website, where person can login and make its own lists of news. Now we trying to develop an Android application, where person could login and do the same in phone. I cannot understand best preactises of implementing such things. It have to be same accounts, with same preserved data as stored online on website.
Could anyone tell me how to synchronize web and android?
Answer: You can use backend scripts to get the same data from database of website in android. You need to call a script(in any language like php) to get the data from database. and show this in listview in android or compare it with the user id password entered.
Comment: The point is that if for instance User1 came and see his list, then User 2 came and he has different list of information on webiste. How to achieve the same in mobile application?
Comment: For your website purpose you must have a database somewhere with list in it corresponding to users. In the same way, if a user with id and password logins and you call a script to check whether this user exists, and after that get the list of that user using sqlite query in your scripts.   I have  done a similar website and android app having similar data , So I can assure you that this is possible in a very simple way. Do you need any more help?
Comment: Yes, please. How you send passord and login? Is it just an ordinary post? Or maybe some tools exist regarding this issue. And one more question. When you load database from website to mobile device it is clear that it will be changed on website. How to update it? Clean out all old data and add new ones? In this occasion most of datas will be dublicated. Maybe some tool exist to add just new datas not removing old ones?
Comment: you can normally create textview with id and password. Get the text of these two fields and call a script and send these two values to it. On the server side(i.e in script) you make a sqlite query for checking these values with id-password tables values. And if it matches any of those, return yes. This is how we know about existannce of id-password
Comment: which second question?Kindly ask again. If my comments are helpful to you please upvote.
Comment: When you load database from website to mobile device it is clear that it will be changed on website. How to update it? Clean out all old data and add new ones? In this occasion most of datas will be dublicated. Maybe some tool exist to add just new datas not removing old ones?
Comment: No data will be removed in this way. I think, you should consult your backend script developer. Sqlite queries can work in any way we want it. It will add data, update from your app too. And I think that it is working the same from your website. There is nothing like tool. Don't worry

Android and website synchronization


Android SearchBar Without Clicking Button

Question: I have been trying to find the answer but maybe I am not asking google correctly so here it goes: I have a search view in my android app that has the top menu item as a search input, etc. I click the magnifier, and then textfield becomes editable for search term. How can I skip this step and make it that, when onCreate() method of my activity, the search field gets the focus automatically without the need for clicking the magnifier icon?
Here is my code:
    MenuInflater inflater = new MenuInflater(SearchMedicineActivity.this);
    inflater.inflate(R.menu.search_view, menu);
    MenuItem searchItem = menu.findItem(R.id.action_search);
    searchItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_IF_ROOM| MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
    mSearchView = (SearchView) searchItem.getActionView();
    mSearchView.setOnQueryTextListener(this);
    mSearchView.setIconifiedByDefault(false);
    return true;

Answer: Calling setIconifiedByDefault(false) inside the public boolean onPrepareOptionsMenu(Menu menu) should get you the result you want. If you want the keyboard to be visible, try calling requestFocus() as well.
Answer: From http://developer.android.com/reference/android/widget/SearchView.html

When the SearchView is used in an ActionBar as an action view for a
  collapsible menu item, it needs to be set to iconified by default
  using setIconifiedByDefault(true). This is the default, so nothing
  needs to be done.
If you want the search field to always be visible, then call
  setIconifiedByDefault(false).
Comment: Actually, I tried this before but it didn't work. I am even updating my question now to reflect what I tried.