text:
## Discuz 和phpwind 的循環抄

phpwind 作為後起之秀, 很多地方借鑑了Discuz! 而在最近, 因為SNS 的興起, 雙方的版本更新甚快, 而對於SNS 的新功能, 甚至出現循環抄的情況。

Discuz 的X-Space 可以說有了的SNS 的初步結構, 但名正言順的產品卻是ucenter home。在初期, 原全複製Facebook 的介面做出來的uch 令人眼前一亮之餘, 也令我想到, SNS 這東西容納如此多的競爭者嗎?

## Quick Inspirations

Over-estimation of value is usually due to supposing equal importance.

Under-estimation of value is usually due to supposing equal unimportance.

1. 我喜歡吃甜品
2. 我喜歡睡覺
3. 我喜歡玩遊戲王
4. 我喜歡下載盜版軟件

1. 我不喜歡吃辣
2. 我不喜歡捱通宵
3. 我不喜歡工作
4. 我不喜歡共產黨

## .htaccess - Allow Only By Referer

Good afternoon-

I have browsed the forums as well as the web looking for an answer to this question. Hope someone out there can help.

I need to create a .htaccess file that will only allow the files in the folder to be seen if the "referer" is from a particular site (or possibly two sites). I have found a lot of solutions out there for people who want to block specific sites, but I can't seem to figure out how to only allow specific sites. I have done some trial and error based on some of the things I have found, but with no luck.

Any ideas?

David

－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－

ANS:

Hi David,

Welcome to the forums

I haven't tested it, but try;

RewriteEngine on
RewriteBase /
RewriteCond %{HTTP_REFERER} !^http://www\.your_domain_name\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^http://www\.OKdomain1\.com/ [NC]
RewriteCond %{HTTP_REFERER} !^http://www\.OKdomain2\.com/ [NC]
RewriteRule ^.*\$ http://www.your_domain_name.com/not_allowed_here.htm [R=301,L]

or I'd try something along those lines anyway - with the not_allowed_here.htm being a page I redirected all those I don't want to.

## 亞貝的天堂template 分享(三欄, 灰)

body{
color:#333
}
.indexBlock{margin: 5px 440px 5px 0px;}
.cateitem{display:block; width:100px; padding:3px 0 0 20px; float:left; background:url("http://grok.lsu.edu/images/category.png") no-repeat;}
.navPanel{width:20px; height:10px; overflow:hidden; position:fixed; opacity:0.7; top:0%; right:50%}
.navPanel:hover{width:100px; height:auto; overflow:hidden}
.buttons a{clear:both}
#rbindexbutton{display:none}

