tag:blogger.com,1999:blog-6122752894055659432024-02-07T06:07:22.028-08:00Many MoodsLike everybody, I have interests in so many activities. Although like Heisenberg's uncertainty principle I can't predict, what I am going to blog about, It should be most probably related with [Business news], [Tennis], [Java], [Ruby], [Technology].Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.comBlogger34125tag:blogger.com,1999:blog-612275289405565943.post-66028820967411216232009-10-13T13:03:00.000-07:002011-07-15T06:56:42.727-07:00How To : A Simple Generic SOAP Test Client written in JavaThere are lots of libraries which are available to consume/generate a web service, like <a href="http://static.springsource.org/spring-ws/sites/1.5/">Spring Webservices</a>, <a href="http://xfire.codehaus.org/">XFire</a>, <a href="http://ws.apache.org/axis/">Apache Axis</a>, to name a few.<br /><br />While each one has its own pro/cons (that we can leave for a separate blog entry), many a times, one needs a simple (1 or 2) methods of a webservice calls to make. She may or may not care about the response, as long as the response is not leading to error.<br /><br />For testing purposes, many use <a href="http://www.soapui.org/">soapui</a>, which is a wonderful tool. You may use it to point towards your soap end point, and it will generate request stub for you . Just fill in few params required by the method you are calling.<br /><br />Here, I am ind of demonstrating the same thing, using a simple java program. <br />I am not using any WSDL2JAVA tool kind of stuff, to generate the stubs. [Please note, these stubs help you with the xml to java bindings, so if you are planning to use many methods, or you have sufficient time and want to do it right way, please follow that way].<br /><br />Here is the code, you may use to call any end point. please note, it has some security headers just to show you. You may/may not need it.<br /><br /><br /><pre><br />package example;<br /><br />import org.apache.axis.client.Service;<br />import org.apache.axis.client.Call;<br />import org.apache.axis.message.SOAPEnvelope;<br /><br />import java.io.InputStream;<br />import java.io.ByteArrayInputStream;<br />import java.net.URL;<br /><br /><br />public class TestClient {<br /> public static String wsURL =<br /> "{YOUR_END_POINT}?WSDL";<br /><br /> public static String mySoapRequest =<br /> new StringBuilder().<br /> append("<soapenv:envelope soapenv="\"http://schemas.xmlsoap.org/soap/envelope/\"" mes="\"http://{URL}/9.01/messages\"" typ="\"{URL}/types\"">\n").<br /> append(" <soapenv:header>\n").<br /> #If your soap end point doesn't need security just remove these elements, or if it implements other sceurity standards, replace here<br /> append(" <typ:requestheader>\n").<br /> append(" <wsse:security mustunderstand="\"1\"" wsse="\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd\"">\n").<br /> append(" <wsse:usernametoken>\n").<br /> append(" <wsse:username>testusername</wsse:username>\n").<br /> append(" <wsse:password type="\"http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordText\"">testpassword</wsse:password>\n").<br /> append(" </wsse:usernametoken>\n").<br /> append(" </wsse:security>\n").<br /> append(" </typ:requestheader>\n").<br /> append(" </soapenv:header>\n").<br /> append(" <soapenv:body>\n").<br /> #Here goes your request body<br /> .......................<br /> .......................<br /> append(" </soapenv:body>\n").<br /> append("</soapenv:envelope>").toString();<br /><br /> public static void test() throws Exception {<br /> InputStream input = new ByteArrayInputStream(mySoapRequest.getBytes());<br /> Service service = new Service();<br /> Call call = (Call) service.createCall();<br /> SOAPEnvelope soapEnvelope = new SOAPEnvelope(input);<br /> call.setTargetEndpointAddress(new URL(wsURL));<br /> call.setUseSOAPAction(true);<br /> System.out.println("Request:\n"+ mySoapRequest);<br /> soapEnvelope = call.invoke(soapEnvelope);<br /> System.out.println("Response:\n" + soapEnvelope.toString());<br /> }<br /><br /> public static void main(String args[]) throws Exception {<br /> TestClient callClient = new TestClient();<br /> callClient.test();<br /> }<br />}<br /></pre>Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com3tag:blogger.com,1999:blog-612275289405565943.post-73131576591207679972010-01-03T16:38:00.000-08:002010-01-03T16:50:01.627-08:00Solving Project Euler Problem #16 in Clojure<span style="font-weight:bold;">Problem Statement</span> : <br /><br />2^15 = 32768 and the sum of its digits is 3 + 2 + 7 + 6 + 8 = 26.<br /><br />What is the sum of the digits of the number 2^1000?<br /><br /><br /><span style="font-weight:bold;">Solution :</span><br />The easiest way to multiply a number by 2 is to perform a left bit shift. <br />Get the number, convert it to string, put the indices in a map and apply a "+" function on it. <br /><br /><pre><br />(println (apply + (map #(Integer/parseInt (str %1)) (str (bit-shift-left 2 999)))))<br /></pre>Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com4tag:blogger.com,1999:blog-612275289405565943.post-63597000156899451622009-11-22T19:08:00.000-08:002009-11-22T19:10:18.172-08:00Solving Project Euler Problem #10 in RubyProblem Statement :-<br /><br />The sum of the primes below 10 is 2 + 3 + 5 + 7 = 17.<br /><br />Find the sum of all the primes below two million.<br /><br /><span style="font-weight:bold;">Solution</span> :-<br /><br /><pre><br /><br />require "mathn"<br />require "benchmark"<br />module Enumerable<br /> def lazy_select<br /> Enumerator.new do |yielder|<br /> each do |obj|<br /> yielder.yield(obj) if yield(obj)<br /> end<br /> end<br /> end<br />end<br /><br />p 5+((5..2000000).lazy_select {|v| (v%6 == 1 || v%6 ==5) && v.prime?}.take(2000000)).inject(0) {|s,v| s+=v}<br />#Benchmark.bm(12) { |b| b.report('Report:') {5+((5..2000000).lazy_select {|v| (v%6 == 1 || v%6 ==5) && v.prime?}.take(2000000)).inject(0) {|s,v| s+=v}} }<br /><br /></pre>Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com0tag:blogger.com,1999:blog-612275289405565943.post-52533329183014426222009-11-14T13:17:00.000-08:002009-11-14T16:52:06.376-08:00Solving Project Euler Problem #9 No code Required<span style="font-weight:bold;">Problem Statement</span> :-<br /><br />A Pythagorean triplet is a set of three natural numbers, a b c, for which,<br /><br />a^2 + b^2 = c^2<br />For example, 3^2 + 4^2 = 9 + 16 = 25 = 5^2.<br /><br />There exists exactly one Pythagorean triplet for which a + b + c = 1000.<br />Find the product abc.<br /><br /><span style="font-weight:bold;">Solution</span> :-<br />Lets have a look on the first Pythagorean triplet 3, 4 and 5.<br /><br />All their multiples, would also be a Pythagorean triplet (e.g. 6, 8 and 10 or 9, 12 and 15 , and so on..)<br /><br />Also, any odd number can be represented as x^2 - y^2<br />For e.g.<br />3 = 2^2 - 1^2<br />5 = 3^2 - 2^2<br />7 = 4^2 - 3^2<br /><br />Since, (x^2 - y^2)^2 + (2xy)^2 = (x^2 + y^2)^2, we can always generate a triplet for any odd number x^2 - y^2.<br /><br />So, using this any triplet is of the form :<br />k*(x^2-y^2), k*2xy and k*(x^2+y^2), where k is any number (1, 2, ...n).<br /><br />Well, now let us solve the current problem.<br /><br />a = k*(x^2-y^2)<br />b = k*2xy<br />c = k*(x^2+y^2)<br />Since a+b+c = 1000, and they are the sides of a triangle, <br /><br />a,b,c < 500<br />=> k*(x^2+y^2) < 500<br />=> x,y < 500^(1/2) < 23<br /><br />Now, given a+b+c = 1000<br />=> k(x^2-y^2+2xy+x^2+y^2) = 1000<br />=> 2kx(x+y) = 1000<br />=> k*x(x+y) = 500 (Factors of 500 is , 2,2,5,5,5)<br />=> k*x(x+y) = 20*(20+5) (This is the only value, which satisfies x,y < 23)<br />=> for k =1 , x = 20, y = 5<br /><br />So, a = 20^2 - 5^2 = 375<br />b = 2*20*5 = 200<br />c = 20^2 + 5 ^2 = 425<br /><br />So, the product is : 375*200*425 = 31875000Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com0tag:blogger.com,1999:blog-612275289405565943.post-79789679945157500752009-11-14T12:48:00.000-08:002009-11-14T13:16:54.952-08:00Solving Project Euler Problem #8 No code Required<span style="font-weight:bold;">Problem Statement</span> :-<br />Find the greatest product of five consecutive digits in the 1000-digit number.<br />73167176531330624919225119674426574742355349194934<br />96983520312774506326239578318016984801869478851843<br />85861560789112949495459501737958331952853208805511<br />12540698747158523863050715693290963295227443043557<br />66896648950445244523161731856403098711121722383113<br />62229893423380308135336276614282806444486645238749<br />30358907296290491560440772390713810515859307960866<br />70172427121883998797908792274921901699720888093776<br />65727333001053367881220235421809751254540594752243<br />52584907711670556013604839586446706324415722155397<br />53697817977846174064955149290862569321978468622482<br />83972241375657056057490261407972968652414535100474<br />82166370484403199890008895243450658541227588666881<br />16427171479924442928230863465674813919123162824586<br />17866458359124566529476545682848912883142607690042<br />24219022671055626321111109370544217506941658960408<br />07198403850962455444362981230987879927244284909188<br />84580156166097919133875499200524063689912560717606<br />05886116467109405077541002256983155200055935729725<br />71636269561882670428252483600823257530420752963450<br /><br /><br /><span style="font-weight:bold;">Solution</span> :<br /><br /><span style="font-weight:bold;">One way</span> to solve is :- <br />starting from the beginning 5 numbers (strating from the 1st), multiplying them, storing it in as max, continuing the process for the next 5 numbers(starting from the 2nd), replacing the max value if the current product is more than the max stored earlier and so on till we reach the last 5 elements.<br />We may minimize the number of iterations based on the fact that for every zero found we don't need to calculate the product.<br /><br /><br /><span style="font-weight:bold;">Lucky Solution</span> :- <br />I started looking for 99999 using "ctrl+F" (as I knew if I find this any where), this would be the max no matter what the other numbers are.<br />Since it was not there, I started looking for the combination of for 9's and one 8 (it was also not there) and so on, and eventually found 99879. Definitely, i was lucky to get the number in a minute or so (The data set for the problem was friendly, otherwise I would have probably coded it.<br /><br />You may use another fact to code your logic. If you know the sum of n numbers x1+x2+..xn, the maximum value of their product is when x1=x2=..=xn.<br /><br />For e.g. sum of 9,9,8,8,8 and 9,9,8,7,9 is equal, the product of 9,9,8,8,8 would be <br />larger (8+7+9 = 24 = 8+8+8).Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com0tag:blogger.com,1999:blog-612275289405565943.post-75458054739940363752009-11-01T13:31:00.000-08:002009-11-01T13:50:44.911-08:00Solving Project Euler Problem #7 in Ruby, Clojure<span style="font-weight:bold;">Problem Statement </span>:<br />By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13.<br /><br />What is the 10001st prime number?<br /><br /><span style="font-weight:bold;">Solution :</span><br /><br />This works on Ruby 1.9+. Here we have taken advantage of the method discusses <a href="http://www.michaelharrison.ws/weblog/?p=163">here</a> to create Lazy enumerator in Ruby. I started looking for the ruby equivalent as the clojure code becomes so easy to deal with using the lazy sequences.<br /><br /><pre><br />require "mathn"<br />infinity = 1.0/0.0<br />module Enumerable<br /> def lazy_select<br /> Enumerator.new do |yielder|<br /> each do |obj|<br /> yielder.yield(obj) if yield(obj)<br /> end<br /> end<br /> end<br />end<br /><br />p (1..infinity).lazy_select { |v| v.prime? }.take(10001).last<br /><br /></pre><br /><br />The clojure code is as follows :<br />Here we have added one optimization (<span style="font-weight:bold;">Any prime number after 2 and 3, when divided by 6, leaves the remainder 5 or 1</span>).<br /><br /><pre><br />(defn sqrt [x]<br /> (int (Math/sqrt x)))<br /><br />(defn get-smallest-prime-factor [n]<br /> (loop [n n d 2]<br /> (cond (> d (sqrt n)) n<br /> (= n d) n<br /> (= 0 (rem n d)) d<br /> true (recur n (inc d)))))<br /><br />(def get-nth-prime<br /> (lazy-cat '(2 3)<br /> (filter<br /> #(= % (get-smallest-prime-factor %))<br /> (filter<br /> #(or (= 1 (rem % 6)) (= 5 (rem % 6)))<br /> (take-nth 2 (iterate inc 3))))))<br /><br />(println (nth get-nth-prime 10000))<br /></pre><br /><br />Here is another cheat, if you have installed the <a href="http://github.com/richhickey/clojure-contrib">clojure contrib library</a>.<br /><br /><pre><br />(use 'clojure.contrib.lazy-seqs)<br />(println (nth primes 10000))<br /></pre>Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com1tag:blogger.com,1999:blog-612275289405565943.post-16336464461681124072009-11-01T13:28:00.000-08:002009-11-01T13:31:00.962-08:00Solving Project Euler Problem #6<span style="font-weight:bold;">Problem Statement</span> :<br />The sum of the squares of the first ten natural numbers is,<br />1**2 + 2**2 + ... + 10**2 = 385<br />The square of the sum of the first ten natural numbers is,(1 + 2 + ... + 10)**2 = 55*2 = 3025<br />Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum is 3025 385 = 2640.<br />Find the difference between the sum of the squares of the first one hundred natural numbers and the square of the sum.<br /><br /><span style="font-weight:bold;">Solution</span> is -> (n(n+1)/2)**2 - (n*(n+1)*(2n+1))/6<br /><br /><br /><pre><br />(defn euler6 [n] (- (* (/ (* n (+ n 1)) 2) (/ (* n (+ n 1)) 2)) (/ (* n (+ n 1) (+ 1 (* n 2))) 6)))<br />(println (euler6 100))<br /></pre>Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com0tag:blogger.com,1999:blog-612275289405565943.post-36130191338513433222009-10-25T06:56:00.000-07:002009-10-25T07:15:58.977-07:00Dual Pivot Quicksort in JavaThis is from the paper published by Vladimir Yaroslavskiy (Read it for more details : <a href="http://iaroslavski.narod.ru/quicksort/DualPivotQuicksort.pdf">here</a><br /><br /><span style="font-style:italic;">Sorting data is one of the most fundamental problems in Computer Science, especially if the arranging objects are primitive ones, such as integers, bytes, floats, etc. Since sorting methods play an important role in the operation of computers and other data processing systems, there has been an interest in seeking new algorithms better than the existing ones. We compare sorting methods by the number of the most "expensive" operations, which influence on effectiveness of the sorting techniques, — comparisons and swaps. Quicksort algorithm is an effective and wide-spread sorting procedure with C*n *ln(n) operations, where n is the size of the arranged array. The problem is to find an algorithm with the least coefficient C. There were many attempts to improve the classical variant of the Quicksort algorithm:<br /><br />1. Pick an element, called a pivot, from the array.<br />2. Reorder the array so that all elements, which are less than the pivot, come before the pivot and all elements greater than the pivot come after it (equal values can go<br />either way). After this partitioning, the pivot element is in its final position.<br />3. Recursively sort the sub-array of lesser elements and the sub-array of greater elements.<br /><br />We can show that using two pivot elements (or partitioning to three parts) is<br />more effective, especially on large arrays. We suggest the new Dual-Pivot Quicksort<br />scheme, faster than the known implementations, which improves this situation. The<br />implementation of the Dual-Pivot Quicksort algorithm has been investigated on different inputs and primitive data types. Its advantages in comparison with one of the most effective known implementations of the classical Quicksort algorithm [1], [2], and implementation of Quicksort in JDK™ 6.0 platform [3] have been shown.<br /><br />It is proved that for the Dual-Pivot Quicksort the average number of <br />comparisons is 2*n*ln(n), the average number of swaps is 0.8*n*ln(n), <br />whereas classical Quicksort algorithm has 2*n*ln(n) and 1*n*ln(n) <br />respectively.</span><br /><br /><br /><br />Here is the source code for the implementation : <a href="http://cr.openjdk.java.net/~alanb/6880672/webrev.03/src/share/classes/java/util/DualPivotQuicksort.java.html">Code</a> by Vladimir Yaroslavskiy, Jon Bentley and Josh Bloch.<br /><br /><br />Comparision between Current JDK Quicksort vs Dual Pivot Quick sort : <a href="http://spreadsheets.google.com/pub?key=tZD0Uq6ox1-BHhCoXDWIyUQ&output=html">comparision</a>Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com1tag:blogger.com,1999:blog-612275289405565943.post-87229321703118463562009-10-23T12:42:00.000-07:002009-10-23T12:47:04.008-07:00Solving Euler Project Problem #4 using Ruby<span style="font-weight:bold;">Problem Statement </span>: A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.<br /><br />Find the largest palindrome made from the product of two 3-digit numbers<br /><br /><span style="font-weight:bold;">Solution :</span> Please check the comments before the code which explains the logic/approach to the problem. We are trying to minimize the iterations to check against the generated palindromic number. Also this divisibility by holds true only for all the even numbered palindroms.<br /><br /><pre><br /><br />#<br />#A palindromic number reads the same both ways. The largest palindrome made from the product of two 2-digit numbers is 9009 = 91 99.<br />#<br />#Find the largest palindrome made from the product of two 3-digit numbers<br />#<br /># Observations :<br /># Number = xyzzyx = 100001*x + 100010*y + 1100*z (which is divisible by 11)<br />#<br />#<br /><br /><br /><br /><br />def largest_palindrome_for_even_digits(n)<br /> max_val = 0<br /> multiplier_x = get_multiplier_x(n)<br /> n.downto(100) { |y|<br /> multiplier_x.each { |x|<br /> product = x * y<br /> if product.to_s == product.to_s.reverse<br /> max_val = [max_val, product].max<br /> end<br /> }<br /> }<br /> max_val<br />end<br /><br /><br />def get_multiplier_x (n)<br /> multipliers = []<br /> current_val = n/11*11<br /> while current_val > 100<br /> multipliers << current_val<br /> current_val-=11<br /> end<br /> multipliers<br />end<br /><br />puts largest_palindrome_for_even_digits(999)<br /><br /></pre>Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com30tag:blogger.com,1999:blog-612275289405565943.post-51421542369140760162009-10-23T12:36:00.000-07:002009-10-23T12:42:37.727-07:00Solving Euler Project Problem #3 using Ruby<div><b>Problem Statement :</b> The prime factors of 13195 are 5, 7, 13 and 29.</div><div>What is the largest prime factor of the number 600851475143</div><div><br /></div><div><b>Solution : </b>Please check the code comments which explains the logic.</div><pre><br />#The prime factors of 13195 are 5, 7, 13 and 29.<br />#<br />#What is the largest prime factor of the number 600851475143<br />#<br />#Start dividing the number by the first prime (i.e. 2). Keep dividing by the current factor<br />#till the remainder is zero. So, the number left is n/(current_prime_factor)**m, where m is the no. of times<br />#current factor was able to divide the number without remainder. Repeat this process with the next<br />#prime factor and the number left as a result of previous division and so on, unless the result of<br />#division becomes 1. As the prime factor we are using to divide keeps on increasing, and the loop ends<br />#when the number is completely divided (or say n become 1), return the current prime factor. This is our<br />#largest prime factor<br /><br />require 'mathn'<br /><br />def find_largest_prime(n)<br /> primes = Prime.new<br /> while n > 1<br /> current_prime_factor = primes.next<br /> while n % current_prime_factor == 0<br /> n /= current_prime_factor<br /> end<br /> end<br /> current_prime_factor<br />end<br /><br />puts find_largest_prime(600851475143)<br /><br /></pre>Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com1tag:blogger.com,1999:blog-612275289405565943.post-51291377872994856052009-10-21T19:49:00.000-07:002009-10-21T20:52:37.225-07:00Google Guice : Part 2 : Inject Config Value<span style="font-weight:bold;">Was Spring 3.0 just released ?</span><br /><br />Right, Here is a link mentioning the same <a href="http://www.reuters.com/article/pressRelease/idUS92638+19-Oct-2009+BW20091019">Spring3.0 release</a>. I am really excited to check it out, specially the REST part of it. But yeah, let us save it for other posts.<br /><br /><span style="font-weight:bold;">I directly came here, where is the part One ?</span><br /><br />If you haven't gone through the <a href="http://anshu-manymoods.blogspot.com/2009/10/google-guice-part-1.html">part 1</a> of this article, and are totally new to Google Guice, please check it out and set up your environment as described there.<br /><br /><span style="font-weight:bold;">What is the goal for this article ?</span><br /><br />Since in the previous article we were able to set up a working project/program. Let us extend it further. Almost all of the applications needs to have some configuration properties, today we will learn to inject the property value from a config file.<br /><br /><span style="font-weight:bold;">Ummm.. before you dive into it, I just forgot what was the spring bean I used to configure it in a Spring App?</span><br /><br />I guess you are probably talking about PropertyPlaceholderConfigurer.java. By the way, the other day I <a href="http://anshu-manymoods.blogspot.com/2009/10/recipe-how-to-get-property-value-in.html">blogged</a> about extending it.<br /><br /><span style="font-weight:bold;">Well...Lets code it :</span><br /><br /><pre><br />public interface IPrinter {<br /> public void print();<br />}<br /><br />public class MyDummyPrinter implements IPrinter {<br /> public void print() {<br /> System.out.println("Article Printed !");<br /> }<br />}<br /><br />public interface IMailSender {<br /> public void sendMail();<br />}<br /><br />public class MyDummyMailSender implements IMailSender {<br /> public void sendMail() {<br /> System.out.println("Mail Sent !");<br /> }<br />}<br /><br />public interface ArticleService {<br /> public void publishArticle();<br />}<br /><br />import com.google.inject.Inject;<br />import com.google.inject.name.Named;<br />public class Article implements ArticleService {<br /> private IMailSender mailSender;<br /> private IPrinter printer;<br /><br /> private String advertizedAt;<br /> private String articleHeading;<br /><br /> @Inject<br /> Article(<br /> @Named("advertised.at") String advertizedAt,<br /> @Named("article.name") String articleHeading,<br /> IMailSender mailSender, IPrinter printer) {<br /> this.mailSender = mailSender;<br /> this.printer = printer;<br /> this.advertizedAt = advertizedAt;<br /> this.articleHeading = articleHeading;<br /> System.out.println("This article has been advertized at :" + advertizedAt +<br /> " with the heading :" + articleHeading);<br /> }<br /><br /> public void publishArticle() {<br /> mailSender.sendMail();<br /> printer.print();<br /> }<br />}<br /><br /></pre><br /><br />Check out the Article.java code. We want to inject two properties namely "advertizedAt" and "articleHeading" throgh a config file. As you can see Guice comes with a built in annotation - <span style="font-weight:bold;">named</span>. So, as it appears, Guice should inject the value for these keys as defined in the config file.<br /><br />Well, let us define our property file :<br /><br /><pre><br />advertised.at=dZone<br />article.name=googleGuicePartTwo<br /></pre><br /><br /><span style="font-weight:bold;">But How will Guice know the property value unless it loads it. Does it has something like PropertyPlaceholderConfigurer ?</span><br /><br />You are right, we are going to write some code to load the property file. As of now, I am not aware about any helper class who does it for us. If you know one please comment, or else I would update it once I know.<br /><br /><pre><br />import com.google.inject.AbstractModule;<br />import com.google.inject.name.Names;<br />import java.util.Properties;<br />import java.net.URL;<br /><br />public class MyArticleModule extends AbstractModule {<br /> @Override<br /> protected void configure() {<br /> try {<br /> Properties props = loadProperties();<br /> Names.bindProperties(binder(),props);<br /> } catch (Exception e) {<br /> e.printStackTrace();<br /> }<br /> bind(IPrinter.class).to(MyDummyPrinter.class);<br /> bind(IMailSender.class).to(MyDummyMailSender.class);<br /> }<br /><br /> private static Properties loadProperties() throws Exception {<br /> Properties properties = new Properties();<br /> ClassLoader loader = MyArticleModule.class.getClassLoader();<br /> URL url = loader.getResource("config.properties");<br /> properties.load(url.openStream());<br /> return properties;<br />}<br />}<br /></pre><br /><br />So, before injection we are loading the config.properties. The code is straight forward. The piece important here to note is the use of <span style="font-weight:bold;">com.google.inject.name.bindProperties</span> which creates a constant binding to @Named(key) for each property.<br /><br />Well , Let us see it in action :<br /><br /><pre><br />import com.google.inject.Injector;<br />import com.google.inject.Guice;<br /><br />public class MyBootStrapInvoker {<br /> public static void main(String[] args) {<br /> Injector injector = Guice.createInjector(new MyArticleModule());<br /> Article article = injector.getInstance(Article.class);<br /> article.publishArticle();<br /> }<br />}<br /></pre><br /><br /><span style="font-weight:bold;">Sample Run :</span>-<br /><br /><pre><br />This article has been advertized at :dZone with the heading :googleGuicePartTwo<br />Mail Sent !<br />Article Printed !<br /></pre><br /><br /><span style="font-weight:bold;">Is this the best approach to do this way </span>:<br /><br />I am sure there must be a better way, as Guice always discourages bindings that uses a string, because the compiler can not check the string. So that means, if there is some spelling mistakes, we would see run time error (like we see in spring, if you make spelling mistakes). Let me know, if you know a better way.<br />Would appreciate your comments.Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com3tag:blogger.com,1999:blog-612275289405565943.post-26927711853616637592009-10-21T13:53:00.000-07:002009-10-21T16:55:51.406-07:00Solving Euler Project Problem #2 using Ruby<span style="font-weight:bold;">Problem Statement </span>: Each new term in the Fibonacci sequence is generated by adding the previous two terms.<br />By starting with 1 and 2, the first 10 terms will be:<br />1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...<br /><br />Find the sum of all the even-valued terms in the sequence which do not exceed four million.<br /><br /><span style="font-weight:bold;">Solution :</span> For the explanation please see the comments. Later I realized that I could have probably used <a href="http://www.geocities.com/hjsmithh/Fibonacc/FibWhat.html">Binet's formula</a>, however this solution also kind of looks good.<br /><br /><br /><pre><br />#Each new term in the Fibonacci sequence is generated by adding the previous two terms.<br />#By starting with 1 and 2, the first 10 terms will be:<br />#<br />#1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...<br />#<br />#Find the sum of all the even-valued terms in the sequence which do not exceed four million.<br />#<br />#Obersevations : starting with 2 every 3rd number is even (it must be, as to make an even number<br />#one needs to add two odds (or two even unlikely here))<br />#So, lets try to decompose the fibonacci series in terms of n-3,n-6,n-9, etc...as it make us do<br />#less iteration while adding<br />#<br /># F(n) = F(n-1)+F(n-2) = F(n-2)+F(n-3)+F(n-2) = F(n-3)+2(F(n-2)) = F(n-3) + 2(F(n-3)+ F(n-4))<br /># = 3F(n-3) + 2F(n-4)<br /># = 3F(n-3) + F(n-4)+F(n-5)+F(n-6) = 4F(n-3) + F(n-6)<br />#<br />#<br /><br /><br />def find_sum_of_even_terms(limit)<br /> if(limit<2)<br /> return 0<br /> end<br /> if(limit<8) <br /> return 2<br /> end<br /> second_last_even_number = 2<br /> last_even_number = 8<br /> current_number = 4*last_even_number+second_last_even_number<br /> sum=second_last_even_number+last_even_number<br /><br /> while current_number<=limit<br /> sum+=current_number<br /> second_last_even_number = last_even_number<br /> last_even_number = current_number<br /> current_number = 4*last_even_number+second_last_even_number<br /> end<br /> sum<br />end<br /><br />puts find_sum_of_even_terms(4000000)<br /><br /></pre>Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com3tag:blogger.com,1999:blog-612275289405565943.post-66884800374875768962009-10-21T13:49:00.000-07:002009-10-21T13:57:50.256-07:00Solving Euler Project Problem #1 using Ruby<span style="font-weight:bold;">Problem statement</span> : If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23. Find the sum of all the multiples of 3 or 5 below 1000.<br /><br /><span style="font-weight:bold;">Solution </span>:<br /><br /><pre><br />#If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9.<br />#The sum of these multiples is 23.<br />#<br />#Find the sum of all the multiples of 3 or 5 below 1000.<br />#<br />#3(1+2+3+....+333)+5(1+2+3+.....+199)-15(1+2+3+...+66)<br />#puts 3*333*334/2+5*199*200/2-15*66*67/2<br />#<br /><br />def sum_of_n_consecutive_numbers (n)<br /> n*(n+1)/2<br />end<br /><br />def sum_of_multiples_of_m(max,m)<br /> m*sum_of_n_consecutive_numbers(max/m)<br />end<br /><br />puts sum_of_multiples_of_m(999,3)+sum_of_multiples_of_m(999,5)-sum_of_multiples_of_m(999,15)<br /><br /></pre>Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com0tag:blogger.com,1999:blog-612275289405565943.post-48607503216256674662009-10-19T21:15:00.000-07:002009-10-19T21:26:53.500-07:00Solving Project Euler Problem #5 in RubyThe problem statement :<br /><br /><span style="font-weight:bold;">2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest number that is evenly divisible by all of the numbers from 1 to 20?</span><br /><br /><span style="font-weight:bold;">Solution/s </span>:<br /><br />One of the solution is straight forward as Ruby exposes such a nice library (Actually it feels like a cheat :))<br /><br /><pre><br /> require 'rational'<br /> puts (1..20).inject(1) { |result, n| result.lcm n }<br /></pre><br /><br />The other solution involves a little bit of math/algorithm. Hopefully you will enjoy it.<br /><br /><pre><br />#<br /># Directly using the ruby library<br /># require 'rational'<br /># puts (1..20).inject(1) { |result, n| result.lcm n }<br />#<br /># The other solution (Code below) Steps :<br /># 1. Fetch all the primes less than "n" in an array (it would be automatically sorted, which will save our efforts later)<br /># 2. For the smallest member "k" of the prime list, find the maxm power "m" such that k**m <=n (For, e.g. 2**4<20)<br /># 3. Replace the smallest member from the array with k**m (For e.g. replace 2 with 16, because anything divisible by k**m<br /># would be itself be divisible by k**0..m-1)<br /># 4. Repeat the steps 2-3, for the next member of the array (starting with the power #m-1). when the power becomes 1, no need<br /># to iterate.<br /># 5. Multiply the members of the final array.<br />#<br /># Sample runs :<br /># For n = 10<br />#<br /># All the primes :<br /># [2, 3, 5, 7]<br /># All the multipliers :<br /># [8, 9, 5, 7]<br /># 2520<br />#<br /># For n = 20<br />#<br /># All the primes :<br /># [2, 3, 5, 7, 11, 13, 17, 19]<br /># All the multipliers :<br /># [16, 9, 5, 7, 11, 13, 17, 19]<br /># 232792560<br />#<br /><br />require 'mathn'<br /><br />def collect_primes(n)<br /> primes_list = []<br /> primes = Prime.new<br /> primes.each { |x| break if x >= n; primes_list<<x; }<br /> puts "All the primes :"<br /> p primes_list<br /> primes_list<br />end<br /><br />def root(arg, base)<br /> arg**(1/base)<br />end<br /><br />def get_all_the_multipliers(n)<br /> primes_list = collect_primes(n)<br /> max_base = get_max_base_for_two(n)<br /><br /> primes_list.each_with_index do |item, index|<br /> primes_list[index]=item**max_base<br /> max_base = get_max_base_for_current_number(n,max_base,primes_list[index+1])<br /> if max_base <=1 then break<br /> end<br /> end<br /> puts "All the multipliers :"<br /> p primes_list<br /> primes_list<br />end<br /><br />def get_mulitiplied_value(n)<br /> list_of_multipliers = get_all_the_multipliers(n)<br /> list_of_multipliers.inject(1){|total, i| total*i}<br />end<br /><br />def get_max_base_for_two(n)<br /> i=2<br /> while root(n,i) >= 2<br /> i = i+1;<br /> end<br /> return i-1<br />end<br /><br />def get_max_base_for_current_number(n,max_base, current_number)<br /> base = max_base - 1<br /> while current_number**base > n<br /> base = base - 1<br /> end<br /> return base<br />end<br /><br /><br />puts get_mulitiplied_value(20)<br />#puts get_mulitiplied_value(10)<br /><br /></pre><br /><br />Comments are welcome .Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com3tag:blogger.com,1999:blog-612275289405565943.post-5471861212916756912009-10-18T20:18:00.000-07:002009-10-18T21:16:52.871-07:00Google Guice : Part 1Over the weekend I was going through this video presented at Google IO 2009.<br />Please watch it if DI (a.k.a Dependency Injection) interests you.<br /><object width="425" height="344"><param name="movie" value="http://www.youtube.com/v/hBVJbzAagfs&hl=en&fs=1&"><param name="allowFullScreen" value="true"><param name="allowscriptaccess" value="always"><embed src="http://www.youtube.com/v/hBVJbzAagfs&hl=en&fs=1&" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="425" height="344"></embed></object><br /><br /><span style="font-weight:bold;">Where is Guice being used in production</span> :-<br />The video mentions Google uses it for <span style="font-weight:bold;">Google Wave</span>, <span style="font-weight:bold;">Google Adwords</span>, <span style="font-weight:bold;">GMail</span>, <span style="font-weight:bold;">Orkut</span>, <span style="font-weight:bold;">Google Docs</span>, <span style="font-weight:bold;">Youtube</span>...pretty much every new project .<br /><br />This is how I talked with myself, in case it is gonna help you let us learn together.<br /><br /><span style="font-weight:bold;">Should I care to learn Guice, I already know/use Spring</span> :- <br />Spring framework is much more than a DI framework.It made DI popular (although there were older DI framework available before it). Spring competes with JEE stack.<br />So, yeah we can say Spring is a super set of Google Guice. Guice wholly embraces annotations and generics, thereby enabling you to wire together and test objects with measurably less effort. Guice proves you can use annotations instead of error-prone, refactoring-adverse string identifiers.And of course it is much light weight.<br /><br /><span style="font-weight:bold;">Spring uses annotations too</span> :- That is true. The newer versions (probably 2+) focuses more to use annotations. We may discuss the benefits of XML declarations vs annotations in a separate post, as it is a topic in itself . <br /><br /><span style="font-weight:bold;">There are so many annotations for different DI libraries, shouldn't it be standardized </span>:- You are in luck. Check it out JSR330- http://code.google.com/p/atinject/<br /><br /><span style="font-weight:bold;">Well...so show me some code </span>:-<br /><br />I won't boar you with the definition(s) of DI, IOC (search it on google rather in case you are new to this). Goal of this post is to make you run a simple Guice Program.<br /><br /><a href="http://google-guice.googlecode.com/files/guice-2.0.zip">Download </a>the guice library, and add it in your classpath.<br /><br />The interfaces and it's implementations are self explanatory :-<br /><br /><pre><br /><br />public interface IPrinter {<br /> public void print();<br />}<br /><br />public class MyDummyPrinter implements IPrinter {<br /> public void print() {<br /> System.out.println("Article Printed !");<br /> }<br />}<br /><br />public interface IMailSender {<br /> public void sendMail();<br />}<br /><br />public class MyDummyMailSender implements IMailSender {<br /> public void sendMail() {<br /> System.out.println("Mail Sent !");<br /> }<br />}<br /><br />public interface ArticleService {<br /> public void publishArticle();<br />}<br /><br />import com.google.inject.Inject;<br />public class Article implements ArticleService{<br /> private IMailSender mailSender;<br /> private IPrinter printer;<br /><br /> @Inject<br /> Article (IMailSender mailSender, IPrinter printer) {<br /> this.mailSender = mailSender;<br /> this.printer = printer;<br /> }<br /> public void publishArticle() {<br /> mailSender.sendMail();<br /> printer.print();<br /> }<br />}<br /></pre><br /><br />As shown in the above program, we want the mailSender and printer to be injected.<br />So, note the @inject annotation over the Article Constructor.<br /><br />Lets inject the dependencies. Well, if you have worked with Spring's XML declarations for defining and injecting the dependencies, then think the next java code to be it's counter part in Guice.<br /><br /><pre><br />import com.google.inject.AbstractModule;<br />public class MyArticleModule extends AbstractModule {<br /> protected void configure() {<br /> bind(IPrinter.class).to(MyDummyPrinter.class);<br /> bind(IMailSender.class).to(MyDummyMailSender.class);<br /> }<br />}<br /></pre> <br /><br />What I like here is the readability (It is like I am coding in Ruby :)). The code clearly shows that IPrinter.class is bound to MyDummyPrinter.class. Similarly, with the other line.<br /><br />Cool..Now let us launch/bootstrap the Guice. For the Spring folks, think it similar to the code you write to load spring config beans (remember : ApplicationContext ctx = new ClasspathApplicationContext("example.xml")).<br /><br /><pre><br />import com.google.inject.Injector;<br />import com.google.inject.Guice;<br /><br />public class MyBootStrapInvoker {<br /> public static void main(String[] args) {<br /> Injector injector = Guice.createInjector(new MyArticleModule());<br /> Article article = injector.getInstance(Article.class);<br /> article.publishArticle();<br /> }<br />}<br /></pre> <br /><br />And that's it. You are running Guice !!!<br /><br />Hopefully, we will dive more in depth in the second post on the same topic.<br />Please let me know your comments, so the next time I could offer more.Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com1tag:blogger.com,1999:blog-612275289405565943.post-61108412270191400462009-10-18T16:20:00.000-07:002009-10-18T19:59:29.699-07:00Introducing JRugged library : Make your Java Programs Rock Solid<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhbR0_sjKTcyzY0_F8oBNASt2vn-gPYTtkNtwo912Be9MnX92RdeNwObLw9PRmtDnqQbSE5wKP9aVDyf8QOQIfOdofM_3Z4JsfXN7wGrdguH_laYxHMw-25r_bbTyV6Hm5mWAxe5uyXMiEC/s1600-h/Release+It.jpg"><img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 240px; height: 240px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhbR0_sjKTcyzY0_F8oBNASt2vn-gPYTtkNtwo912Be9MnX92RdeNwObLw9PRmtDnqQbSE5wKP9aVDyf8QOQIfOdofM_3Z4JsfXN7wGrdguH_laYxHMw-25r_bbTyV6Hm5mWAxe5uyXMiEC/s320/Release+It.jpg" border="0" alt=""id="BLOGGER_PHOTO_ID_5394085089577683090" /></a><br /><br /><br /> This <a href="http://www.amazon.com/Release-Production-Ready-Software-Pragmatic-Programmers/dp/0978739213/ref=sr_1_1?ie=UTF8&s=books&qid=1255908437&sr=8-1">book</a>, is definitely among one of the best books, I've read this year. It lays out some critical aspects to creating and rolling out stable software systems. Each of the case studies discussed is based on real events. <br /><br />While reading the book you will feel, how nice it would be if there is a library you could use to gain the advantages discussed to make your programs/software/systems rock solid.<br /><br />The <a href="http://code.google.com/p/jrugged">JRugged</a> is such a library written to be used in Java. To summarize, what it offers , here it is (directly from the project home page) :- <br /><br /><span style="font-style:italic;">The jrugged library provides straightforward add-ons to existing code to make it more robust and easier to manage.<br /><br />Although there are several lower-level building block classes here available for custom solutions, most clients will find they can use just the following classes:<br /><br /><span style="font-weight:bold;">CircuitBreaker</span> provides a way to wrap a service in a way that provides a bulkhead against system failure; when a remote service fails, further calls to the service are prevented for a period of time to allow the remote service to recover.<br /><br /><span style="font-weight:bold;">Initializer</span> provides a way to decouple service construction from initialization/startup and allows the latter to occur in the background, even retrying if initial attempts to initialize fail.<br /><br /><span style="font-weight:bold;">PerformanceMonitor</span> provides a way to wrap a service and collect a series of useful statistics about its latency and throughput, even calculating moving averages across different time windows.<br /><br /><span style="font-weight:bold;">Monitorable</span>, <span style="font-weight:bold;">Status</span>, and <span style="font-weight:bold;">RolledUpStatus</span> are related classes that provide a simple RED/YELLOW/GREEN encoding for service health, possibly useful for constructing operational dashboards.<br /><br />Generally speaking, most of these classes implement a ServiceWrapper interface to allow them to be applied around existing services using the Decorator design pattern. Those classes providing operational information, such as PerformanceMonitor and Monitorable can be wrapped in classes that expose their data to JMX controls or on web-accessible health status pages as desired.</span><br /><br /><br />Here I would show you, how easy it to use this in your existing code base. It provides it by the classic use of the Decorator Pattern.<br /><br /><pre><br /><br />import org.fishwife.jrugged.CircuitBreaker;<br />import org.fishwife.jrugged.PerformanceMonitor;<br />import org.fishwife.jrugged.Status;<br />import org.springframework.jmx.export.annotation.ManagedAttribute;<br /><br />public abstract class AbstractMonitor implements IMonitorable {<br /><br /> /** Circuit breaker to detect server oveloading */<br /> protected final CircuitBreaker cBreaker = new CircuitBreaker();<br /><br /> /** Performance stat monitor */<br /> protected final PerformanceMonitor perfMonitor = new PerformanceMonitor(5);<br /><br /><br /> @ManagedAttribute(description = "My System status")<br /> public String getHealthCheck() {<br /> return cBreaker.getStatus().getSignal();<br /> }<br /><br /><br /> @ManagedAttribute<br /> public double getAverageFailureLatencyLastDay() {<br /> return perfMonitor.getAverageFailureLatencyLastDay();<br /> }<br /><br /> @ManagedAttribute<br /> public double getAverageFailureLatencyLastHour() {<br /> return perfMonitor.getAverageFailureLatencyLastHour();<br /> }<br /><br /> @ManagedAttribute<br /> public double getAverageFailureLatencyLastMinute() {<br /> return perfMonitor.getAverageFailureLatencyLastMinute();<br /> }<br /><br /> @ManagedAttribute<br /> public double getAverageSuccessLatencyLastDay() {<br /> return perfMonitor.getAverageSuccessLatencyLastDay();<br /> }<br /><br /> @ManagedAttribute<br /> public double getAverageSuccessLatencyLastHour() {<br /> return perfMonitor.getAverageSuccessLatencyLastHour();<br /> }<br /><br /> @ManagedAttribute<br /> public double getAverageSuccessLatencyLastMinute() {<br /> return perfMonitor.getAverageSuccessLatencyLastMinute();<br /> }<br /><br /> @ManagedAttribute<br /> public long getFailureCount() {<br /> return perfMonitor.getFailureCount();<br /> }<br /><br /> @ManagedAttribute<br /> public double getFailureRateLastDay() {<br /> return perfMonitor.getFailureRateLastDay();<br /> }<br /><br /> @ManagedAttribute<br /> public double getFailureRateLastHour() {<br /> return perfMonitor.getFailureRateLastHour();<br /> }<br /><br /> @ManagedAttribute<br /> public double getFailureRateLastMinute() {<br /> return perfMonitor.getFailureRateLastMinute();<br /> }<br /><br /> @ManagedAttribute<br /> public double getFailureRateLifetime() {<br /> return perfMonitor.getFailureRateLifetime();<br /> }<br /><br /> @ManagedAttribute<br /> public long getRequestCount() {<br /> return perfMonitor.getRequestCount();<br /> }<br /><br /> @ManagedAttribute<br /> public double getRequestRateLastDay() {<br /> return perfMonitor.getRequestRateLastDay();<br /> }<br /><br /> @ManagedAttribute<br /> public double getRequestRateLastHour() {<br /> return perfMonitor.getRequestRateLastHour();<br /> }<br /><br /> @ManagedAttribute<br /> public double getRequestRateLastMinute() {<br /> return perfMonitor.getRequestRateLastMinute();<br /> }<br /><br /> @ManagedAttribute<br /> public double getRequestRateLifetime() {<br /> return perfMonitor.getRequestRateLifetime();<br /> }<br /><br /> @ManagedAttribute<br /> public long getSuccessCount() {<br /> return perfMonitor.getSuccessCount();<br /> }<br /><br /> @ManagedAttribute<br /> public double getSuccessRateLastDay() {<br /> return perfMonitor.getSuccessRateLastDay();<br /> }<br /><br /> @ManagedAttribute<br /> public double getSuccessRateLastHour() {<br /> return perfMonitor.getSuccessRateLastHour();<br /> }<br /><br /> @ManagedAttribute<br /> public double getSuccessRateLastMinute() {<br /> return perfMonitor.getSuccessRateLastMinute();<br /> }<br /><br /> @ManagedAttribute<br /> public double getSuccessRateLifetime() {<br /> return perfMonitor.getSuccessRateLifetime();<br /> }<br /><br /> public CircuitBreaker getCBreaker() {<br /> return cBreaker;<br /> }<br /><br /> public PerformanceMonitor getPerfMonitor() {<br /> return perfMonitor;<br /> }<br /><br /> public Status getStatus (){<br /> return cBreaker.getStatus();<br /> }<br />}<br /><br /></pre><br /><br />Now, your class just needs to extend this abstract class inherits all those JMX statistics as well as the handles to the Circuitbreaker and PerformanceMonitor Object.<br /><br /><pre><br />@ManagedResource(objectName = "com.example:type=manager,name=mysystem",<br /> description = "shows the running status of mysystem")<br />public class MySystem extends AbstractMonitor {<br /><br />.........<br />.........<br /> //This is the method I want to decorate<br /> public BackEndData processArgument(final String myArg) {<br /> final BackEndService theBackend = backend;<br /> try {<br /> return cBreaker.invoke(new Callable< BackEndData >() {<br /> public BackEndData call() throws Exception {<br /> return perfMonitor.invoke(new Callable< BackEndData >() {<br /> //This is the actual method which you were using earlier without decoration<br /> public BackEndData call() throws Exception {<br /> return theBackend.processArgument(myArg);<br /> }<br /> });<br /> }<br /> });<br /> } catch (RuntimeException re) {<br /> throw re;<br /> } catch (Exception e) {<br /> throw new RuntimeException("wrapped", e);<br /> }<br /> }<br /><br />}<br /><br /></pre><br /><br />You probably would change this code a little bit depending on the definitions of your critical components, and the health status (But you get the idea).<br /><br /><br />Now just fire up the JConsole and you can see all the statistics for your classes. And it handles failures as well, showing you the status of the system as Green/Red/Yellow (depending on your definition of the critical system/components).<br /><br />Please check it out for details, as the <a href="http://code.google.com/p/jrugged/source/browse/">code base</a> is pretty terse.<br /><br />You may wish to extend it to be used as an Aspect (AOP), so that your classes could avail the benefits without changing your java code. The project mentions, it is looking to offer AOP wrapper to make it easier to do drop-in decoration of existing code.<br />So wait if you could or if you implement it yourself, please post it so others could use it.Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com2tag:blogger.com,1999:blog-612275289405565943.post-32964595097724470672009-10-15T18:37:00.000-07:002009-10-16T15:44:25.189-07:00Intellij Idea IDE OpenSourced - The current state of the Java IDE'sIt is a great news that Jetbrains has opensourced the <a href="http://www.jetbrains.com/idea/nextversion/free_java_ide.html?promo">Intellij Idea</a>, a well known Java Editor. I have used it along with both Eclipse and Netbeans in the past.<br /><br />Last year, I decided to buy a professional license for the intellij and never looked back. So, what would I say about eclipse, Netbeans and Intellij ?<br /><br />Well, frankly speaking, they all have their positives. In fact, they are all competing on a very high level now.<br /><br />Lets compare them based on few criterias :<br /><br />1. <span style="font-weight:bold;">User Adoption</span> : Eclipse wins easily. However, I guess with today's announcement, it is going to be exciting. Don't forget Netbeans is releasing the 6.8 beta shortly, and it has significantlly improved.<br /><br />2. <span style="font-weight:bold;">Company Backing</span> : Although Eclipse was started by IBM, Jetbrains owns intellij and Netbeans is owned by Sun (ohh.. I guess it is Oracle), but now the open source has changed the game. It is all about users, developers, speed and plugins.<br /><br />3. <span style="font-weight:bold;">Speed </span> :- I don't have a benchmark, however the last time I felt, Eclipse and Intellij both were better. Netbeans still needs to work on it (I last tried the full j2ee version of it - 6.5, never tried 6.7).<br /><br />4. <span style="font-weight:bold;">Plugins </span> :- Again Eclipse wins by the numbers. As far as quality is concerned, Intellij would probably be the best. Again, used mostly the in-built plugins for the netbeans (Correct me, and add comments if you find it better). However, now I see all the three editors have got a nice plugin framework and lots of developers writing for them.<br /><br />5. <span style="font-weight:bold;">Maven Support</span> :- Hmm....Here the Netbeans is the one, closely followed by Intellij.<br /><br />6. <span style="font-weight:bold;">Usability</span> :- Power users like Intellij with the best Refactoring offering , intelligent shortcuts, the awesome customer care support.<br /><br />7.<span style="font-weight:bold;">Dynamic Language Support (Ruby/JRuby/Groovy)</span> :- NetBeans is the best IDE for Ruby/JRuby(I am not including Rubymine from Jetbrains, as it is a separate product). For Groovy, my vote goes to Intellij again. <br /><br />I think as now Intellij has provided the free editor (Community Edition), more people would give it a try, and hence would be in a better position to compare it (And who knows may be then buy the Professional Edition eventually).<br /><br />What do you think ?<br /><br />Update : Here is the <a href="http://www.jetbrains.com/idea/nextversion/editions_comparison_matrix.html">comparison chart</a> for the OpenSource version vs the Commercial One.Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com8tag:blogger.com,1999:blog-612275289405565943.post-72357700231681974782009-10-05T16:47:00.000-07:002009-10-14T07:51:16.300-07:00Recipe : How to get property value in a Spring ApplicationIf you work with Spring, I am sure you might have come across the scenario when you need to access the value of a property key in your application.<br /><br />The class "org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" is normally used to resolve the runtime key/value pairs. However, if you need to use a property value in your bean, it doesn't expose that to be read.<br /><br />Here is a very simple work-around :-<br /><br />1. Extend the <span style="font-weight:bold;">PropertyPlaceholderConfigurer</span> <br /><br /><pre><br />public class OpenPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer {<br /><br /> Properties mergedProperties;<br /><br /> public Properties getMergedProperties() throws IOException {<br /> if (mergedProperties == null) {<br /><br /> mergedProperties = mergeProperties();<br /><br /> }<br /> return mergedProperties;<br /><br /> }<br />}<br /></pre><br /><br /><br />2. Configure it to be used instead of PropertyPlaceholderConfigurer <br /><br /><pre> <br /> <bean id="propertyConfigurer" class="com.mypackage.OpenPropertyPlaceholderConfigurer"><br /> <property name="ignoreResourceNotFound" value="false"/><br /> <property name="locations"><br /> <list><br /> <value>classpath:common.properties</value><br /> <value>classpath:${YOUR_ENV}.properties</value><br /> </list><br /> </property><br /> </bean><br /></pre><br /><br />3. Inject this "propertyConfigurer" in your defined bean.<br /><br />4. Get the key value propertyConfigurer.getMergedProperties().getProperty("your.prop.key")<br /><br />I am sure, there could be some better ways. Let me know, if you know one.<br /><br />Credit goes to <a href="http://matschaffer.com/">Mat</a> for this recipe.Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com1tag:blogger.com,1999:blog-612275289405565943.post-37151060311145725592009-10-13T18:39:00.000-07:002009-10-13T18:50:54.562-07:00Simple Feed Aggregator in RubyRuby already has few RSS standard libraries (0.9, 1.0 , 2.0) in built, and it is good enough for simple purpose. <br /><br />Today, I am trying to work on a simple feed aggregator, which could take multiple feed source url's and enlists the stories published there. I was tempted to use the standard library, however since it would not support the <a href="http://en.wikipedia.org/wiki/Atom_(standard)">Atom</a> standard, started looking for another library which supports both.<br /><br /><a href="http://simple-rss.rubyforge.org/">SimpleRSS </a>lib by Lucas Carlson looks great.<br /><br />So, here goes the code. You may extend it if you wish.<br /><br /><pre><br />require 'simple-rss'<br />require 'open-uri'<br /><br />class FeedAggregator<br /> def initialize(urls)<br /> @urls = urls<br /> @feeds = []<br /> read_feeds<br /> end<br /><br /> def read_feeds<br /> @urls.each { |url| @feeds.push(SimpleRSS.new(open(url).read)) }<br /> end<br /><br /> def feed_source_counts<br /> @feeds.each_with_index do |feed, index|<br /> feed_source = "Feed Source [#{index}]: #{feed.channel.title}"<br /> published_articles = "Published Articles: #{feed.items.size}"<br /> puts feed_source + ', ' + published_articles<br /> end<br /> end<br /><br /> def list_articles(id)<br /> puts "-----Feed Source [#{id}] : #{@feeds[id].channel.title}-----"<br /> @feeds[id].items.each { |item| puts ' ' + item.title }<br /> end<br /><br /> def list_all_articles<br /> @feeds.each_with_index { |f, i| list_articles(i) }<br /> end<br />end<br /><br />MyFeedAggregator = FeedAggregator.new(ARGV)<br />MyFeedAggregator.feed_source_counts<br />puts "------------ Feed Details ------------------"<br />MyFeedAggregator.list_all_articles<br /></pre><br /><br /><br />Here is the test run :<br /><br /><pre><br />C:\Ruby\bin\ruby.exe -e STDOUT.sync=true;STDERR.sync=true;load($0=ARGV.shift) C:/Users/anshu/RubymineProjects/TestRubyProjectTwo/test_two.rb http://rubyforge.org/export/rss_sfnewreleases.php http://www.dzone.com/links/feed/frontpage/rss.xml<br />Feed Source [0]: RubyForge New Releases, Published Articles: 10<br />Feed Source [1]: dzone.com: latest front page, Published Articles: 25<br />------------ Feed Details ------------------<br />-----Feed Source [0] : RubyForge New Releases-----<br /> Dr Nic's Utilities<br /> WysMacs Trainable Text and Code Editor<br /> Loofah<br /> autotest-fsevent<br /> state_pattern<br /> codeforpeople<br /> Seattle.rb Projects<br /> rjack<br /> snk's open source<br /> Spidr<br />-----Feed Source [1] : dzone.com: latest front page-----<br /> Non-Technical Factors that Lead to Poor Architectures<br /> My Tools of the Trade – 2009<br /> Week Calendar using Jquery<br /> Oracle Taunts IBM with $10M Challenge<br /> Rant about developers or how I stopped worrying and love the simplicity<br /> ScalaTest 1.0 Release "A Path Forward" to Scala<br /> Resolving a Relative URL to a Full URL in ASP.NET<br /> JxBrowser 2.0 Early Access Program<br /> PrimeFaces UI 0.9.3 Released<br /> Mozilla Join Microsoft in Slamming Google Chrome Frame<br /> TDD is not test-first. TDD is specify-first and test-last.<br /> Five super-secret features in Windows 7<br /> Git# Offers Git Access for .NET and Mono Projects<br /> Getting Started with Scrum<br /> Apparent risk and actual risk<br /> 8 Hand Drawn Icon Sets For Bloggers<br /> Optimize your Mac experience with the LaunchBar multitasker<br /> 18 Really Beautiful and Creative Web Designs<br /> Google Released Page Speed for Firefox<br /> Objective-C's niche: why it survives in a world of alternatives<br /> Mobile Ajax Push for iPhone with JSF and PrimeFaces<br /> Book Review - Spring in Practice<br /> Tips for Designing an Awesome Coming Soon Page<br /> Abstracting away Dependencies for Simpler code<br /> MacRuby 0.5 Pulls the Plug on YARV<br /><br />Process finished with exit code 0<br /></pre>Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com3tag:blogger.com,1999:blog-612275289405565943.post-29812704433215732402009-10-12T16:40:00.000-07:002009-10-12T17:32:51.308-07:00XDepend : Java Code Base AnalysisToday morning, when I checked my email I was offered a Pro License for <a href="http://www.xdepend.com/">XDepend</a>. Thanks to them for letting me explore it. I would post my findings once my hands get a little bit dirty.<br /><br />The installer which I got was for a PC (I work on mac in my office), probably they have released a linux version as well. Would be nice, if they plan a release for the mac too.<br /><br />By now what I know about is, it is from the same people who have offered <a href="http://www.ndepend.com/">NDepend</a>, a well known code base analyzer in .Net environment.<br /><br />Here is a short and nice intro to it by <span style="font-weight:bold;">Mat Huston</span> :- <a href="http://www.coderanch.com/t/462565/Blatant-Advertising/New-Tool-Java-code-base#2065255">http://www.coderanch.com/t/462565/Blatant-Advertising/New-Tool-Java-code-base#2065255</a><br /><br />Give it a try, as the trial version is available on the XDepend.com.<br />Once I get chance to explore more, I would update this thread.Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com0tag:blogger.com,1999:blog-612275289405565943.post-83536260056728061302009-10-11T14:34:00.000-07:002009-10-11T15:42:21.502-07:00Writing Google Wave Robots using Java on Intellij<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKSzOw9m3Fbv3aJwhLcfX5MzDQUKE0n15RWV9EWQDO4BkbeQ7DTUHa8DFP3G_Ll4Pg8KjEoY9Q1huMwCvVpo_QMIg2cIH-E9D07XdYFsfmU_zSnwMNIE11tQdOFJjN5rMWPZD0yI7ScO9j/s1600-h/google_wave_robot3.jpg"><img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 320px; height: 200px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEjKSzOw9m3Fbv3aJwhLcfX5MzDQUKE0n15RWV9EWQDO4BkbeQ7DTUHa8DFP3G_Ll4Pg8KjEoY9Q1huMwCvVpo_QMIg2cIH-E9D07XdYFsfmU_zSnwMNIE11tQdOFJjN5rMWPZD0yI7ScO9j/s320/google_wave_robot3.jpg" border="0" alt="" id="BLOGGER_PHOTO_ID_5391472623647382914" /></a><br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdkkaRyuc9owwIasJTXD6XcuPlYrpHFsMHDkGn_5f3xUmRGVBgStvQA9Wj7qWhRfGrUX4OIi6Ylyo2q6WRrcR-JA9PHT8N3Fb2rR7w6jdNi4mJc7y_C_IhKpLeZfr7X5hG8tJiIB8GxmlQ/s1600-h/google_wave_robot2.jpg"><img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 320px; height: 193px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhdkkaRyuc9owwIasJTXD6XcuPlYrpHFsMHDkGn_5f3xUmRGVBgStvQA9Wj7qWhRfGrUX4OIi6Ylyo2q6WRrcR-JA9PHT8N3Fb2rR7w6jdNi4mJc7y_C_IhKpLeZfr7X5hG8tJiIB8GxmlQ/s320/google_wave_robot2.jpg" border="0" alt="" id="BLOGGER_PHOTO_ID_5391469280014808962" /></a><br /><a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDV6zT4vlOT1dSPKJWIdMiyOQ2ROHJVPz4fY7kNknKu1AY02uy_2HCL3I58BAXbpp1YddhGElBL6bhPDdJnYc-LBuZ3l0rF7qkX89WBLnZ9sutKDYI1AR1OEc7iillDbzbOMoQ-o3YQd0G/s1600-h/google_wave_robot.jpg"><img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 320px; height: 193px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhDV6zT4vlOT1dSPKJWIdMiyOQ2ROHJVPz4fY7kNknKu1AY02uy_2HCL3I58BAXbpp1YddhGElBL6bhPDdJnYc-LBuZ3l0rF7qkX89WBLnZ9sutKDYI1AR1OEc7iillDbzbOMoQ-o3YQd0G/s320/google_wave_robot.jpg" border="0" alt="" id="BLOGGER_PHOTO_ID_5391468458531460914" /></a><br />I got my <a href="http://wave.google.com/">google wave</a> invite two days back (friday night, can't be a better time). And within 4 hours I was talking with my "HelloWorldish" <a href="http://code.google.com/apis/wave/extensions/robots/">Robot</a>, such is the power and ease to write and deploy a robot is.<br /><br />If you use eclipse, you already are set and this is the best place to start with : http://code.google.com/apis/wave/extensions/robots/java-tutorial.html<br /><br />In fact, I used the same page for the sourcecode, and the steps. Make sure, you have a google wave id before you start looking at the next steps.<br /><br />Steps :-<br /><br />1.Make sure you are using Java 1.6.<br /><br />2. I am using <a href="http://www.jetbrains.net/confluence/display/IDEADEV/Maia+EAP">Intellij Maia (9)</a>. If you are on older version install the google appengine plugin.<br /><br />3. Use this plugin to generate a dummy web project. In the wizard, choose google app engine. We are not going to use either GWT/ JDO or JPA for this project, so just uncheck them.<br /><br />4. You can see a "AppEngine Dev" settings to run. Run it ,and you should be able to browse the dummy page at localhost:8080<br /><br />5. To write the Robot, we need few libraries. Download it from http://code.google.com/p/wave-robot-java-client/downloads/list.<br /><br />6.create a lib directory inside WEB-INF and copy all these jars . Also, add servlet-api-2.4.jar or higher.<br /><br />7.Make a package src/parroty.server and copy paste the ParrotyServlet code described at http://code.google.com/apis/wave/extensions/robots/java-tutorial.html<br /><br />8.Make a web/_wave dir. Create a capabilties.xml file and copy paste the code<br /><br /><pre><br /><?xml version="1.0" encoding="utf-8"?><br /><w:robot xmlns:w="http://wave.google.com/extensions/robots/1.0"><br /><w:capabilities><br /> <w:capability name="WAVELET_PARTICIPANTS_CHANGED" content="true" /><br /></w:capabilities><br /><w:version>1</w:version><br /></w:robot><br /></pre><br /><br />9. Register your application on appengine site.<br /><br />In you appengine-web.xml file substitute your application id (instead of mine, "mytestwaveapp") :-<br /><br /><pre><br /><?xml version="1.0" encoding="utf-8"?><br /><appengine-web-app xmlns="http://appengine.google.com/ns/1.0"><br /><application>mytestwaveapp</application><br /><version>1</version><br /></appengine-web-app><br /></pre><br /><br />10. Configure your ParrotyServlet inside the web.xml :<br /><pre><br /><?xml version="1.0" encoding="UTF-8"?><br /><web-app xmlns="http://java.sun.com/xml/ns/javaee"<br /> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"<br /> xsi:schemaLocation="http://java.sun.com/xml/ns/javaee<br /> http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"<br /> version="2.5"><br /> <servlet><br /> <servlet-name>Parroty</servlet-name><br /> <servlet-class>parroty.server.ParrotyServlet</servlet-class><br /> </servlet><br /> <servlet-mapping><br /> <servlet-name>Parroty</servlet-name><br /> <url-pattern>/_wave/robot/jsonrpc</url-pattern><br /> </servlet-mapping><br /></web-app><br /></pre><br /><br />Go to "Tools->Upload AppEngine Application", and you are good enough to deploy this Robot.It would ask you your appengine loginid/pwd.The console would show, that everything went fine. You can confirm by accessing the capabilties.xmlfile :- http://applicationName.appspot.com/_wave/capabilities.xml <br /><br />11.Well, now you are done. Use this robot as a participant for your wave and it should answer as I have shown in the picture. More Sample Robot Codes :- http://code.google.com/p/google-wave-resources/source/browse/trunk/samples/extensions/robots/java<br /><br />Happy Coding ! Happy Waving !!!Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com6tag:blogger.com,1999:blog-612275289405565943.post-8108263992411108432009-10-11T13:43:00.000-07:002009-10-11T14:15:32.428-07:00Easy Graph with Scruffy on Ruby<a onblur="try {parent.deselectBloggerImageGracefully();} catch(e) {}" href="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi965NgsPEOUaaq37DB3th6tPYapWE7TQ-AoU7QbAVmGQa_gfnvvrntnTrWKxyHrM7U5348XSwazX0g-5QhZXL-2L22q37u7JuRklInJdBej43YGE61b8m2yn0QdJ05thO6DItwt5cqWrld/s1600-h/split_test.png"><img style="float:left; margin:0 10px 10px 0;cursor:pointer; cursor:hand;width: 320px; height: 192px;" src="https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEi965NgsPEOUaaq37DB3th6tPYapWE7TQ-AoU7QbAVmGQa_gfnvvrntnTrWKxyHrM7U5348XSwazX0g-5QhZXL-2L22q37u7JuRklInJdBej43YGE61b8m2yn0QdJ05thO6DItwt5cqWrld/s320/split_test.png" border="0" alt=""id="BLOGGER_PHOTO_ID_5391453973516373746" /></a><br />This weekend, I was going through the first chapter of the book <a href="http://www.manning.com/mcanally/">Ruby in Practice</a>. Kind of like it as of yet , although have read only 4-5 pages. <br /><br />It shows an example of using the graphing library <a href="http://scruffy.rubyforge.org/">Scruffy</a>. Thought to give it a try on my home PC (Vitsa).<br /><br />This blog is to save your time, in case you want to use this nice library and run into configuration problem.<br /><br />1. You need to install the "Scruffy" gems<br />gem install scruffy<br /><br />2. Then I tried the example discussed at :- http://scruffy.rubyforge.org. However, was getting error, which made it clear, you need to install another gem - RMagick. Won't bother you with my trial and errors, so to cut long story short, RMagick in turn requires other graphing lib (for e.g., I opted for IMageMagick).<br /><br />So, download http://rubyforge.org/frs/download.php/38052/RMagick-2.5.0-ImageMagick-6.4.1-5-Q8.zip<br /><br />3. Extract this to a temp directory, and run the IMageMagick installer.<br /><br />4. Follow the readme file, which mentions to update your gem and install the RMagick gem.<br /><br />5.Now, the most important part. Reboot your machine [:)]. Don't forget it.<br /><br />6.After this, the sample codes described here :- http://scruffy.rubyforge.org/ started to work, except the graphs being generated was exactly as it appears on this site (as of this writing, wonder why it hasn't been fixed ?), i.e. blank images.<br /><br />7. One blog post which helped me to fix this was :- http://www.ruby-forum.com/topic/193988<br />It suggests to replace the line 35, of the base.rb (for me it is C:\Ruby\lib\ruby\gems\1.8\gems\scruffy-0.2.6\lib\scruffy\renderers\base.rb)with <br /><br />svg.svg(:xmlns => "http://www.w3.org/2000/svg", 'xmlns:xlink' =>"http://www.w3.org/1999/xlink",:viewBox => "0 0 #{options[:size].first} #{options[:size].last}") {<br /><br />After it, the graphs started working like a charm. Looking forward to explore it more. Hope, it saves your time.Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com4tag:blogger.com,1999:blog-612275289405565943.post-17493047045540387832009-10-05T08:13:00.000-07:002009-10-05T08:21:00.811-07:00Mac Terminal Error : Could not determine audit condition<div>When I launched my terminal today, was welcomed with this error :-</div><div><br /></div><div><div>login: PAM Error (line 396): System error</div><div>login: Could not determine audit condition</div><div><br /></div><div>[Process completed]</div><div><br /></div><div>It is most probably because I was playing with my /usr/bin permissions the other day.</div><div>The fix is easy. Just delete the "/usr/bin/login" dir.</div><div><br /></div><div>But how do I delete it, if I can't access the "Terminal" altogether ? </div><div>Come on - You can access any folder using the "Finder".</div><div><br /></div><div>1. Open "Finder"</div><div>2. Open "Go To Folder"</div><div>3. Type "/usr/bin/login"</div><div>4. Delete it.</div><div><br /></div><div>You are done.</div><div> </div></div><div><span class="Apple-style-span" style="font-family:verdana, geneva, lucida, 'lucida grande', arial, helvetica, sans-serif;font-size:100%;color:#6C6F73;"><span class="Apple-style-span" style="font-size: 13px; -webkit-border-horizontal-spacing: 2px; -webkit-border-vertical-spacing: 2px; "><br /></span></span></div>Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com6tag:blogger.com,1999:blog-612275289405565943.post-62208150783646736132009-10-04T19:54:00.000-07:002009-10-04T20:06:28.663-07:00Typica library - Added my patch to set connection timeout<div><a href="http://code.google.com/p/typica/">Typica</a> :- <span class="Apple-style-span" style="font-family: arial, sans-serif; font-size: 13px; ">is a simple API to access Amazon's SQS, EC2, SimpleDB and DevPay LS web services</span></div><div><br /></div>A couple of month ago, I was using this library to interact with the Amazon's SQS queue. While testing, a bug popped up where in case of a network failure, the code was trying to make the connection endlessly.<div><br /></div><div>Here is the <a href="http://code.google.com/p/typica/issues/detail?id=50">history </a>of this bug. I changed the jar and suggested a patch.</div><div><br /></div><div>The good news is that they applied my patch to the code base and from the version 1.6 onwards, this bug shouldn't appear.</div><div><br /></div><div> </div>Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com0tag:blogger.com,1999:blog-612275289405565943.post-20087699651227352232009-09-13T08:32:00.000-07:002009-09-13T08:33:12.417-07:00Why are we happy?<p>TED.com: <a href="http://www.ted.com/talks/dan_gilbert_asks_why_are_we_happy.html">Dan Gillbert asks, Why are we happy?</a>: </p><blockquote><p>...When our ambition is bounded, it leads us to work joyfully. When our ambition is unbounded, it leads us to lie, to cheat, to steal, to hurt others, to sacrifice things of real value. When our fears are bounded, we're prudent, we're cautious, we're thoughtful. When our fears are unbounded and overblown, we're reckless, and we're cowardly.</p></blockquote><p></p><br /><br /><p>The lesson I want to leave you with from these data is that our longings and our worries are both to some degree overblown, because we have within us the capacity to manufacture the very commodity we are constantly chasing when we choose experience.</p><br /><br /><p> </p><br /> <br /> <div><br /><a href="http://feeds.feedburner.com/~ff/KarlMartino?a=c3Day3kZiFk:T36woxWNsN8:yIl2AUoC8zA"><img src="http://feeds.feedburner.com/~ff/KarlMartino?d=yIl2AUoC8zA" border="0" /></a> <a href="http://feeds.feedburner.com/~ff/KarlMartino?a=c3Day3kZiFk:T36woxWNsN8:7Q72WNTAKBA"><img src="http://feeds.feedburner.com/~ff/KarlMartino?d=7Q72WNTAKBA" border="0" /></a><br /></div>"Anshuhttp://www.blogger.com/profile/18379710357924026688noreply@blogger.com0