.selected{background:url("http://www.foxlingo.com/img/icons/selected.png") no-repeat;font-weight:bold}
a,
a:visited,
a:active {color: #666;text-decoration: underline;}
a:hover {	color: #999;background: none;}
.sidebar{width:420px; border-left:none}
.content{margin:0 -440px 0 0}
.cussidebar{float:right; width:200px}

.syssidebar{border-right:1px #999 dashed; border-left:1px #999 dashed;float:left; width:200px; padding:0 5px}
.navPanel{background:#DDD}

## Best Programming Jokes

How can you tell when a programmer has had sex?

When he’s washing the pepper spray out of his eyes.
~~~~~~~~~~~~~~~~~~~~~~~~~
Two bytes meet.  The first byte asks, “Are you ill?”
The second byte replies, “No, just feeling a bit off.”

~~~~~~~~~~~~~~~~~~~~~~~~~
Eight bytes walk into a bar.  The bartender asks, “Can I get you anything?”
“Yeah,” reply the bytes.  “Make us a double.”
~~~~~~~~~~~~~~~~~~~~~~~~~
Q. How did the programmer die in the shower?
A. He read the shampoo bottle instructions: Lather. Rinse. Repeat.
~~~~~~~~~~~~~~~~~~~~~~~~~
How many programers dose it take to change a light bulb?
None – It’s a hardare problem
~~~~~~~~~~~~~~~~~~~~~~~~~
Why do programmers always mix up Halloween and Christmas?
Because Oct 31 equals Dec 25.
~~~~~~~~~~~~~~~~~~~~~~~~~
There are only 10 kinds of people in this world: those who know binary and those who don’t.
~~~~~~~~~~~~~~~~~~~~~~~~~
A programmer walks to the butcher shop and buys a kilo of meat.  An hour later he comes back upset that the butcher shortchanged him by 24 grams.
~~~~~~~~~~~~~~~~~~~~~~~~~
“Knock, knock.”
“Who’s there?”
very long pause….
“Java.”
~~~~~~~~~~~~~~~~~~~~~~~~~
Programming is 10% science, 20% ingenuity, and 70% getting the ingenuity to work with the science.
~~~~~~~~~~~~~~~~~~~~~~~~~
Programming is like sex:
One mistake and you have to support it for the rest of your life.
~~~~~~~~~~~~~~~~~~~~~~~~~
A man is smoking a cigarette and blowing smoke rings into the air.  His girlfriend becomes irritated with the smoke and says, “Can’t you see the warning on the cigarette pack?  Smoking is hazardous to your health!”
To which the man replies, “I am a programmer.  We don’t worry about warnings; we only worry about errors.”
~~~~~~~~~~~~~~~~~~~~~~~~~
There are three kinds of lies: Lies, damned lies, and benchmarks.
~~~~~~~~~~~~~~~~~~~~~~~~~
A programmer is walking along a beach and finds a lamp.  He rubs the lamp, and a genie appears.  “I am the most powerful genie in the world.  I can grant you any wish, but only one wish.”
The programmer pulls out a map, points to it and says, “I’d want peace in the Middle East.”
The genie responds, “Gee, I don’t know.  Those people have been fighting for millenia.  I can do just about anything, but this is likely beyond my limits.”
The programmer then says, “Well, I am a programmer, and my programs have lots of users.  Please make all my users satisfied with my software and let them ask for sensible changes.”
At which point the genie responds, “Um, let me see that map again.”
~~~~~~~~~~~~~~~~~~~~~~~~~
All programmers are playwrights, and all computers are lousy actors.
~~~~~~~~~~~~~~~~~~~~~~~~~
Have you heard about the new Cray super computer?  It’s so fast, it executes an infinite loop in 6 seconds.
~~~~~~~~~~~~~~~~~~~~~~~~~
The generation of random numbers is too important to be left to chance.
~~~~~~~~~~~~~~~~~~~~~~~~~
“I just saw my life flash before my eyes and all I could see was a close tag…”
~~~~~~~~~~~~~~~~~~~~~~~~~
The computer is mightier than the pen, the sword, and usually, the programmer.
~~~~~~~~~~~~~~~~~~~~~~~~~
Debugging: Removing the needles from the haystack.
~~~~~~~~~~~~~~~~~~~~~~~~~
Two strings walk into a bar and sit down. The bartender says, “So what’ll it be?”
The first string says, “I think I’ll have a beer quag fulk boorg jdk^CjfdLk jk3s d#f67howe%^U r89nvy~~owmc63^Dz x.xvcu”
“Please excuse my friend,” the second string says, “He isn’t null-terminated.”
~~~~~~~~~~~~~~~~~~~~~~~~~
From the Random Shack Data Processing Dictionary:
Endless Loop: n., see Loop, Endless.
Loop, Endless: n., see Endless Loop.
~~~~~~~~~~~~~~~~~~~~~~~~~
The three most dangerous things in the world are a programmer with a soldering iron, a hardware engineer with a software patch, and a user with an idea.  – The Wizardry Compiled by Rick Cook
~~~~~~~~~~~~~~~~~~~~~~~~~
One hundred little bugs in the code
One hundred little bugs.
Fix a bug, link the fix in,
One hundred little bugs in the code.
~~~~~~~~~~~~~~~~~~~~~~~~~
A computer science student is studying under a tree and another pulls up on a flashy new bike.  The first student asks, “Where’d you get that?”
The student on the bike replies, “While I was studying outside, a beautiful girl pulled up on her bike.  She took off all her clothes and said, ‘You can have anything you want’.”
The first student responds, “Good choice!  Her clothes probably wouldn’t have fit you.”
~~~~~~~~~~~~~~~~~~~~~~~~~

~~~~~~~~~~~~~~~~~~~~~~~~~
CIA – Computer Industry Acronyms
CD-ROM: Consumer Device, Rendered Obsolete in Months
PCMCIA: People Can’t Memorize Computer Industry Acronyms
ISDN: It Still Does Nothing
SCSI: System Can’t See It
MIPS: Meaningless Indication of Processor Speed
DOS: Defunct Operating System
WINDOWS: Will Install Needless Data On Whole System
OS/2: Obsolete Soon, Too
PnP: Plug and Pray
APPLE: Arrogance Produces Profit-Losing Entity
IBM: I Blame Microsoft
MICROSOFT: Most Intelligent Customers Realize Our Software Only Fools Teenagers
COBOL: Completely Obsolete Business Oriented Language
LISP: Lots of Insipid and Stupid Parentheses
MACINTOSH: Most Applications Crash; If Not, The Operating System Hangs
AAAAA: American Association Against Acronym Abuse.
WYSIWYMGIYRRLAAGW: What You See Is What You Might Get If You’re Really Really Lucky And All Goes Well.
~~~~~~~~~~~~~~~~~~~~~~~~~
Funny Error Messages
~~~~~~~~~~~~~~~~~~~~~~~~~
God as a Programmer
~~~~~~~~~~~~~~~~~~~~~~~~~
Computer Stupidities
~~~~~~~~~~~~~~~~~~~~~~~~~
Comedy Code is syntactically correct programming code written just for fun.  The code doesn’t actually have to do anything if it’s executed, but it should look like regular code.
~~~~~~~~~~~~~~~~~~~~~~~~~
Why computers are like men:

1. In order to get their attention, you have to turn them on.
1. They have a lot of data, but are still clueless.
1. They are supposed to help you solve problems, but half the time they are the problem.
1. As soon as you commit to one, you realize that if you had waited a little longer, you could have had a better model.
Why computers are like women:
1. No one but the Creator understands their internal logic.
1. The native language they use to communicate with other computers is incomprehensible to everyone else.
1. Even your smallest mistakes are stored in long-term memory for later retrieval.
1. As soon as you make a commitment to one, you find yourself spending half your paycheck on accessories for it.
~~~~~~~~~~~~~~~~~~~~~~~~~
Laws of Computer Programming
1. Any given program, when running, is obsolete.
1. Any given program costs more and takes longer.
1. If a program is useful, it will have to be changed.
1. If a program is useless, it will have to be documented.
1. Any program will expand to fill available memory.
1. The value of a program is proportional to the weight of its output.
1. Program complexity grows until it exceeds the capabilities of the programmer who must maintain it.
1. Any non-trivial program contains at least one bug.
1. Undetectable errors are infinite in variety, in contrast to detectable errors, which by definition are limited.
1. Adding manpower to a late software project makes it later.
~~~~~~~~~~~~~~~~~~~~~~~~~
• Lubarsky’s Law of Cybernetic Entomology: There’s always one more bug.
• Shaw’s Principle: Build a system that even a fool can use, and only a fool will want to use it.
• Woltman’s Law: Never program and drink beer at the same time.
• Gallois’ Revelation: If you put tomfoolery into a computer, nothing comes out but tomfoolery. But this tomfoolery, having passed through a very expensive machine, is somehow enobled, and no one dares to criticize it.
A programmer finds himself in front of a committee that decides whether he should go to Heaven or Hell.  The committee tells the programmer he has a say in the matter and asks him if he wants to see either Heaven or Hell before stating his preference.
“Sure,” the programmer replies.  “I have a pretty good idea what Heaven is like, so let’s see Hell.”  So an angel takes the programmer to a sunny beach, full of beautiful women in skimpy bikinis playing volleyball, listening to music and having a great time.  “Wow!” he exclaims, “Hell looks great!  I’ll take Hell!”
Instantly the programmer finds himself in red-hot lava with demons tearing at his flesh.  “Where’s the beach?  The music?  The women?” he screams frantically to the angel.
“That was the demo,” the angel replies as she vanishes.
~~~~~~~~~~~~~~~~~~~~~~~~~
Jesus and Satan have an argument as to who is the better programmer.  This goes on for a few hours until they come to an agreement to hold a contest with God as the judge.  They set themselves before their computers and begin.  They type furiously, lines of code streaming up the screen, for several hours straight.
Seconds before the end of the competition, a bolt of lightning strikes, taking out the electricity.  Moments later, the power is restored, and God announces that the contest is over.  He asks Satan to show his work.  Visibly upset, Satan cries and says, “I have nothing.  I lost it all when the power went out.”
“Very well,” says God, “let us see if Jesus has fared any better.”
Jesus presses a key, and the screen comes to life in vivid display, the voices of an angelic choir pour forth from the speakers.
Satan is astonished.  He stutters, “B-b-but how?!  I lost everything, yet Jesus’ program is intact!  How did he do it?”
God chuckles, “Everybody knows… Jesus saves.”
~~~~~~~~~~~~~~~~~~~~~~~~~
Redneck Computer Terms
LOG ON: Makin’ a woodstove hot.
LOG OFF: Don’t add no more wood.
MONITOR: Keepin’ an eye on the wood stove.
MEGA HERTZ: When you’re not keerfull gittin’ the farwood.
FLOPPY DISC: Whutcha git from trying to tote too much farwood.
RAM: That thar thing whut splits the farwood.
HARD DRIVE: Gittin’ home in the winter time.
WINDOWS: Whut to shut when it’s cold outside.
SCREEN: Whut to shut when it’s black fly season.
BYTE: Whut them dang flys do.
CHIP: Munchies fer the TV.
MICRO CHIP: Whut’s in the bottom of the munchie bag.
MODEM: Whutcha do to the hay fields.
DOT MATRIX: Old Dan Matrix’s wife.
LAP TOP: Whar the kitty sleeps.
KEYBOARD: Whar you hang the dang truck keys.
SOFTWARE: Them dang plastic forks and knifes.
MOUSE: Whut eats the grain in the barn.
MOUSE PAD: That’s hippie talk fer the mouse hole.
MAINFRAME: Holds up the barn roof.
PORT: Fancy Flatlander wine.
ENTER: Northerner talk fer, “C’mon in, y’all.”
CLICK: Whut you hear when you cock your gun.
DOUBLE CLICK: When the dang gun don’t far when you pull the trigger.
REBOOT: Whut you have to do at bedtime when you forgot the kitty’s still outside.
~~~~~~~~~~~~~~~~~~~~~~~~~
Software Development Cycles
1. Programmer produces code he believes is bug-free.
1. Product is tested. 20 bugs are found.
1. Programmer fixes 10 of the bugs and explains to the testing department that the other 10 aren’t really bugs.
1. Testing department finds that five of the fixes didn’t work and discovers 15 new bugs.
1. Repeat three times steps 3 and 4.
1. Due to marketing pressure and an extremely premature product announcement based on overly-optimistic programming schedule, the product is released.
1. Users find 137 new bugs.
1. Original programmer, having cashed his royalty check, is nowhere to be found.
1. Newly-assembled programming team fixes almost all of the 137 bugs, but introduce 456 new ones.
1. Original programmer sends underpaid testing department a postcard from Fiji. Entire testing department quits.
1. Company is bought in a hostile takeover by competitor using profits from their latest release, which had 783 bugs.
1. New CEO is brought in by board of directors. He hires a programmer to redo program from scratch.
1. Programmer produces code he believes is bug-free…
~~~~~~~~~~~~~~~~~~~~~~~~~
Top 10 phrases spoken by a Klingon Programmer
1. A TRUE Klingon Warrior does not comment his code!
1. By filing this bug report you have challenged the honor of my family.  Prepare to die!
1. You question the worthiness of my code?  I should kill you where you stand!
1. Our competitors are without honor!
1. Specifications are for the weak and timid!
1. This machine is GAGH!  I need dual Pentium processors if I am to do battle with this code!
1. Perhaps it IS a good day to die!  I say we ship it!
1. Our users will know fear and cower before our software!  Ship it!  Ship it and let them flee like the dogs they are!
1. My program has just dumped Stova Core!
1. Behold, the keyboard of Kalis!  The greatest Klingon code warrior that ever lived!
~~~~~~~~~~~~~~~~~~~~~~~~~
The programmer compiled an array of reasons as to why he can’t find a girlfriend with a good <HEAD> on her <BODY>, reason 0 being that he has limited cache.  So he searches his memory to recall connecting to the TCP/IP tunnel of his last girlfriend — sometimes even without a secure socket.  His last girlfriend always complained about his lack of comments. He fumed, “I hate commenting!”  Realizing it was a program requirement, he told her she had nice bits.  This resulted in a Syntax Error.  Now she demanded a massage, but this was rejected as “Feature Creep.”  He smacked her back-end and shouted, “Who’s your parent node?!”  He scanned for open ports.  He attempted to install a backdoor worm but her response was 403.  While his data uploaded into her input device, she considered terminating the process.  But instead she initiated a Do While loop where she recalled a previous boyfriend with a larger pointer.  To expedite the routine routine, she screamed, “Hack into my system! Hack deep into my system! You’re 1337, baby!”  This caused his stack to overflow, and he shot his GUI on her interface.  (Source)
~~~~~~~~~~~~~~~~~~~~~~~~~
What’s the difference between drug dealers and computer programmers?

 Drug Dealers Computer Programmers Refer to their clients as “users”. Refer to their clients as “users”. “The first one’s free!” “Download a free trial version…” Have important South-East Asian connections (to help move the stuff). Have important South-East Asian connections (to help debug the code). Strange jargon: “Stick,” “Rock,” “Dime bag,” “E”. Strange jargon: “SCSI,” “RTFM,” “Java,” “ISDN”. Realize that there’s tons of cash in the 14- to 25-year-old market. Realize that there’s tons of cash in the 14- to 25-year-old market. Job is assisted by the industry’s producing newer, more potent mixes. Job is assisted by industry’s producing newer, faster machines. Often seen in the company of pimps and hustlers. Often seen in the company of marketing people and venture capitalists. Their product causes unhealthy addictions. DOOM. Quake. SimCity. Duke Nukem 3D. ‘Nuff said. Do your job well, and you can sleep with sexy movie stars who depend on you. Damn! Damn! DAMN!!!

~~~~~~~~~~~~~~~~~~~~~~~~~


text:
User tryingotounderstand - MathOverflow most recent 30 from http://mathoverflow.net 2013-05-21T14:46:28Z http://mathoverflow.net/feeds/user/16393 http://www.creativecommons.org/licenses/by-nc/2.5/rdf http://mathoverflow.net/questions/70162/why-lawvere-theories-have-finite-products-and-more Why Lawvere theories have finite products? and more tryingotounderstand 2011-07-12T18:48:49Z 2011-07-13T07:33:00Z
According to Wikipedia, a Lawvere theory consists of a small category $L$ with (strictly associative) finite products and a strict identity-on-objects functor $I:\aleph_0^\text{op}\rightarrow L$ preserving finite products.

Why a Lawvere theory have n-products for any n finite? For example, why isn't a Lawvere theory for monoids a category T with four elements: $1$, $T$, $T^2$ and $T^3$, and morphisms $e:1 \to T$ and $*:T^2 \to T$ making the appropiate diagrams commute and such that they are products of each other as expected? ($T^3$ is needed in order to state these diagrams)

Also, why do they usually use the 'free' maps between the desired objects to model and not just the operators that the desired family of algebras has?
 http://mathoverflow.net/questions/70162/why-lawvere-theories-have-finite-products-and-more/70182#70182 Comment by tryingotounderstand tryingotounderstand 2011-07-13T16:31:16Z 2011-07-13T16:31:16Z Andrej, I quote from nLab article on Lawvere theories: "Remark. For T a Lawvere theory, we are to think of the hom-set T(n,1) as the set of n-ary operations defined by the theory. For instance for T the theory of abelian groups, we have T(2,1)={+,−} and T(0,1)={0}." Why is T(2,1) just {+,-},? Wouldn't it include other 'unnamed' operations as well? http://mathoverflow.net/questions/70162/why-lawvere-theories-have-finite-products-and-more/70187#70187 Comment by tryingotounderstand tryingotounderstand 2011-07-13T06:41:01Z 2011-07-13T06:41:01Z Thanks, after reading Andrej's post, now (3) makes sense. http://mathoverflow.net/questions/70162/why-lawvere-theories-have-finite-products-and-more/70182#70182 Comment by tryingotounderstand tryingotounderstand 2011-07-13T06:38:53Z 2011-07-13T06:38:53Z Thank you, very clear. I was misunderstanding it all, not thinking in syntax at all, just thinking about the models. http://mathoverflow.net/questions/70162/why-lawvere-theories-have-finite-products-and-more Comment by tryingotounderstand tryingotounderstand 2011-07-12T20:25:29Z 2011-07-12T20:25:29Z But isn't the monoid described just by the functor that tells what's the set ($F T$), the operation ($F *$) and the neuter ($F e$)? http://mathoverflow.net/questions/70162/why-lawvere-theories-have-finite-products-and-more Comment by tryingotounderstand tryingotounderstand 2011-07-12T19:46:54Z 2011-07-12T19:46:54Z I think this is the point where I get confused. Why would I need a product of four things? If model for $T$ would be a functor $F$ from $T$ to $Set$, then the product would be $F * : F T^2 \to F T$. For example if $F T = \mathbb{Z}_n$, then $F * : \mathbb{Z}_n^2 \to \mathbb{Z}_n$ would be the product (+) of my monoid (Z_n, +, 0) in Set, wouldn't it?

format: plain


text:
# My Weblog

## Proving the correctness of code using SMT sovler.

SMT solvers are great tool in computer science. One use of these solvers to prove the correctness of code. I wrote Haskell code to compute the inverse of polynomial using extended euclidean algorithm in Galois Field GF ( 2n ). If we try to analyze the code of inversePolynomial then every thing is normal except passing the depth parameter. It is unnecessary because we know that recursion is going to terminate. Initially I wrote the code without depth and the program was not terminating so I wrote mail to Levent Erkok and according to him

Your code suffers from what’s known as the “symbolic termination”. See Section 7.4 of: http://goo.gl/0E7wkm for a discussion of this issue in the context of Cryptol; but the same comments apply here as well. Briefly, when you recurse in inversePoly, SBV does not know when to stop the recursion of both branches in the ite: Thus it keeps expanding both branches ad infinitum.

Luckily, symbolic termination is usually easy to deal with once you identify what the problem is. Typically, one needs to introduce a recursion depth counter, which would stop recursion when it reaches a pre-determined depth that is determined to be safe. In fact, SBV comes with the regular GCD example that talks about this issue in detail:

I’d recommend reading the source code of the above; it should clarify the problem. You’ll need to find out a recursion-depth that’ll work for your example (try running it on concrete values and coming up with a safe number); and then prove that the bound is actually correct as explained in the above. The recursion depth bound just needs to be an overapproximation: If the algorithm needs 20 iterations but you use 30 as your recursion depth, nothing will go wrong; it’ll just produce bigger code and thus be less efficient and maybe more complicated for the backend prover. Of course, if you put a depth of 18 when 20 is needed, then it will be wrong and you won’t be able to establish correctness.

My verification condition is inverse of inverse of polynomial is same as polynomial. Right now I have no idea about proving the upper bound on depth so I just took 20. If you have any suggestion/comments then please let me know.

```
import Data.SBV.Bridge.Z3
import Data.Maybe

inversePolynomial ::  [ Int ] -> [ Int ] ->  SWord16
inversePolynomial poly reducer =  inversePoly  reducer' rem' first' second' depth'  where
poly' =  polynomial poly :: SWord16
reducer' =  polynomial reducer :: SWord16
first' =  0 :: SWord16
second' = 1 :: SWord16
depth' = 20 :: SWord16
( quot', rem' ) = pDivMod poly' reducer'

inversePoly :: SWord16 -> SWord16 -> SWord16 -> SWord16  ->  SWord16 -> SWord16
inversePoly  reducer'' poly'' first'' second'' depth'' =
ite ( depth'' .== 0 ||| rem'' .== ( 0 :: SWord16 ) ) (  second'' )  ( inversePoly  poly'' rem'' second'' ret ( depth'' - 1 ) )  where
( quot'', rem'' ) = pDivMod reducer'' poly''
ret =  pAdd ( pMult ( quot'', second'', [] ) ) first''

isInversePolyCorrect :: SWord16 -> SWord16 -> SBool
isInversePolyCorrect poly reducer = inversePoly reducer ( inversePoly reducer rem first second depth ) first second depth .== rem where
( quot, rem ) = pDivMod  poly reducer
first = 0 :: SWord16
second = 1 :: SWord16
depth = 20 :: SWord16

*Main> showPoly ( inversePolynomial  [ 6,4,1,0] [ 8,4,3,1,0] )
"x^7 + x^6 + x^3 + x"
*Main> proveWith z3 { verbose=False }  \$ forAll ["x"] \$ \x ->  pMod x ( 283 :: SWord16 ) ./=0 ==> isInversePolyCorrect x ( 283 :: SWord16 )
Q.E.D.
*Main> proveWith cvc4 { verbose=False }  \$ forAll ["x"] \$ \x ->  pMod x ( 283 :: SWord16 ) ./=0 ==> isInversePolyCorrect x ( 283 :: SWord16 )
*** Exception: fd:10: hFlush: resource vanished (Broken pipe)
*Main> proveWith yices { verbose=False }  \$ forAll ["x"] \$ \x ->  pMod x ( 283 :: SWord16 ) ./=0 ==> isInversePolyCorrect x ( 283 :: SWord16 )
Q.E.D.
```

September 21, 2013

## Counting Inversions

First week of algorithm course programming assignment is to compute the number of inversion count of given array. We have a given array A[0...n - 1] of n distinct positive integers and we have to count all the pairs ( i , j ) such that i < j and A[i] > A[j].
1. Brute Force
Brute force idea is very simple. Run two loops and keep counting the respective pairs for which i < j and A[i] > A[j]. The complexity of brute force is O( n2 ).

```bruteForce :: [ Int ] -> Int
bruteForce [] = 0
bruteForce [_] = 0
bruteForce ( x : xs ) = ( length . filter ( x > ) \$ xs ) + bruteForce xs

*Main> bruteForce [ 3 , 1 , 2]
2
*Main> bruteForce [ 2,3,8,6,1]
5
```

2. Divide and Conquer
We can modify the merge sort to compute the inversion count. The idea is to compute the inversion count of during the merge phase. Inversion count of array C resulting from merging two sorted array A and B is sum of inversion count of A, inversion count of B and their cross inversion. The inversion count of single element is 0 ( base case ). The only trick is compute the cross inversion. What will be the inversion count of following array if we merge them ?
A = [ 1 , 2 , 3 ]
B = [ 4 , 5 , 6 ]
Clearly 0 because all element of A is less than the first element of B. What is the inversion count of C = [ 4 , 5 , 6 ] and D = [ 1 , 2 , 3 ] ? First element of D ( 1 ) is less than first element of C ( 4 ) so we have total three pairs ( 4 , 1 ) ( 5 , 1 ) ( 6 , 1). Similarly for 2 and 3 ( total 9 inversion count ). It reveals that if we have any element y in D is less than certain element x in C then all the element of A after x will also be greater than y and we will have those many cross inversion counts. More clear explanation. Wrote a quick Haskell code and got the answer.

```import Data.List
import Data.Maybe ( fromJust )
import qualified Data.ByteString.Lazy.Char8 as BS

inversionCnt :: [ Int ] -> [ Int ] -> [ Int ] -> Int -> ( Int , [ Int ] )
inversionCnt [] ys  ret  cnt = ( cnt , reverse ret ++ ys )
inversionCnt xs []  ret  cnt = ( cnt , reverse ret ++ xs )
inversionCnt u@( x : xs ) v@( y : ys )  ret  cnt
| x <= y = inversionCnt xs v  (  x : ret   )   cnt
| otherwise = inversionCnt u ys  ( y : ret )  ( cnt + length u )

merge ::  ( Int , [ Int ] ) -> ( Int , [ Int ] ) -> ( Int , [ Int ] )
merge ( cnt_1 , xs ) ( cnt_2 , ys ) = ( cnt_1 + cnt_2 + cnt , ret ) where
( cnt , ret ) = inversionCnt xs ys []   0

mergeSort ::  [ Int ] -> ( Int , [ Int ] )
mergeSort [ x ] = ( 0 , [ x ] )
mergeSort  xs   = merge ( mergeSort xs' ) ( mergeSort ys' ) where
( xs' , ys' ) = splitAt ( div ( length xs ) 2 ) xs

main =  BS.interact \$ ( \x -> BS.pack \$ show x ++ "\n" ) . fst
.  mergeSort . map ( fst . fromJust .  BS.readInt :: BS.ByteString -> Int  )
. BS.lines

Mukeshs-MacBook-Pro:Puzzles mukeshtiwari\$ ghc  -fforce-recomp -O2  Inversion.hs
[1 of 1] Compiling Main             ( Inversion.hs, Inversion.o )
Mukeshs-MacBook-Pro:Puzzles mukeshtiwari\$ time ./Inversion <  IntegerArray.txt
2407905288

real	0m8.002s
user	0m7.881s
sys	0m0.038s
```

I tried to compare this solution with GeeksforGeeks‘s solution written in C and it was a complete surprise to me.

```Mukeshs-MacBook-Pro:Puzzles mukeshtiwari\$ time ./a.out <  IntegerArray.txt
Number of inversions are 2407905288

real	0m0.039s
user	0m0.036s
sys	0m0.002s
```

Almost 200 times faster! My Haskell intuition told me that I am doing certainly some wrong. I started analyzing the code and got the point. In inversionCnt function, I am doing extra work for computing the length of list u ( O ( n ) ) so rather than doing this extra work, I can pass the length.

```import Data.List
import Data.Maybe ( fromJust )
import qualified Data.ByteString.Lazy.Char8 as BS

inversionCnt :: [ Int ] -> [ Int ] -> [ Int ] -> Int -> Int -> ( Int , [ Int ] )
inversionCnt [] ys  ret _ cnt = ( cnt , reverse ret ++ ys )
inversionCnt xs []  ret _ cnt = ( cnt , reverse ret ++ xs )
inversionCnt u@( x : xs ) v@( y : ys )  ret n cnt
| x <= y = inversionCnt xs v  (  x : ret   )  ( pred n ) cnt
| otherwise = inversionCnt u ys  ( y : ret ) n ( cnt + n )

merge ::  ( Int , [ Int ] ) -> ( Int , [ Int ] ) -> ( Int , [ Int ] )
merge ( cnt_1 , xs ) ( cnt_2 , ys ) = ( cnt_1 + cnt_2 + cnt , ret ) where
( cnt , ret ) = inversionCnt xs ys [] ( length xs )  0

mergeSort ::  [ Int ] -> ( Int , [ Int ] )
mergeSort [ x ] = ( 0 , [ x ] )
mergeSort  xs   = merge ( mergeSort xs' ) ( mergeSort ys' ) where
( xs' , ys' ) = splitAt ( div ( length xs ) 2 ) xs

main =  BS.interact \$ ( \x -> BS.pack \$ show x ++ "\n" ) . fst
.  mergeSort . map ( fst . fromJust .  BS.readInt :: BS.ByteString -> Int  )
. BS.lines

Mukeshs-MacBook-Pro:Puzzles mukeshtiwari\$ time ./Inversion <  IntegerArray.txt
2407905288

real	0m0.539s
user	0m0.428s
sys	0m0.031s
```

Now 10 times slower and still lot of room for improvement but for now I am happy with this :). You can also try to solve INVCNT. Run this code on Ideone.

July 4, 2013

## Computing a^n using binary representation of natural number in Agda

While following the Agda tutorial, I wrote this code to compute an. Not very elegant example probably because I am not expert and still learning about dependent types. Maybe after getting some more experience and knowledge, I will try to prove the correctness and complexity of this algorithm. See the post of Twan van Laarhoven about proving correctness and complexity of merge sort in Agda.

```
module PowerFunction where

data ℕ⁺ : Set where
one : ℕ⁺
double : ℕ⁺ → ℕ⁺
double⁺¹ : ℕ⁺ → ℕ⁺

add : ℕ⁺ → ℕ⁺ → ℕ⁺
add one one = double one
add one ( double x ) = double⁺¹ x
add one ( double⁺¹ x ) = double ( add x one )
add ( double x ) one =  double⁺¹ x
add ( double x ) ( double y ) = double ( add x y )
add ( double x ) (  double⁺¹ y ) =  double⁺¹ (  add x y )
add (  double⁺¹ x ) one =   double (  add x one )
add (  double⁺¹ x ) (  double y ) =  double⁺¹ (  add x y  )
add (  double⁺¹ x ) (  double⁺¹ y ) = double ( add (  add x y ) one )

mult : ℕ⁺ → ℕ⁺ → ℕ⁺
mult x one = x
mult x ( double y ) = double ( mult x y )
mult x ( double⁺¹ y ) = add x ( double ( mult x y ) )

pow : ℕ⁺ → ℕ⁺ → ℕ⁺
pow one _ = one
pow x  one =  x
pow x ( double one ) = mult x x
pow x ( double y ) =  pow ( pow x y ) ( double one )
pow x ( double⁺¹ y ) =  mult x ( pow ( pow x y ) ( double one ) )

```

Computing 2 ^ 6
pow ( double one ) ( double ( double⁺¹ one ))
double (double (double (double (double (double one)))))
If you have suggestion then please let me know.

June 12, 2013

## ZeroMQ for distributed computing.

This post is influenced by ØMQ – The Guide By Pieter Hintjens and translation of codes in Haskell. I suggest you to read The Guide By Pieter Hintjens and if you are interested in Haskell code then you see these codes.

The client sends “Accept hello from Client. ” to the server, which replies with “I got you.”. This Haskell server opens a ØMQ socket on port 5555, reads requests on it, and replies with “I got you” to each request.The REQ-REP socket pair is in lockstep. The client issues send and then receive, in a loop (or once if that’s all it needs). Doing any other sequence (e.g., sending two messages in a row) will result in a return code of -1 from the send or receive call.

```
import System.ZMQ3
import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Lazy.Internal as BL
import Data.IORef
main = do
c <- context
s <- socket c Rep
bind s "tcp://127.0.0.1:5555"
counter <- newIORef 0
forever \$ do
print res
send' s [] ( BL.packChars \$ "I got you. " ++ show t )
modifyIORef counter ( +1 )
close s
destroy c
return ()

```

Client

```import System.ZMQ3
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Internal as BL
import Data.IORef

main = do
c <- context
s <- socket c Req
connect s "tcp://127.0.0.1:5555"
counter <- newIORef 0
forever \$ do
send' s [] ( BL.packChars \$ "Accept hello from Client. " ++ show t )
print msg
modifyIORef counter ( +1 )
return ()

```

Running a server with two clients.

```
Mukeshs-MacBook-Pro:ZMQ mukeshtiwari\$ ./ZeroMqServer
"Accept hello from Client. 0"
"Accept hello from Client. 1"
"Accept hello from Client. 2"
"Accept hello from Client. 3"
"Accept hello from Client. 4"
"Accept hello from Client. 5"
"Accept hello from Client. 6"
"Accept hello from Client. 7"
"Accept hello from Client. 8"
"Accept hello from Client. 9"
"Accept hello from Client. 10"
"Accept hello from Client. 11"
"Accept hello from Client. 12"
"Accept hello from Client. 13"
"Accept hello from Client. 14"
"Accept hello from Client. 15"

"Accept hello from Client. 0"
"Accept hello from Client. 228"
"Accept hello from Client. 1"
"Accept hello from Client. 229"
"Accept hello from Client. 2"
"Accept hello from Client. 230"
"Accept hello from Client. 3"
"Accept hello from Client. 231"
"Accept hello from Client. 4"
"Accept hello from Client. 232"

First client.
Mukeshs-MacBook-Pro:ZMQ mukeshtiwari\$ ./ZeroMqClient
"I got you. 0"
"I got you. 1"
"I got you. 2"
"I got you. 3"
"I got you. 4"
"I got you. 5"
"I got you. 6"
"I got you. 7"
"I got you. 8"
"I got you. 9"
"I got you. 10"
"I got you. 11"
"I got you. 12"

Second client
Mukeshs-MacBook-Pro:ZMQ mukeshtiwari\$ ./ZeroMqClient
"I got you. 228"
"I got you. 230"
"I got you. 232"
"I got you. 234"
"I got you. 236"
"I got you. 238"
"I got you. 240"
"I got you. 242"
"I got you. 244"
"I got you. 246"
"I got you. 248"
"I got you. 250"
"I got you. 252"
"I got you. 254"
"I got you. 256"
"I got you. 258"
"I got you. 260"
"I got you. 262"
"I got you. 264"
"I got you. 266"
```

### Publish-Subscribe

Data publishing server which publishes weather data for zip codes in range 500 and 2000.

```import System.ZMQ3
import qualified Data.ByteString.Char8 as BS hiding ( putStrLn )
import qualified Data.ByteString.Lazy.Internal as BL
import System.Random

main = do
c <- context
publisher <- socket c Pub
bind publisher "tcp://127.0.0.1:5556"
bind publisher "ipc://weather.ipc"
forever \$ do
zipcode <- randomRIO ( ( 500 , 2000 ) ::  ( Int , Int ) )
temp <- randomRIO ( 10 , 45 ) :: IO Int
relhum <- randomRIO ( 0 , 100 ) :: IO Int
putStrLn \$ show zipcode ++ " " ++ show temp ++ " " ++ show relhum
send' publisher [] ( BL.packChars \$ show zipcode ++ " " ++ show temp ++
" " ++  show relhum )
close publisher
destroy c
return ()
```

Client who is only interested in two zip codes.

```import System.ZMQ3
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Internal as BL
import System.Random

main = do
c <- context
subscriber <- socket c Sub
connect subscriber "tcp://127.0.0.1:5556"
subscribe subscriber ( BS.pack "1000" )
subscribe subscriber ( BS.pack "1010" )
forever \$ do
print update

close subscriber
destroy c

```

Our server is publishing lot of data but client is only interested in two zip codes.

```

Mukeshs-MacBook-Pro:ZMQ mukeshtiwari\$ ./ZeroMqWeatherPubServer
1568 27 85
924 41 46
1461 15 46
1867 44 28
1013 23 100
1052 13 6
1720 45 6
1480 12 94
1852 33 4
1295 20 6
925 18 77
935 37 94
1670 11 6
1285 39 38
1613 44 99
1888 26 62
1011 21 45
993 45 45
1402 26 86
1639 13 65
1285 18 40
1960 38 18
1160 27 39
1374 16 59
665 25 22

Mukeshs-MacBook-Pro:ZMQ mukeshtiwari\$ ./ZeroMqWeatherClient
"1000 34 89"
"1010 19 70"
"1010 15 86"
"1000 38 57"
"1010 12 42"
"1000 25 1"
"1000 28 78"
"1000 25 16"
"1000 28 82"
"1010 28 98"
"1000 12 77"
"1010 11 16"
"1010 44 14"
"1010 12 89"
"1000 32 8"
"1010 37 55"
"1010 17 21"
"1000 13 96"
"1000 18 51"
"1010 16 38"
"1000 18 21"
"1010 37 60"
"1010 17 25"
"1000 33 43"
"1000 34 44"
"1010 33 78"
"1010 35 63"
"1000 39 50"
"1000 45 70"
"1000 26 3"
"1010 34 12"
"1010 26 3"
"1000 32 75"
"1010 14 68"
"1000 44 75"
"1010 27 54"
"1000 21 39"
"1010 12 65"
"1010 43 29"
"1010 25 60"
```

### Divide and Conquer

For this problem we will calculate the number of primes less than $10^{7}$. Our ventilator will push the task to workers and they will perform the task. After finishing the job, they will send the result back to sink.

Ventilator

```import System.ZMQ3
import qualified Data.ByteString.Char8 as BS
import Data.ByteString.Lazy.Internal as BL
import Data.IORef

main = do
c <- context
sender <- socket c Push
bind sender "tcp://127.0.0.1:5557"

sink <- socket c Push
connect sink "tcp://127.0.0.1:5558"

putStrLn "Press enter when workers are ready."
_ <- getChar
putStrLn "Sending the task to workers.\n"

send' sink [] ( BL.packChars . show \$ 0 )

forM_ [ 0..9999 ] \$ \ i -> do
putStrLn \$ "Sending the range [ " ++ show ( 1000 * i + 1 ) ++ " .. " ++ show  ( 1000 * i + 1 + 999 ) ++ "] to worker for primality testing."
send' sender [] ( BL.packChars . show \$ 1000 * i + 1 )

close sink
close sender
destroy c

```

Worker for computing the prime number.

```import System.ZMQ3
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Internal as BL
import Data.IORef
import Data.Bits

powM :: Integer -> Integer -> Integer ->  Integer
powM a d n = powM' a d n where
powM' a d n
| d == 0 = 1
| d == 1 = mod a n
| otherwise = mod q n  where
p = powM'  ( mod ( a^2 ) n ) ( shiftR d 1 ) n
q = if (.&.) d 1 == 1 then mod ( a * p ) n else p

calSd :: Integer -> ( Integer , Integer )
calSd n = ( s , d ) where
s = until ( \x -> testBit ( n - 1) ( fromIntegral x ) )  ( +1 ) 0
d = div ( n - 1 ) (  shiftL 1 ( fromIntegral s )  )

rabinMiller::Integer->Integer->Integer->Integer-> Bool
rabinMiller  n s d a
| n == a = True
| otherwise =  case x == 1 of
True -> True
_ ->   any ( == pred n ) . take ( fromIntegral s )
. iterate (\e -> mod ( e^2 ) n ) \$ x
where
x = powM a d n

isPrime::Integer-> Bool
isPrime n
| n <= 1 = False
| n == 2 = True
| even n = False
| otherwise  = all ( == True ) . map ( rabinMiller n s d ) \$  [ 2 , 3 , 5 , 7 , 11 , 13 , 17 ] where
( s , d ) = calSd n

primeRange :: Integer -> Integer -> [ Bool ]
primeRange m n = map isPrime [ m .. n ]

main = do
c <- context

sender <- socket c Push
connect sender "tcp://127.0.0.1:5558"

forever \$ do
let n = read . BS.unpack \$ num  :: Integer
let len = length . filter ( == True ) . primeRange  n  \$  n + 999
putStrLn \$ "Received range [ " ++  show n ++ " .. " ++ show ( n + 999 ) ++ "  and number of primes in this range is " ++ show len
send' sender [] ( BL.packChars . show \$ len  )

close sender
destroy c

```

Sink for collecting the results.

```import System.ZMQ3
import qualified Data.ByteString.Char8 as BS
import qualified Data.ByteString.Lazy.Internal as BL
import Data.IORef

main = do
c <- context

print m
sum <- newIORef  0
forM_ [ 1.. 10000 ] \$ \i -> do
let n = read . BS.unpack \$ num :: Integer
putStrLn \$ "Received a number " ++ show n ++ " from one of worker"
modifyIORef sum ( + n )

putStrLn \$ "Total number of primes in the range is " ++ show t
destroy c
```

Running Ventilator, 3 workers and sink

```Mukeshs-MacBook-Pro:ZMQ mukeshtiwari\$ ./TaskVent
Sending the range [ 9992001 .. 9993000] to worker for primality testing.
Sending the range [ 9993001 .. 9994000] to worker for primality testing.
Sending the range [ 9994001 .. 9995000] to worker for primality testing.
Sending the range [ 9995001 .. 9996000] to worker for primality testing.
Sending the range [ 9996001 .. 9997000] to worker for primality testing.
Sending the range [ 9997001 .. 9998000] to worker for primality testing.
Sending the range [ 9998001 .. 9999000] to worker for primality testing.
Sending the range [ 9999001 .. 10000000] to worker for primality testing.

Received range [ 9978001 .. 9979000  and number of primes in this range is 60
Received range [ 9981001 .. 9982000  and number of primes in this range is 49
Received range [ 9984001 .. 9985000  and number of primes in this range is 69
Received range [ 9987001 .. 9988000  and number of primes in this range is 57
Received range [ 9990001 .. 9991000  and number of primes in this range is 60
Received range [ 9993001 .. 9994000  and number of primes in this range is 71
Received range [ 9996001 .. 9997000  and number of primes in this range is 58
Received range [ 9999001 .. 10000000  and number of primes in this range is 53

Received range [ 9982001 .. 9983000  and number of primes in this range is 69
Received range [ 9985001 .. 9986000  and number of primes in this range is 62
Received range [ 9988001 .. 9989000  and number of primes in this range is 58
Received range [ 9991001 .. 9992000  and number of primes in this range is 57
Received range [ 9994001 .. 9995000  and number of primes in this range is 64
Received range [ 9997001 .. 9998000  and number of primes in this range is 67
Received range [ 9986001 .. 9987000  and number of primes in this range is 59
Received range [ 9989001 .. 9990000  and number of primes in this range is 58
Received range [ 9992001 .. 9993000  and number of primes in this range is 58
Received range [ 9995001 .. 9996000  and number of primes in this range is 62
Received range [ 9998001 .. 9999000  and number of primes in this range is 64

Sink
Received a number 53 from one of worker
Received a number 67 from one of worker
Received a number 64 from one of worker
Received a number 52 from one of worker
Received a number 59 from one of worker
Received a number 58 from one of worker
Received a number 58 from one of worker
Received a number 62 from one of worker
Received a number 64 from one of worker
Total number of primes in the range is 664579
```

First start all the workers and sink and then run ventilator. See more about distributed computing in Haskell Eden and distributed-process. If you have any suggestion then please let me know. Some of the contents and images are taken from Pieter Hintjens‘s tutorial by his permission.

May 13, 2013

## Missionaries and cannibals problem

In the missionaries and cannibals problem, three missionaries and three cannibals must cross a river using a boat which can carry at most two people, under the constraint that, for both banks, if there are missionaries present on the bank, they cannot be outnumbered by cannibals (if they were, the cannibals would eat the missionaries.) The boat cannot cross the river by itself with no people on board. We can solve this problem using depth first search. Representing the states as number of missionaries, cannibals and boat location in following way.

```
data Side = Side { missionaries :: Int , cannibals :: Int } deriving ( Show , Eq  )
data Loc = L | R deriving ( Show , Eq  )
data State = State { left :: Side , right :: Side , bloc :: Loc } deriving ( Show , Eq  )

```

Target is to move every missionaries and cannibals from left to right so our initial state is initialState and final state is finalState.

```
initialState = State { left =  Side 3 3  , right =  Side 0 0  , bloc = L }
finalState = State  { left =  Side 0 0  , right = Side 3 3  , bloc = R }

```

Possible movements
1. move ( 2 , 0 )
2. move ( 1 , 0 )
3. move ( 1 , 1 )
4. move ( 0 , 1 )
5. move ( 0 , 2 )
where move ( M , C ) is movement of M missionaries and C cannibals from one side to other side depending on boat location. If boat location is left then move ( M , C ) is moving M missionaries and C cannibals from left to right and vice versa. Using depth first search, we can explore every possible movement

```path :: [ State ] -> [ State ] -> [ State ]
path []   vis = reverse vis
path  ( x : xs )  vis
| x  == finalState  = reverse ( x : vis )
| elem x vis = path xs vis
| otherwise = path xs'  vis'  where
vis'  = x : vis
xs' =   ( filter  isLegal  ( move x ) ) ++ xs
```

Encoding the moves and testing the legality

```
move :: State -> [ State ]
move ( State ( Side ml cl ) ( Side mr cr ) L ) =
[ State ( Side ( ml - 2 ) cl ) ( Side ( mr + 2 ) cr ) R
, State ( Side ( ml - 1 ) cl ) ( Side ( mr + 1 ) cr ) R
, State ( Side ( ml - 1 ) ( cl - 1 ) ) ( Side ( mr + 1 ) ( cr + 1 ) ) R
, State ( Side ml ( cl - 2 ) ) ( Side mr ( cr + 2 ) ) R
, State ( Side ml ( cl - 1 ) ) ( Side mr ( cr + 1 ) ) R
]
move  ( State ( Side ml cl ) ( Side mr cr ) R ) =
[ State ( Side ( ml + 2 ) cl ) ( Side ( mr - 2 ) cr ) L
, State ( Side ( ml + 1 ) cl ) ( Side ( mr - 1 ) cr ) L
, State ( Side ( ml + 1 ) ( cl + 1 ) ) ( Side ( mr - 1 ) ( cr - 1 ) ) L
, State ( Side ml ( cl + 2 ) ) ( Side mr ( cr - 2 ) ) L
, State ( Side ml ( cl + 1 ) ) ( Side mr ( cr - 1 ) ) L
]

isLegal :: State -> Bool
isLegal ( State ( Side ml cl ) ( Side mr cr ) y )
| ml == 0 = mr >= cr  && cr >= 0
| mr == 0 = ml >= cl  && cl >= 0
| otherwise = ml >= cl && mr >= cr && cl >= 0 && cr >= 0

```

Complete source code ( In case if you are lazy )

```import Data.List

data Side = Side { missionaries :: Int , cannibals :: Int } deriving ( Show , Eq  )
data Loc = L | R deriving ( Show , Eq  )
data State = State { left :: Side , right :: Side , bloc :: Loc } deriving ( Show , Eq  )

initialState = State { left =  Side 3 3  , right =  Side 0 0  , bloc = L }
finalState = State  { left =  Side 0 0  , right = Side 3 3  , bloc = R }

path :: [ State ] -> [ State ] -> [ State ]
path []   vis = reverse vis
path  ( x : xs )  vis
| x  == finalState  = reverse ( x : vis )
| elem x vis = path xs vis
| otherwise = path xs'  vis'  where
vis'  = x : vis
xs' =   ( filter  isLegal  ( move x ) ) ++ xs

move :: State -> [ State ]
move ( State ( Side ml cl ) ( Side mr cr ) L ) =
[ State ( Side ( ml - 2 ) cl ) ( Side ( mr + 2 ) cr ) R
, State ( Side ( ml - 1 ) cl ) ( Side ( mr + 1 ) cr ) R
, State ( Side ( ml - 1 ) ( cl - 1 ) ) ( Side ( mr + 1 ) ( cr + 1 ) ) R
, State ( Side ml ( cl - 2 ) ) ( Side mr ( cr + 2 ) ) R
, State ( Side ml ( cl - 1 ) ) ( Side mr ( cr + 1 ) ) R
]
move  ( State ( Side ml cl ) ( Side mr cr ) R ) =
[ State ( Side ( ml + 2 ) cl ) ( Side ( mr - 2 ) cr ) L
, State ( Side ( ml + 1 ) cl ) ( Side ( mr - 1 ) cr ) L
, State ( Side ( ml + 1 ) ( cl + 1 ) ) ( Side ( mr - 1 ) ( cr - 1 ) ) L
, State ( Side ml ( cl + 2 ) ) ( Side mr ( cr - 2 ) ) L
, State ( Side ml ( cl + 1 ) ) ( Side mr ( cr - 1 ) ) L
]

isLegal :: State -> Bool
isLegal ( State ( Side ml cl ) ( Side mr cr ) y )
| ml == 0 = mr >= cr  && cr >= 0
| mr == 0 = ml >= cl  && cl >= 0
| otherwise = ml >= cl && mr >= cr && cl >= 0 && cr >= 0

```

``` Main> path [ initialState ] [] [State {left = Side {missionaries = 3, cannibals = 3}, right = Side {missionaries = 0, cannibals = 0}, bloc = L},State {left = Side {missionaries = 2, cannibals = 2}, right = Side {missionaries = 1, cannibals = 1}, bloc = R},State {left = Side {missionaries = 3, cannibals = 2}, right = Side {missionaries = 0, cannibals = 1}, bloc = L},State {left = Side {missionaries = 3, cannibals = 0}, right = Side {missionaries = 0, cannibals = 3}, bloc = R},State {left = Side {missionaries = 3, cannibals = 1}, right = Side {missionaries = 0, cannibals = 2}, bloc = L},State {left = Side {missionaries = 1, cannibals = 1}, right = Side {missionaries = 2, cannibals = 2}, bloc = R},State {left = Side {missionaries = 2, cannibals = 2}, right = Side {missionaries = 1, cannibals = 1}, bloc = L},State {left = Side {missionaries = 0, cannibals = 2}, right = Side {missionaries = 3, cannibals = 1}, bloc = R},State {left = Side {missionaries = 0, cannibals = 3}, right = Side {missionaries = 3, cannibals = 0}, bloc = L},State {left = Side {missionaries = 0, cannibals = 1}, right = Side {missionaries = 3, cannibals = 2}, bloc = R},State {left = Side {missionaries = 1, cannibals = 1}, right = Side {missionaries = 2, cannibals = 2}, bloc = L},State {left = Side {missionaries = 0, cannibals = 0}, right = Side {missionaries = 3, cannibals = 3}, bloc = R}] *Main> map bloc . path [ initialState ] \$ [] [L,R,L,R,L,R,L,R,L,R,L,R] ```
If you have any suggestion or comment then please let me know.

April 19, 2013

## SPOJ Pell (Mid pelling)

Pell (Mid pelling) is related to Pell’s equation. It is similar to Project Euler 66 and SPOJ EQU2. I just wrote the quick solution from mathworld but I found Chakravala method very interesting. Accepted Haskell code.

```import qualified Data.ByteString.Char8 as BS
import Data.List
import Data.Maybe ( fromJust )

continuedFraction :: Integer -> [ Integer ]
continuedFraction n = map ( \ ( a , _ , _ ) -> a ) . iterate fun \$ ( d , 0 , 1 )
where
d = truncate . sqrt . fromIntegral \$ n
fun ( a0 , p0 , q0 ) = ( a1 , p1 , q1 ) where
p1 = a0 * q0 - p0
q1 = div ( n - p1 ^ 2 ) q0
a1 = div ( d + p1 ) q1

pellSolver :: Integer -> BS.ByteString
pellSolver n
| perfectSqr n = BS.pack. show \$ ( -1 )
| otherwise =  ( BS.pack . show \$ p ) `BS.append` ( BS.pack " " )
`BS.append` ( BS.pack.show \$ q ) where
d = truncate . sqrt . fromIntegral \$ n
lst = takeWhile ( /= 2 * d ) . continuedFraction \$ n
len = length lst
r@( x : y : xs ) = take ( if even len then len else 2 * len ) .
continuedFraction \$ n
( p0 , p1 , q0 , q1 ) = ( x , x * y + 1 , 1 , y )
( p , _ ) = foldl' compute ( p1 , p0 ) \$ xs
( q , _ ) = foldl' compute ( q1 , q0 ) \$ xs
compute :: ( Integer , Integer ) -> Integer -> ( Integer , Integer )
compute ( p1 , p0 ) a = ( a * p1 + p0 , p1 )

perfectSqr :: Integer -> Bool
perfectSqr n = d * d == n where
d = truncate . sqrt . fromIntegral \$ n

main = BS.interact \$  BS.unlines . map ( pellSolver . readI ) . tail . BS.lines
```

March 23, 2013

## SPOJ EMAIL ID

Finally solved EMAIL ID using python though it was very hard for me to switch from Haskell to python. While doing this problem, I learned quite a lot about regular expressions, found some cool site like pythontutor and problem solving with python . Accepted code in python.

```
import re

if __name__ == "__main__":
n = int ( raw_input() )
c = 1
while c <= n :
email =  re.findall ( "[a-zA-Z0-9][a-zA-Z0-9._]{4,}@[a-zA-Z0-9]+\.(?:com|edu|org|co\.in)", raw_input() )
t = len ( email )
print 'Case #' + str ( c ) + ': ' + str ( t )
for i in xrange ( t ) : print email[i]
c += 1

```

March 11, 2013

## My experience with online learning

I am one big confused soul who is always curious for learning. I found Coursera and Udacity very helpful. I try to take as many courses as possible but recently I took the Heterogeneous Parallel Programming by Professor Wen-mei W. Hwu and it was fun course. The video lectures were excellent and assignments were not very hard. They were designed to make us familiar with basics of cuda programming and apart from that I got certificate signed by Professor Wen-mei W. Hwu :). While doing some more research about heterogeneous computing which involves CPU, GPU and FPGA all together in single system, today I found FPGA Programming for the Masses. There are two promising technologies, one from Altera and other is Liquid Metal from IBM.

Altera OpenCL-to-FPGA Framework.
Altera proposed a framework for synthesizing bitstreams from OpenCL. The framework consists of a kernel compiler, a host library, and a system integration component. The kernel compiler, based on the open source LLVM compiler infrastructure, synthesizes OpenCL kernel code into hardware. The host library provides APIs and bindings for establishing communication between the host part of the application running on the processor and the kernel part of the application running on the FPGA. The system integration component wraps the kernel code with memory controllers and a communication interface (such as PCIe)
Liquid Metal.
The Liquid Metal project at IBM aims to provide not only high-level synthesis for FPGAs,1 but also, more broadly, a single unified language for programming heterogeneous architectures. The project offers a language called Lime, which can be used to program hardware (FPGAs), as well as software running on conventional CPUs and more exotic architectures such as GPUs. The Lime language was founded on principles that eschew the complicated program analysis that plagues C-based frameworks, while also offering powerful programming models that espouse the benefits of functional and stream-oriented programming.
Heterogeneous parallel programming looks very promising but still long way to go. My certificate

.

March 9, 2013

## Parsing Email ID

Now a days I am exploring one of the most awesome feature of Haskell, parsing. There are lot of parsing libraries but Parsec is the popular one. This parsing code is written for SPOJ EMAIL ID problem ( Unfortunately it’s getting time limit exceed. I have seen couple of python solution accepted so I am hopeful that there must be another algorithm probably using regular expressions to solve the problem ) but you can build more sophisticated email-id parser by adding more functionality. Tony Morris excellent parsing tutorial is must read.

```import Data.List
import qualified Text.Parsec.ByteString as PB
import Text.Parsec.Prim
import Text.Parsec.Char
import Text.Parsec.Combinator
import qualified Data.ByteString.Char8 as BS
import Control.Applicative hiding ( ( <|> ) , many )

validChars :: PB.Parser Char
validChars  = alphaNum <|> oneOf "._"

dontCare :: PB.Parser Char
dontCare = oneOf "~!@#\$%^&*()<>?,."

{--
_ <- many dontCare
fi <- alphaNum
se <- validChars
th <- validChars
fo <- validChars
ft <- validChars
let addr = fi : se : th : fo : ft : restAddr
char '@'
dom <- many1 alphaNum
rest <- try ( string ".com" <|> string ".org"
<|>  string ".edu" ) <|> try ( string ".co.in" )
_ <- many dontCare
return \$  addr ++ (  '@': dom ++ rest )

--}

emailAddress = conCatfun <\$> ( many dontCare *> alphaNum ) <*> validChars <*>
validChars <*> validChars <*> validChars <*> many alphaNum  <*>
( char '@' *> many1 alphaNum ) <*> ( try ( string ".com" <|>
string ".org" <|>  string ".edu" ) <|> try ( string ".co.in" )
<* many dontCare ) where
conCatfun a b c d e f dom rest =
( a : b : c : d : e : f ) ++ ( '@' : dom ) ++ rest

collectEmail :: BS.ByteString -> String
collectEmail email = case  parse emailAddress "" email of
Left err ->  ""

process :: ( Int , [ String ] ) -> BS.ByteString
process ( k , xs ) = ( BS.pack "Case " ) `BS.append` ( BS.pack . show \$ k )
`BS.append` ( BS.pack ": " ) `BS.append` ( BS.pack . show . length \$ xs )
`BS.append` ( BS.pack "\n" ) `BS.append` ( BS.pack
(  unlines . filter ( not . null ) \$  xs ) )

main = BS.interact \$ BS.concat .  map process . zip [ 1.. ] . map ( map collectEmail .
BS.words ) . tail . BS.lines

```
```Mukeshs-MacBook-Pro:Haskell mukeshtiwari\$ cat t.txt
2
svm11@gmail.com
svm11@gmail.com svm12@gmail.co.in  ~!@#\$%^&*()<>?svm12@gmail.co.in~!@#\$%^&*()
Case 1: 1
svm11@gmail.com
Case 2: 2
svm11@gmail.com
svm12@gmail.co.in
svm12@gmail.co.in
```

#### Update

I tried again to solve this problem using regular expression. Following the tutorial, I wrote this code but I got compiler error because of old version of ghc on SPOJ ( GHC-6.10.4 ). It’s working fine on my system but I still have to test if it is correct and fast enough to get accepted.

```import Data.List
import Text.Regex.Posix
import qualified Data.ByteString.Char8 as BS

pat :: BS.ByteString
pat = BS.pack "[^~!@#\$%^&*()<>?,.]*[a-zA-Z0-9][a-zA-Z0-9._][a-zA-Z0-9._][a-zA-Z0-9._][a-zA-Z0-9._][a-zA-Z0-9._]*@[a-zA-Z0-9]+.(com|edu|org|co.in)[^~!@#\$%^&*()<>?,.a-zA-Z0-9]*"

collectEmail :: BS.ByteString -> BS.ByteString
collectEmail email = ( =~ ) email pat

process :: ( Int , [ BS.ByteString ] ) -> BS.ByteString
process ( k , xs ) = ( BS.pack "Case " ) `BS.append` ( BS.pack . show \$ k )
`BS.append` ( BS.pack ": " ) `BS.append` ( BS.pack . show . length \$ xs )
`BS.append` ( BS.pack "\n" ) `BS.append` ( BS.unlines xs )

main = BS.interact \$ BS.concat .  map process . zip [ 1 .. ] .
map ( filter ( not . BS.null ) . map collectEmail . BS.words ) .
tail . BS.lines
```
```Mukeshs-MacBook-Pro:SPOJ mukeshtiwari\$ cat t.txt
2
svm11@gmail.com
svm11@gmail.com svm12@gmail.co.in %&^%&%&%&%&^%&^%&^%&^mukeshtiwari.iiitm@gmail.com%&%^&^%&%&%&%&^%&%&^%&^%&^% %\$%\$#%#%#%#%\$#%&%&%&tiwa@gmail.com
Mukeshs-MacBook-Pro:SPOJ mukeshtiwari\$ ./Spoj_11105 < t.txt
Case 1: 1
svm11@gmail.com
Case 2: 3
svm11@gmail.com
svm12@gmail.co.in
mukeshtiwari.iiitm@gmail.com
```

March 8, 2013

## Learning Agda

Finally I am feeling bit comfortable with Agda and feeling great :). I started reading Ulf Norell‘s Dependently Typed Programming in Agda. Tutorials on Agda-wiki , AgdaTutorial , papers which mention Agda , stackoverflow post, Introduction to Agda and Programming in Martin-Löf’s Type Theory. I wrote some of the codes from the paper. You can also try a similar language Idris ( See the stackoverflow post about difference between these languages ).

```module Basic where

data Bool : Set where
true : Bool
false : Bool

not : Bool → Bool
not true = false
not false = true

or : Bool → Bool → Bool
or false false = false
or _ _ = true

and : Bool → Bool → Bool
and true true = true
and _ _ = false

data ℕ  : Set where
zero : ℕ
suc : ℕ → ℕ

_+_ : ℕ → ℕ → ℕ
zero + m = m
suc n + m = suc ( n + m )

_⋆_ : ℕ → ℕ → ℕ
zero ⋆ m = zero
suc n ⋆ m =   ( n ⋆ m ) + m

fold-ℕ : ℕ → ( ℕ → ℕ ) → ℕ → ℕ
fold-ℕ u _ zero = u
fold-ℕ u f ( suc n ) = f ( fold-ℕ u f n )

if_then_else_ : { A : Set } → Bool → A → A → A
if true then x else y = x
if false then x else y = y

data List ( A : Set ) : Set where
[] : List A
_::_ : A → List A -> List A

identity : ( A : Set ) → A → A
identity A x = x

zero′ : ℕ
zero′ = identity ℕ zero

apply : ( A : Set ) ( B : A → Set ) → ( ( x : A ) → B x ) → ( a : A ) → B a
apply A B f a = f a

identity₂ : ( A : Set ) → A → A
identity₂ = \A x → x

identity₃ : ( A : Set ) → A → A
identity₃ = \(A : Set ) ( x : A ) → x

identity₄ : ( A : Set ) → A → A
identity₄ = \ ( A : Set ) x → x

id : { A : Set } → A → A
id x = x

true′ : Bool
true′ = id true

one : ℕ
one = identity _ ( suc zero )

_∘_ : { A : Set } { B : A → Set } { C : ( x : A ) → B x → Set }
( f : { x : A } ( y : B x ) → C x y ) ( g : ( x : A ) → B x ) ( x : A )
→ C x ( g x )
( f ∘ g ) x = f ( g x )

plus-two = suc ∘  suc
plus-three = suc ∘ ( suc ∘ suc )

map : { A B : Set } → ( A → B ) → List A → List B
map f [] = []
map f ( x :: xs ) = f x :: map f xs

_++_ : { A : Set } → List A → List A → List A
[] ++ ys = ys
( x :: xs ) ++ ys = x :: ( xs ++ ys )

foldl : { A B : Set } → ( A → B → A ) → A → List B → A
foldl f val [] = val
foldl f val ( x :: xs ) = foldl f ( f val x ) xs

foldr : { A B : Set } → ( A → B → B ) → B → List A → B
foldr f val [] = val
foldr f val ( x :: xs ) = f x ( foldr f val xs )

--type of Vec A is  ℕ → Set. This mean Vec A is family of types indexed by
-- natural numbers

data Vec ( A : Set ) : ℕ →  Set where
[] : Vec A zero
_::_ : { n : ℕ } → A → Vec A n → Vec A ( suc n )

head : { A : Set } { n : ℕ } → Vec A ( suc n )  → A
head ( x :: xs ) = x

vmap : { A B : Set } { n : ℕ } → ( A → B ) → Vec A n → Vec B n
vmap f [] = []
vmap f ( x :: xs ) = f x :: vmap f xs

data Vec₂ ( A : Set ) : ℕ → Set where
nil : Vec₂ A zero
cons : ( n : ℕ ) → A → Vec₂ A n → Vec₂ A ( suc n )
{--
The rule for when an argument should be dotted is:
if there is a unique
type correct value for the argument it should be dotted
--}

vmap₂ : { A B : Set } ( n : ℕ ) → ( A → B ) → Vec₂ A n → Vec₂ B n
vmap₂ .zero f nil = nil
vmap₂ .( suc n ) f ( cons n x xs ) = cons n  ( f x ) ( vmap₂ n f xs )

vmap₃ : { A B : Set } ( n : ℕ ) → ( A → B ) → Vec₂ A n → Vec₂ B n
vmap₃ zero f nil = nil
vmap₃ ( suc n ) f ( cons .n x xs ) = cons n ( f x ) ( vmap₃ n f xs )

pow : ℕ →  ℕ  →  ℕ
pow _  zero = suc zero
pow a ( suc n ) =  a ⋆ pow a n

t : ℕ
t = pow ( suc ( suc  zero ) ) ( suc ( suc ( suc zero ) ) )

```

To evaluate the expression , type C-c C-n. Here is the output of t
suc (suc (suc (suc (suc (suc (suc (suc zero))))))).

February 10, 2013


text:
# Diffraction Grating lab

1. May 7, 2008

### salsabel

You find two unlabelled diffraction gratings in your lab. From purchase records, you know that one grating has 5000 lines/cm, while the other has 10 000 lines/cm. Given the following equipment, describe how you would determine which is the grating with 10 000 lines/cm:
• Red laser
• detection screen
• the two unknown diffraction gratings
describe what difference you would observe.
n = d sin(theta)
d=1/5*105 = 2*10-6
d=1/1*106= 10-6

2. May 7, 2008

### oedipa maas

At what angle would you see the first maximum for the 5000 line grating? At what angle would you see the first maximum for the 10000 line grating?

If you had a screen, say, 10 m away from the 5000 line grating, how far would the central maximum be from the first, second and nth maximas? What about for the 10000 line grating?

3. May 7, 2008

### AstroRoyale

You missed a $$\lambda$$ in your equation. It should read

$$n \lambda = d sin(\theta)$$

Anyway, what do you expect the difference between the interference patterns to be when you shine the laser on the two different gratings? Where is the first order (n=1) maximum with each grating?

Edit:
And I see oedipa maas just posted similar remarks. . .

Last edited: May 7, 2008
4. May 11, 2008

### salsabel

thats what i got
suppose the wavelength= 1cm = 1*10^-9
and m= 1
when d= 2*10^-6 m/line
theta= 0.029

when d= 10^-6
theta= 0.057
that's all what i got


text:
Properties

 Label 18496t Number of curves $2$ Conductor $18496$ CM no Rank $0$ Graph

Related objects

Show commands for: SageMath
sage: E = EllipticCurve("18496.f1")

sage: E.isogeny_class()

Elliptic curves in class 18496t

sage: E.isogeny_class().curves

LMFDB label Cremona label Weierstrass coefficients Torsion structure Modular degree Optimality
18496.f2 18496t1 [0, 1, 0, -1252, -36810] [2] 18432 $$\Gamma_0(N)$$-optimal
18496.f1 18496t2 [0, 1, 0, -25817, -1604057] [2] 36864

Rank

sage: E.rank()

The elliptic curves in class 18496t have rank $$0$$.

Modular form 18496.2.a.f

sage: E.q_eigenform(10)

$$q - 2q^{3} + 2q^{5} + 2q^{7} + q^{9} + 2q^{11} - 2q^{13} - 4q^{15} - 4q^{19} + O(q^{20})$$

Isogeny matrix

sage: E.isogeny_class().matrix()

The $$i,j$$ entry is the smallest degree of a cyclic isogeny between the $$i$$-th and $$j$$-th curve in the isogeny class, in the Cremona numbering.

$$\left(\begin{array}{rr} 1 & 2 \\ 2 & 1 \end{array}\right)$$

Isogeny graph

sage: E.isogeny_graph().plot(edge_labels=True)

The vertices are labelled with Cremona labels.


text:
# DAVIDSTUTZ

12thJUNE2015

Ganin and Lempitsky propose to use a combination of convolutional neural networks and $K$-nereast-neighbor for edge detection. Their implementation is based on the implementation and architecture by Krizhevsky et al. [1], see here, however code is not publicly available. Similar to [2], the convolutional neural network is trained on patches of fixed size. However, as the desired output annotation may have high dimension, principal component analysis (e.g. see [3]) is employed to reduce the target dimensionality. The network is then trained on these new target outputs. Finally, $1$-nearest-neighbor on a subset of the training set is used to annotate new test samples. In practice, Ganin and Lempitsky use a committee of these so called $N^4$-fields (convolutional neural network + $1$-nearest-neighbor) and average across predictions.


text:
# Sinc functions

• Feb 17th 2008, 04:44 PM
crane_2001
Sinc functions
If sinc(x)=0.707.. what is x..
How do we calculate this
Thanks
• Feb 17th 2008, 05:18 PM
Plato
Quote:

Originally Posted by crane_2001
If sinc(x)=0.707.. what is x.. How do we calculate this?

What is the function $sinc(x)$?
• Feb 17th 2008, 06:16 PM
TwistedOne151
Are you using the normalized or unnormalized sine cardinal function?
-Kevin C.
• Feb 17th 2008, 06:18 PM
crane_2001
sinc function
normalised
• Feb 17th 2008, 07:48 PM
mr fantastic
Quote:

Originally Posted by crane_2001
If sinc(x)=0.707.. what is x..
How do we calculate this
Thanks

Quote:

Originally Posted by crane_2001
normalised

You're asking how to solve $\frac{\sin (\pi x)}{\pi x} = 0.707 ..$. You can't get an exact value in closed form. It's an example of a transcendental equation.

If you're only interested in calculatiing a numerical approximation to the exact value, then there are many options.


text:
# Tag Info

1

Looking at your code, you seem to be mixing the risk minimization formulation of the mean-variance problem with the risk aversion formulation. Both formulations include the "budget" constraint, that the sum of the weights equal 1, and can require that each of the weights be greater than zero, the "long-only" inequality constraints. In the risk minimization ...

2

As regards the free sources, the best place where you can find material about credit risk management is defaultrisk.com; it is a website where are collected (almost) all academic (and not) articles and working paper, references and researchers. Moreover, as regards the forums, I think you should try visiting Credit Risk Group at Linkedin; it is a very ...

0

FinAnalytica Inc www.finanalytica.com has a multi-asset class commercial implementation including fitted classical tempered stable distributions and fitted skewed t-distributions (for lower frequency data) in its software named Cognity. You should talk to those guys. Their backtests do all the talking...risk forecasts from left tail all the way through to ...

1

This problem is from the exercise for Chapter 2 of Kerry Back's Asset Pricing Book. The setup of the problem is rather simple. You want to \begin{equation*} \begin{aligned} & \underset{\phi}{\text{maximize}} & & \phi'\mu + \frac{1}{2} \alpha \phi' \Sigma \phi\\ & \text{subject to} & & 1'\phi = w_0 \end{aligned} \end{equation*} The ...

0

This is my experience (I am heading the Risk Analytics team for an investment bank in the City): We only ever bought the Optimization and Statistics toolboxes. You are better off writing any extra functionality yourself. Most of the stuff is simple, and writing it yourself improves your understanding and highlights potential pitfalls. Having said that, we ...

2

These are identical definitions of ES. It's just a matter of expressing losses as negatives or positives. First definition Notice the integral bounds are $a$ and $1$: losses are positive; this is so-called Loss(+)/Profit(-). Here alpha might be 95%, as in 95% confidence VaR or ES. Second definition Losses are negative, and the corresponding quantile is ...

1

Conversion to a butterfly can mitigate or even eliminate all risk taken by opening a initial debit spread or long option position. This is possible only if the underlying moved in your favor after your initial position is open. To convert to a butterfly you simply sell and buy enough options (for a credit) that together with your initial position forms a ...

Top 50 recent answers are included


text:
Question

What is valency? Give the valencies of the following: oxygen, hydrogen, sodium, magnesium, chlorine.

Open in App
Solution

Valency is the capacity of an atom to combine with the other atoms to form compounds. The valencies of the following atoms are: Oxygen (O) : 2 Hydrogen (H) : 1 Sodium (Na) : 1 Magnesium (Mg) : 2 Chlorine (Cl) : 1

Suggest Corrections
1
Related Videos
Mono Atomic Ions
CHEMISTRY
Watch in App
Explore more


text:
AT&T

Address 1072 S 2nd St, Coos Bay, OR 97420 (541) 269-2337 http://www.teletron.ca

# mean square of error Coquille, Oregon

Have a nice day! There are, however, some scenarios where mean squared error can serve as a good approximation to a loss function occurring naturally in an application.[6] Like variance, mean squared error has the Am I missing something? One can compare the RMSE to observed variation in measurements of a typical point.

Check out the grade-increasing book that's recommended reading at Oxford University! How would you do that? This is a subtlety, but for many experiments, n is large aso that the difference is negligible. Examples Mean Suppose we have a random sample of size n from a population, X 1 , … , X n {\displaystyle X_{1},\dots ,X_{n}} .

The mean squared error can then be decomposed as                   The mean squared error thus comprises the variance of the estimator and the Contents 1 Definition and basic properties 1.1 Predictor 1.2 Estimator 1.2.1 Proof of variance and bias relationship 2 Regression 3 Examples 3.1 Mean 3.2 Variance 3.3 Gaussian distribution 4 Interpretation 5 Further, while the corrected sample variance is the best unbiased estimator (minimum mean square error among unbiased estimators) of variance for Gaussian distributions, if the distribution is not Gaussian then even Pearson's Correlation Coefficient Privacy policy.

This definition for a known, computed quantity differs from the above definition for the computed MSE of a predictor in that a different denominator is used. Estimators with the smallest total variation may produce biased estimates: S n + 1 2 {\displaystyle S_{n+1}^{2}} typically underestimates σ2 by 2 n σ 2 {\displaystyle {\frac {2}{n}}\sigma ^{2}} Interpretation An I used this online calculator and got the regression line y= 9.2 + 0.8x. There are, however, some scenarios where mean squared error can serve as a good approximation to a loss function occurring naturally in an application.[6] Like variance, mean squared error has the

By choosing an estimator that has minimum variance, you also choose an estimator that has minimum mean squared error among all unbiased estimators. RMSD is a good measure of accuracy, but only to compare forecasting errors of different models for a particular variable and not between variables, as it is scale-dependent.[1] Contents 1 Formula A unimodal distribution that is skewed left. However, one can use other estimators for σ 2 {\displaystyle \sigma ^{2}} which are proportional to S n − 1 2 {\displaystyle S_{n-1}^{2}} , and an appropriate choice can always give

Key point: The RMSE is thus the distance, on average, of a data point from the fitted line, measured along a vertical line. See also Root mean square Average absolute deviation Mean signed deviation Mean squared deviation Squared deviations Errors and residuals in statistics References ^ Hyndman, Rob J. For example, in a linear regression model where is a new observation and is the regression estimator       with variance , the mean squared prediction error for is   Step 2: Find the new Y' values: 9.2 + 0.8(43) = 43.6 9.2 + 0.8(44) = 44.4 9.2 + 0.8(45) = 45.2 9.2 + 0.8(46) = 46 9.2 + 0.8(47) =

For example: 2 and 4 are only 4-2=2 apart. Exercises 2 and 3 show that the mean is the natural measure of center precisely when variance and standard deviation are used as the measures of spread. The root-mean-square deviation (RMSD) or root-mean-square error (RMSE) is a frequently used measure of the differences between values (sample and population values) predicted by a model or an estimator and the Though there is no consistent means of normalization in the literature, common choices are the mean or the range (defined as the maximum value minus the minimum value) of the measured

Thus, this vertical line in the MSE graph gives essentially the same information as the horizontal bar in the histogram. The goal of experimental design is to construct experiments in such a way that when the observations are analyzed, the MSE is close to zero relative to the magnitude of at Then you add up all those values for all data points, and divide by the number of points minus two.** The squaring is done so negative values do not cancel positive In this context, suppose that we measure the quality of t, as a measure of the center of the distribution, in terms of the mean square error MSE(t) is a weighted

This also is a known, computed quantity, and it varies by sample and by out-of-sample test space. Find My Dealer Prices shown are valid only for International. It would do two things: 1. The smaller the means squared error, the closer you are to finding the line of best fit.

Values of MSE may be used for comparative purposes. The MSE can be written as the sum of the variance of the estimator and the squared bias of the estimator, providing a useful way to calculate the MSE and implying If the statistic and the target have the same expectation, , then       In many instances the target is a new observation that was not part of the analysis. It is not to be confused with Mean squared displacement.

H., Principles and Procedures of Statistics with Special Reference to the Biological Sciences., McGraw Hill, 1960, page 288. ^ Mood, A.; Graybill, F.; Boes, D. (1974). For a Gaussian distribution this is the best unbiased estimator (that is, it has the lowest MSE among all unbiased estimators), but not, say, for a uniform distribution. However, as you can see from the previous expression, bias is also an "average" property; it is defined as an expectation. The fourth central moment is an upper bound for the square of variance, so that the least value for their ratio is one, therefore, the least value for the excess kurtosis


text:
# evaluate-overlap¶

## Synopsis¶

evaluate-overlap <target> [<source>...] [options]

## Description¶

Computes the overlap of either two intensity images (average SI) or two segmentations (see evaluate-overlap -label). If more than one source image is given, the overlap between each of these and the target is evaluated.

## Arguments¶

target

Target image/segmentation.

source

Transformed source image/segmentation.

## Command options¶

-images <file>

Text file with source image file paths.

-images-delim, -images-delimiter <c>

Delimiter used in -images file. (default: ‘,’ for .csv, ‘t’ for .tsv, and ‘ ‘ otherwise)

-Rx1 <int>

Region of interest lower index threshold in x dimension.

-Ry1 <int>

Region of interest lower index threshold in y dimension.

-Rz1 <int>

Region of interest lower index threshold in z dimension.

-Rx2 <int>

Region of interest upper index threshold in x dimension.

-Ry2 <int>

Region of interest upper index threshold in y dimension.

-Rz2 <int>

Region of interest upper index threshold in z dimension.

-Tp <value>

-label, -segment <value|lower..upper>...

Segmentation labels. When more than one specified, the segments are merged. This option can be given multiple times to evaluate the overlap of more than one (merged) segment at once. Use ‘-label 0’ to evaluate overlap of all labels merged into one segment (i.e., union of all labels). (default: none)

-labels

All (positive) segmentation labels individually. Can be combined with -label.

-probs [<threshold>]

Evaluate overlap of class probability maps (fuzzy membership functions). The values of the input images are rescaled to [0, 1]. When no <threshold> is specified, a value of 0.5 is used to binarize the fuzzy segmentation masks. When no <threshold> is specified and the metric is either Dice (DSC) or Jaccard (JSC), these metrics are evaluated using their respective definition based on scalar products.

-precision <int>

Number of significant digits. (default: 2)

-metric <name>

Segmentation overlap metric (see https://en.wikipedia.org/wiki/Confusion_matrix). (default: Dice / F1-score)

-delimiter, -delim <char>

Delimiter for output of multiple overlap values. (default: ,)

-table [<file>|stdout|cout]

Write table with overlap measures for all segments in a row, one row per input source image which is compared to the target segmentation. By default, the output to STDIN with verbosity 0 is the transpose table and excludes a table header. (default: off)

-header, -noheader

Whether to output a header row when -table is used. (default: on)

-id [<name>]

Print ID column with given <name> when -table is used and multiple source images are given. When only one image is given, the table is normally transposed with the label value in the first column. With this option, the table is always such that each row corresponds to one input source image, also when only one is given. (default: off)

-noid

Do not print ID column when -table is used.

-id-path, -noid-path

Use full input source image file path as ID column entry. (default: off)

## Standard options¶

-v, -verbose [n]

Increase/Set verbosity of output messages. (default: 0)

-debug [level]

Increase/Set debug level for output of intermediate results. (default: 0)

-version [major.minor]

Print version and exit or set version to emulate.

-revision

Print revision (or version) number only and exit.

-h, -help

Print help and exit.

## Terminal options¶

-color, -nocolor

Enable/disable colored output. (default: off)

## Parallelization options¶

-threads <n>

Use maximal <n> threads for parallel execution. (default: automatic)


text:
### Solving Euler’s equations

We are going to solve now Euler’s equations. In order to solve them in an intelligent way we need some preparation.

In “Angular momentum” we have derived Euler’s equations that govern rotations of a free rigid body about its center of mass:

(Euler)

Here are the components of the angular velocity vector in the body frame, while are the three principal moments of inertia.

Euler’s equations follow from conservation of the angular momentum vector with respect to space, as seen from the inertial laboratory frame. This is how we derived them in the previous post. The angular momentum vector in the laboratory frame is where has components Although we do not know (it needs to be found through solving differential equations), we know that it is an orthogonal matrix. And orthogonal matrix preserves the length of the vector. Since the components of the vector are constants, also its length is a constant. But the length of is the same as the length of and the length squared of is

(1)

There is also another important constant of motion – kinetic energy. We denote by the doubled kinetic energy:

(2)

To see that indeed is a constant of motion, we differentiate with respect to :

Now, we use the Euler’s equations and, surprise-surprise, everything on the right hand side cancels out:

(3)

Thus we get

So, we have identified two important constants of motion. Whenever a rigid body rotates, it will change its orientation in space, its rotation axis may change its direction, but the absolute value of the angular momentum given by Eq. (1) is constant in time. Kinetic energy is also constant in time. Yet these two constants are not completely independent. There are restrictions on the possible values of if is given. To see this let us order so that

(4)

We then have:

For the same reason we have

Let us introduce the constant defined by

(5)

Then we have

(6)

We can now move to solving the Euler’s equations (Euler) – at the top. To this end we compare them with the properties of the derivatives of Jacobi elliptic functions that we have derived in “Derivatives of Jacobi elliptic am, sn, cn, dn“:

(7)

According to our convention (4) on the right hand side of Euler’s equation we have signs . Our guess is that is proportional to We do not know whether to assume proportional to or to ? Let us try proportional and proportional to . So, here is our “Ansatz”:

(8)

Question is: can we find such that the Euler’s equation are satisfied automatically, given and ?

The answer has been found long ago. We can see a solution in the 1894 book by Alfred Cardew Dixon, “The elementary properties of the elliptic functions” . But we want to do it in a modern way. Here, for instance, is REDUCE code that provides us with a solution:

%We derive a solution of Euler’s equations
o1(t):=A1*cn(B*t);
o2(t):=A2*sn(B*t);
o3(t):=A3*dn(B*t);
%To solve Euler’s equation we must have e1=e2=e3=0 where
e1:=(I1*DF(o1(t),t)-(I2-I3)*o2(t)*o3(t))/(dn(b*t)*sn(b*t));
e2:=(I2*DF(o2(t),t)-(I3-I1)*o3(t)*o1(t))/(cn(b*t)*dn(b*t));
e3:=(I3*DF(o3(t),t)-(I1-I2)*o1(t)*o2(t))/(sn(b*t)*cn(b*t));
% Here are properties of sn, cn, dn
For all v let DF(sn(v),v)=cn(v)*dn(v);
For all v let DF(cn(v),v)=-sn(v)*dn(v);
For all v let DF(dn(v),v)=-m*sn(v)*cn(v);
For all v let cn(v)**2=1-sn(v)**2;
For all v let dn(v)**2=1-m*sn(v)**2;
% en2 is twice kinetic energy:
en2:=I1*o1(t)^2+I2*o2(t)^2+I3*o3(t)^2;
% ll2 is square of angular momentum:
ll2:=I1^2*o1(t)^2+I2^2*o2(t)^2+I3^2*o3(t)^2;
OFF NAT;
OUT “H:\Reduce MyFiles\eu1.txt”;
e1;
e2;
e3;
% we use the three Euler’s equations in order to express A1,A2,A3 in terms of i1,i2,i3,b,m
xx:=solve({e1=0,e2=0,e3=0},{A1,A2,A3});
% We get four solutions, with different signs, we choose one with all signs plus:
PART(xx,3);
a1:= part(part(part(xx,3),1),2);
a2:= part(part(part(xx,3),2),2);
a3:= part(part(part(xx,3),3),2);
en2;
ll2;
% now we call angular momentum squared l^2 and we introduce d=en2/ll2.
% we then find m,b expressed through l and d
% again there are two solutions, with different signs. We choose both plus signs:
xxx:=solve({ll2=l^2,en2=l^2*d},{b,m});
b:=part(part(part(xxx,1),1),2);
m:=part(part(part(xxx,1),2),2);
% now we find final expressions for a1,a2,a3
a1:=a1;
a2:=a2;
a3:=a3;
SHUT “H:\Reduce MyFiles\eu1.txt”;
END;

The results spilled out by REDUCE are not yet nicely arranged. After the arrangement, taking into account our conventions, the answer takes the following form:

(9)

Now I should verify that it is indeed a solution. I was trying to do it using REDUCE, but I did not succeed. So, I will return to this problem in my next post (and I will also try to fix typos in this post). Hopefully I will be able to find a way of verifying for sure the above statements.

##### Update: The following REDUCE code verifies the solution on random data. On output it spits out three zeros.:
a1:=l*sqrt((d*i3-1)/(i1*(i3-i1)));
a2:=l*sqrt((d*i3-1)/(I2*(i3-i2)));
a3:=l*sqrt((1-d*i1)/(i3*(i3-i1)));
b:=l*sqrt((1-d*i1)*(I3-i2)/(i1*i2*i3));
m:=(d*i3-1)*(i2-i1)/((1-d*i1)*(i3-i2));
o1(t):=A1*cn(B*t);
o2(t):=A2*sn(B*t);
o3(t):=A3*dn(B*t);
For all v let DF(sn(v),v)=cn(v)*dn(v);
For all v let DF(cn(v),v)=-sn(v)*dn(v);
For all v let DF(dn(v),v)=-m*sn(v)*cn(v);
For all v let cn(v)**2=1-sn(v)**2;
For all v let dn(v)**2=1-m*sn(v)**2;
e1:=(I1*DF(o1(t),t)-(I2-I3)*o2(t)*o3(t))/(dn(b*t)*sn(b*t));
e2:=(I2*DF(o2(t),t)-(I3-I1)*o3(t)*o1(t))/(cn(b*t)*dn(b*t));
e3:=(I3*DF(o3(t),t)-(I1-I2)*o1(t)*o2(t))/(sn(b*t)*cn(b*t));
for all a,b let sqrt(a)*sqrt(b)=sqrt(a*b);
off rounded;
i1:=random(1000)/1000;
i2:=1.0+random(1000)/1000;
i3:=2.0+random(1000)/1000;
l:=random(10)/2;
d:=1/i3+(1/i1-1/i3)/2;

OFF NAT;
OUT “H:\Reduce MyFiles\eu3.txt”;
e1:=e1;
e2:=e2;
e3:=e3;
SHUT “H:\Reduce MyFiles\eu3.txt”;
END;

##### Update 2:

Both REDUCE and Mathematica are able to do the task in a symbolic mode, but not without human help. These programs have very smart simplification algorithms, but sometimes our eye see that two expressions are the same, though they have different forms, while the programs do not want to see it. Then we need to help the program. For instance with Mathematica, it did not want to see that a particular expression is zero, but it recognized that its square is zero! Like here:

Here is the Mathematica notebook verifying Euler’s equations.
So, I consider that the job is done, and that we do have a solution of Euler’s equations.


text:
# why first line is missing using fancybox BVerbatim?

Why is defining a new name for environment for a command produces different result than when using the environment directly without defining a name for it?

Here are 2 examples, one uses a name for the env. and one does it. The second one is missing the first line in the verbatim text. Same text is used in both examples.

Code is below:

\documentclass{article}
\usepackage{fancybox}

\newenvironment{myStuff}%
{\VerbatimEnvironment\begin{Sbox}\begin{BVerbatim}}%
{
\end{BVerbatim}\end{Sbox}\fbox{\TheSbox}
}
\begin{document}
\begin{myStuff}
line 1
line 2
line 3
\end{myStuff}
\end{document}

second example

\documentclass{article}
\usepackage{fancybox}

\begin{document}

\begin{Sbox}\begin{BVerbatim}%
line 1
line 2
line 3
\end{BVerbatim}
\end{Sbox}\fbox{\TheSbox}
\end{document}

Texlive 2014

-

Your problem is that % after \begin{BVerbatim} in the second example. In the first example, the line \begin{myStuff} has a normal line ending (no %, so an end-of-line is seen), whereas as you've written it in the second example the % means that \begin{BVerbatim} 'runs on' into the line 1 line. I've not traced it through but I strongly suspect that \begin{BVerbatim} ignores the rest of the content of the 'current' line at the start of the environment. As a result, the % means that line 1 is ignored in the second case. Simply removing it solves the problem

\documentclass{article}
\usepackage{fancybox}

\begin{document}

\begin{Sbox}\begin{BVerbatim}
line 1
line 2
line 3
\end{BVerbatim}
\end{Sbox}\fbox{\TheSbox}
\end{document}

-

Here is a solution with package fancyvrb:

\documentclass{article}
\usepackage{fancyvrb}
\newenvironment{myStuff}
{\VerbatimEnvironment
\begin{SaveVerbatim}{VerbEnv}}
{\end{SaveVerbatim}\fbox{\BUseVerbatim{VerbEnv}}}

\begin{document}
\begin{myStuff}
line 1
line 2
line 3
\end{myStuff}
\end{document}

-
Thanks, but actually all the options being passed via [frame=single] and others like it, has no effect. Actually without [frame=single] it still works as is. Another thing I tried is \begin{SaveVerbatim}[frame=single,framerule=2pt]... and the line thickness did not change. I think all these options do not work for some reason like they do with normal \begin{Verbatim}[frame=single,framerule=2pt,samepage...] and I can't figure out why. I wish they did. –  Nasser Aug 27 '14 at 7:13
fyi, I have found another issue with this, which I am not able to resolve. May be you can. What happens is this: If the verbatim text is too long, the fbox does not overflow to the next page, but gets chopped off at the end of the page, and any remaining verbatim text is lost. i.e. if I just use \begin{Verbatim}{frame=single}... this problem do not happen, and the frame continue to next page, for as many pages as needed for large verbatim text. But not with the above. I'll post screen show below to show the difference. –  Nasser Aug 27 '14 at 10:34
screen shot !Mathematica graphics –  Nasser Aug 27 '14 at 10:39
for such listings you should use package listings. –  Herbert Aug 27 '14 at 10:42
Ok, will look at listing. But this all works fine with \begin{Verbatim}[frame=single]. I do not want to include text from files. The verbatim text is already inside the latex document. Only reason I was looking at fancybox here, is to make the box fit tight around the text, which \begin{Verbatim}[frame=single] does not do and has no option to do that. I assumed listing works only with reading text from files, but will check on it now. As long as I can get a frame that fits tight around the text, and does not get chopped at the end of the page, then I can use listing instead. Thanks. –  Nasser Aug 27 '14 at 10:53

Here is a solution with the package verbatimbox.

\documentclass{article}
\usepackage{verbatimbox}
\begin{document}
\begin{verbbox}
line1
line2
line3
\end{verbbox}
\fbox{\theverbbox}
\end{document}

-
thanks. But verbatimbox has the same issue I wrote about in my comment to Herbert above. For verbatim that is too long, the box gets chopped off and I lose verbatim text if the is longer than one page. This problem do not happen with \begin{Verbatim}[frame=single] –  Nasser Aug 27 '14 at 10:49
@Nasser I see. Thanks for the clarification. –  Steven B. Segletes Aug 27 '14 at 11:28


text:
# Building a Heap solved by 701

Feb. 21, 2014, 4:23 p.m. by Rosalind Team

Topics: Sorting

## Problem

A binary heap is a binary tree based data structure that is often used to implement priority queues. Binary heaps, in turn, can be easily implemented using an array if the underlying tree is a complete binary tree. The tree nodes have a natural ordering: row by row, starting at the root and moving left to right within each row. If there are $n$ nodes, this ordering specifies their positions $1, 2, \dots,n$ within the array. Moving up and down the tree is easily simulated on the array, using the fact that node number $j$ has parent $\lceil j/2 \rceil$ and children $2j$ and $2j + 1$.

The goal of this problem is to build a heap from the given array. For this, go from the end to the beginning of a given array and let each element "bubble up".

Given: A positive integer $n \le 10^5$ and array $A[1..n]$ of integers from $-10^5$ to $10^5$.

Return: A permuted array $A$ satisfying the binary max heap property: for any $2 \le i \le n$, $A[\lfloor i/2 \rfloor] \ge A[i]$.

## Sample Dataset

5
1 3 5 7 2

## Sample Output

7 5 1 3 2

## Running time

Since each "bubble up" operation requires only $O(\log n)$ time the running time of this algorithm is $O(n \log n)$. A more careful analysis shows that the running time is in fact just linear.


text:
# Questions for current (JC) Set 1

A storage battery, used for emergency lighting in the even of a power cut operates on 24V. The battery has negligible internal resistance and is rated at 140 ampere-hour.
(a) What is the total energy stored by the battery?
(b) What external resistance would have to be connected to the battery if it were to be discharged in 14 hours?
(c) What power output is the battery giving at this rate of discharge?

The resistivity of the human body is low as compared to the resitivity of the human skin (given as 3.0 X 104 Ω m for dry human skin). For a layer of dry human skin 0.5mm thick, and cross sectional area of 1.0 cm2, determine the resistance of the skin.

In a particular cathode ray oscilloscope, the measured current of the electron beam is 20.0 µA. How many electrons strike the oscilloscope screen every minute?

The unit of energy commonly used by electrical companies is the kilowatt-hour(kWh).

(a) How many joules are there in a kWh?
(b) A television set rated at 80W is operated from 8pm to midnight. How much energy is this in kWh and in MJ?

A cell of e.m.f. 9.00V and internal resistance of 0.50Ω is connected to a 8.50Ω resistor.
(a) Explain what is meant by an e.m.f. of 9.00V?

Calculate
(b) i) the current in the circuit,
ii) the p.d across the 8.50Ω resistor,
iii) the output efficiency of the circuit

Back To Current Of Electricity

##### Mini Physics

• The battery is rated at 140 ampere-hour. It means that it will provide 140 amperes in one hour. In this case, the battery is discharged over a 14 hours period. Hence, the current will be given by $\frac{140}{14}$.


text:
# 大数学家会解 IMO /高考 / Concours吗 ？

19 CE Evariste Galois 是 ”抽象代数” 群论之父 (Abstract Algebra – Group Theory), 大学入学考试 (Concours = 法国科举) 连续2年不及格 – 因为他准备不充足，不适应考题的技巧。

(想看更多合你口味的内容，马上下载 今日头条)

# Quora: IMO 1988 Question 3

Problem A3

A function f is defined on the positive integers by:

for all positive integers n,

$f(1) = 1$
$f(3) = 3$
$f(2n) = f(n)$
$f(4n + 1) = 2f(2n + 1) - f(n)$
$f(4n + 3) = 3f(2n + 1) - 2f(n)$

Determine the number of positive integers n less than or equal to 1988 for which f(n) = n.

What is the explanation of the solution of problem 3 from IMO 1988? by Alon Amit

# The Legend of Question Six (IMO 1988)

This question was submitted  by West Germany to the IMO Committee, the examiners could not solve it in 6 hours.

In the IMO (1988) only 11 contestants solved it,  one of them proved it elegantly. Terence Tao (13, Australia) only got 1 mark out of 7 in this question.

Solution

[INMO 1993]

# Prof ST Yau’s 丘成桐 Talk to Chinese Youth on Math Education

Prof ST Yau 丘成桐 , Chinese/HK Harvard Math Dean, is the only 2 Mathematicians in history (the other person is Prof Pierre Deligne of Belgium) who won ALL 3 top math prizes: Fields Medal 1982 (at 27, proving Calabi Conjecture), Crafoord Prize (1994) , Wolf Prize (2010).

Key Takeaways :

1. On Math Education
◇ Compulsary Math training for reasoning skill applicable in Economy, Law, Medicine, etc.
◇ Study Math Tip: read the new topic notes 1 day before the lecture, then after lecture do the problems to enhance understanding.
◇ Read Math topics even though you do not understand in first round, re-read few more times,  then few days / months / years / decades later you will digest them. (做学问的程序).
◇ Do not consult students in WHAT to teach, because they don’t know what to learn.
◇ Love of Math beauty is the “pull-factor” for motivating  students’ interest in Math.
◇ Parental Pressure.

2. “3D” facial photo using Math

3. Pi-Music: 1 = “do”, 2 = “re”, 3 =”me”…
Pi =3.1415926…

4. Math Olympiad: Prof ST Yau had criticised publicly it as a bad Math training, not the “real” Math.

An audience tested Prof ST Yau on a Math (Accounting) Puzzle which he couldn’t  solve on the spot. He said Mathematicians are poor in +-×÷ arithmetic.

5. Chinese students in USA: China sends over 200,000 students to USA universities. They are good in secondary / high school Math with known solutions,  but poor in graduate PhD Math which requires “out-of-the-box” independent thinking skill for finding unknown solutions. Recent few years Chinese students (eg. Stanford Prof 李骏 : 1989 Harvard PhD)  in USA have improved standard in PhD research.

6. Research is not for fame. It takes many years to think through an interesting topic.

Reference:

1. Prof ST Yau’s Best Seller Book 《The Shape of Inner Space》avail @ NLB (Ref #530.1) 11 copies in most NLB branches@ AMK, Bishan etc.

2. Interview Prof ST Yau by HK TV (Cantonese)

3. 丘成桐 (2008) 评中国 和 美 国的教育 : 中国学生不爱看课外书, 因为考试太重, 课余时间花在玩电脑游戏。

4.  丘成桐 (2016): 中国大学本科要注重基础教育, 才能培养世界级一流人才

# Smart Algebraic Technique

Calculate:
$(3+1). (3^2 +1). (3^4 + 1)(3^8 +1).... (3^{32} +1)$

Let
$x = (3+1). (3^2 +1). (3^4 + 1)(3^8 +1).... (3^{2n} +1)$

Or:
$\displaystyle x = \sum_{n=0}^{n}(3^{2n} + 1)$

Quite messy to expand out:

$\displaystyle { \sum_{n=0}^{n} (3^{2n}) + \sum_{n=0}^{n}(1) = .... }$

This 14-year-old vienamese student in Berlin – Huyen Nguyen Thi Minh discovered a smart trick using the identity:
$\displaystyle { (a -1).(a + 1) = a^{2} - 1}$
or more general,
$\displaystyle \boxed { (a^{n} -1).(a^{n} + 1) = a^{2n} - 1 }$

He multiplies x by (3-1):

$x. (3-1) = (3-1)(3+1). (3^{2} +1)... (3^{2n} + 1)$
$2x = (3^{2} -1). (3^{2} +1)...(3^{2n} + 1)$

$2x = (3^{4} -1).(3^{4} +1) ... (3^{2n} + 1)$
.
.
.

$2x = (3^{4n} -1)$

$\displaystyle \boxed { x = (3^{4n} -1) / 2 }$
When n = 16,
$\displaystyle { x = (3^{64} -1) / 2 }$

$x = 1,716,841,910,146,256,242,328,924,544,640$