Handling exceptions

During vulnerability scanning, we figured out there were lot of exceptions handled through print statement. That’s not very efficient way of handling exceptions. Print statements are still better than not writing anything to handle. That’s known as swallowing an exception. A good approach to handle exceptions is to write some way to log those exceptions or throw those exceptions with stack trace during runtime.

What are exceptions ?

Exceptions are error events. These events happen during runtime of a program. This generally disrupts the flow of the program.

There are three components to exception handlers – try, catch and finally.

try – This part of exception handling contains code which will be executed during every flow.

catch – If code in try part throws a runtime exception, that will be caught in catch part.

finally – This contains the code you want to execute after try part of execution is done. This ensures that finally block is executed even when unexpected exceptions occur. It is mostly used to clean up resources.

Types of Exceptions –

  • Unchecked Exceptions – Exception types that are direct or indirect subclasses of  class RuntimeException , those are unchecked exception.
  • Checked Exceptions – Exceptions that inherit Exception class are known as checked exceptions. RuntimeException are also extended from Exception , but client code doesn’t have to handle them, while Checked exceptions have to be handled by catch or throws clause.

How to handle Exceptions

  1. What exceptions to use? Checked or Unchecked?
    – In case the code doesn’t know what to do if an exception is thrown, it should be a unchecked exception. If code using an exception knows what to do to recover
    from that exception along with logging that information, that should be checked exception.
  2. Preserve encapsulation
    – Don’t propagate an exception from data access layer to business object layer.
    Example – SQLException is a RuntimeException. If data access layer throws this exception in following manner , catch block will not do anything, but will suppress it.
      public void dataAccessCode()
    catch (SQLException ex)

    On other hand to preserve encapsulation, the same runtime exception can be converted into another unchecked exception like below

    public void dataAccessCode()
    catch (SQLException ex)
    throw new RuntimeException(ex);

    Best practices for Exceptions
    1) Use finally block for cleaning the code
    2) Do not ignore or suppress an exception
    3) Log exceptions once
    4) Do not use exceptions for flow control


  1. Best Practices for Exceptions
  2. Exceptions by Oracle
  3. Checked Exceptions by Bruce Eckel

SSO with PingFederate using SAML

Ping Federate is a third party vendor which provides capabilities for Single Sign On (SSO) using either SAML or WS-Federation protocol. I recently worked on a project where we had to provide this capabilities to applications.

Here I document how I achieved this through SAML protocol.

SAML stands for Security Assertion Markup Language and it is an open-standard data format for exchanging information related to authentication and authorization (Source-Wikipedia – SAML ). SAML is used mostly for web browser SSO.

Ping Federate plays the role of an Identity Provider or Service Provider depending on what purpose you are using it for.

In this particular post, we will be seeing how a SP initiated SSO works with Ping Federate.

Here are the steps –

Create a SP connection in Ping Federate

Create a unique connection for your SP service in Ping Federate, this unique connection will be identified by Ping Federate with Entity Id which you will create in Ping Federate. Provide an Assertion Consumer Service (ACS) URL in your connection in Ping Federate. Basically Ping will send a response back at ACS URL. There is a step by step process to create a SP connection in Ping Federate.

You will need to specify a protocol to be used for this connection. For our post purposes, we are using SAML 2.0. What kind of binding can be used? Post, Redirect, Artifact, SOAP. For this post, we will be using Post or Redirect.

During the process, you also provide an IdP adapter in the connection. IdP adapter is nothing but the way of authentication – how do you want an user to be authenticated? Through an HTML form or Windows Account? .

You will also need to provide a signing certificate if you are going to send a signed login request to Ping Federate.

Once you create a connection, you set that connection as ACTIVE in ping.

Changes on SP Side

Now when you send a Login request to ping, it will be posted on the protocol endpoint URL from ping side. So Ping provides certain static endpoints for your connection. If Ping is installed on a server called abc.com , the endpoint for Ping will be abc.com/idp/SSO.saml2 and this is where you will post your login request. Here is a sample Login request looks like

<samlp:AuthnRequest xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" ID="_bec424fa533dj2ff020502892fghjjf221" Version="2.0" IssueInstant="2016-02-10T11:39:34Z" ForceAuthn="false" IsPassive="false" ProtocolBinding="urn:oasis:names:tc:SAML:2.0:bindings:HTTP-POST" AssertionConsumerServiceURL="http://abc.bloodycoders.com/login/saml2/sp/AssertionConsumerService.php">
<saml:Issuer xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">
<samlp:NameIDPolicy xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Format="urn:oasis:names:tc:SAML:2.0:nameid-format:persistent" SPNameQualifier="abc.bloodycoders.com" AllowCreate="true" />
<samlp:RequestedAuthnContext xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol" Comparison="exact">
<saml:AuthnContextClassRef xmlns:saml="urn:oasis:names:tc:SAML:2.0:assertion">

Ping Federate will verify the request based on entity id and where the response to be sent. If the request is valid, it will be send a response. On SP side, you then verify the response if it is coming from an authentic source.

(I have not included response back from Ping Federate for post purposes).

The Art of learning – Part II

If you have missed the notes from Part I, they are Here.

Part II notes begin below

85) If I want to be the best, I have to take risks other would avoid, always optimizing the learning potential of the moment and turning adversity to my advantage. That said, there are times when the body needs to heal but those are ripe opportunities to deepen the mental, technical, internal side of my game.

86) When aiming for the top, your path requires an engaged, searching mind. You have to make obstacles spur you to reactive new angles in the learning process.
Let setbacks deepen your resolve. You should always come off an injury or a loss better than when you went down.

87) It is all too easy to get caught up in the routines of our lives and to lose creativity in the learning process. Even people who are completely devoted to cultivating a certain discipline often fall into a mental rut, a disengaged lifestyle that implies excellence can be obtained by going through the motions. We lose presence.

88) If dirty opponents inspire a great competitor to raise his game, he should learn to raise his game without relying on the ugly ruses of his opponents. Once we learn how to use adversity to our advantage, we can manufacture the helpful growth opportunity without actual danger or injury. I call this tool the internal solution – we can notice external events that trigger helpful growth or performance opportunities, and then internalize the effects of those events without their actually happening. In this way, adversity becomes a tremendous source of creative inspiration.

89) Clearly, there is a survival mechanism that allows human beings to channel their physical and mental capacities to an astonishing degree of intensity in life-or-death moments, but can we do this at will?

90) Artists often refer to intuition as a muse. In my opinion, intuition is our most valuable compass in this world. It is the bridge between the unconsicous and the conscious mind.

91) You start with the fundamentals, get a solid foundation fueled by understanding the principles of your discipline, then you expand and refine your repertoire, guided by your individual predispositions, while keeping in touch, however abstractly, with what you feel to be the essential core of the art.

92) Chunking relates to the mind’s ability to assimilate large amounts of information into a cluster that is bound together by certain patterns or principles to a given discipline.

93) The stronger the player, the more sophisticated was his or her ability to quickly discover connecting logical patterns between the pieces(attach,defense,tension, pawn chains etc.) and thus they had better chess memories.

94) In a nutshell, chunking relates to the mind’s ability to take lots of information, find a harmonizing/logically consistent strain, and put it together into one mental file that can be accessed as if it were a single piece of information.

95) By “carved natural pathways” I am referring to the process of creating chunks and the navigation system between chunks. I am not making a literal physical description, so much as illustrating the way the brain operates.

96) Over time each chess principle loses rigidity, and you get better and better at reading the subtle signs of qualitative relativity. Soon enough, learning becomes unlearning. The stronger chess player is often the one who is less attached to a dogmatic interpretation of the principles.

97) The network of my chess knowledge now involves principles, patterns and chunks of information, accessed through a whole new set of navigational principles, patterns, and chunks of information.

98) Learning chess at this level becomes sitting with paradox, being at peace with and navigating the tension of competing truths, letting go of any notion of solidity.

99) Everyone at a high level has a huge amount of chess understanding, and much of what separates the great from the very good is deep presence, relaxation of the conscious mind, which allows the unconscious to flow unhindered. This is a nuanced and largely misunderstood state of mind that when refined involves a subtle reintegration of the conscious mind into a free-flowing unconscious process. The idea is to shift the primary role from the conscious to the unconscious without blissing out and losing the precision the conscious can provide.

100) Chess players must let the unconscious flow while the conscious leads and follows, sorting out details, putting things in order, making precise mathematical calculations.

101) I am making networks of chunks and paving more and more neutral pathways, which effectively takes huge piles of data and throws it over to my high-speed processor- the unconscious. Now my conscious mind, focusing on less, seems to rev up its shutter speed from, say, four frames per second to 300 or 400 frames per second. The key is to understand that my trained mind is not necessarily working much faster than an untrained mind-it is simply working more effectively, which means that my conscious mind has less to deal with.

102) Life-or-death scenario kicks the human mind into a very narrow area of focus. Time feels slowed down because we instinctively zero in on a tiny amount of critical information that our processor can then break down as if it is in a huge font. The trained version of this state of mind shares that tiny area of conscious focus.

103) We cultivate this experience by converting all the other surrounding information into unconsciously integrated data instead of ignoring it.

104) In most situations, we need to be aware of what is happening around us, and our processor is built to handle this responsibility. The key is to practice.

105) At the opponent’s slightest move, I move first, as pertaining to intention-reading and ultimately controlling intention. The deepest form of adherence or shadowing involves a switching of roles, where the follower becomes the followed in a relationship in which time seems to twist in a tangle of minds-this is how the great Tai Chi or Aikido artist guides the opponent into a black hole, or appears to psychically impel the other throw himself on the ground.

106) I let opponents read my facial expressions as I moved through thought processes. My goal was to use my natural personality to dictate the tone of the struggle.

107) Impatience while standing on line at the buffet might betray a problem sitting with tension. It’s amazing how much you can learn about someone when they get caught in the rain! Some will run with their hands over their heads, others will smile and take a deep breath while enjoying the wind. What does this say about one’s relationship to discomfort? The reaction to surprise? The need for control?

108) In physical disciplines like the martial arts, getting into the opponent’s head has an immediate and often violent effect that is much more visible to the observing eyes.

109) Imagine the condensing process of making smaller circles applied to the observation and programming side of this interaction.

110) He is already set up to be thrown with a one-two combination because his reaction to the one is already predictable. I will move before his two. Taking this one step further, if my first movement is condensed enough, it will hardly manifest physically at all. My two appears to be a one. At the opponent’s slightest move, I move first.

111) The battle becomes about reading breath patterns and blinks of the eye, playing in frames the opponent is unaware of, invisible technical manipulation that slowly creates response patterns.

112) In virtually every competitive physical discipline, if you are a master of reading and manipulating footwork, then you are a force to be reckoned with.

113) There are two intertwined components to this process. The first is condensed technique. The second is enhanced perception.

114) There are many weaknesses or tells that may be used to approach this goal – breath patterns, physical tension, inferior technical understanding, complacency,emotion, distraction, and an array of other unconscious, predictable habits can all be homed in on or combined for the desired effect. For simplicity’s sake, let’s focus on the eyes. Specifically the blink.

115) If, through incremental training as described earlier in the book, your unconscious understanding of your discipline of choice has become sufficiently advanced, and you have learned how to trust your physical and intuitive intelligence to handle the technical components of your moment, then your conscious mind can zoom in on very small amounts of data – in this case, the eyes.

116) The car salesman and potential buyer are opponents. When two highly trained minds square off, in any field, the players are in a fight to enter each other’s heads. These exchanges feel like epic tennis rallies in which the tilt of battle sways back and forth as one player picks up on a faint tell that may or may not exist long enough to be exploited, and the other has to feel the danger, and swat the rival out of his mind before it is too late.

117) To master these psychological battles, it is essential to understand their technical foundation.

118) Grandmasters know how to make the subtlest cracks decisive. The only thing to do was become immune to the pain, embrace it, until I could work through hours of mind numbing complexities as if I were taking a lovely walk in the park. I spent years working on this issue, learning how to maintain the tension-becoming at peace with mounting pressure.

119) In every discipline, the ability to be clearheaded, present, cool under fire is much of what separates the best from the mediocre.

120) While more subtle, this issue (of being present) is perhaps even more critical in solitary pursuits as writing, painting, scholarly thinking, or learning. In the absence of continual external reinforcement, we must be our own monitor, and quality of presence is often the best gauge. We cannot expect to touch excellence if “going through the motions” is the norm of our lives. On the other hand, if deep, fluid presence becomes second nature, then life, art, and learning take on a richness that will continually surprise and delight. Those who excel are those who maximize each moment’s creative potential – for these masters of living, presence to the day-to-day learning process is akin to that purity of focus others dream of achieving in rare climactic moments when everything is on the line.

121) The more present we are at practice, the more present we will be in competition, in the boardroom, at the exam, the operating table, the big stage.

122) We have to be prepared by a lifestyle of reinforcement. Presence must be like breathing.

123) Concept of stress and recovery – One of the most telling features of a dominant performer is the routine use of recovery periods. Players who are able to relax in brief moments of inactivity are almost always the ones who end up coming through when the game is on the line.

124) The notion that I didn’t have to hold myself in a state of feverish concentration every second of a chess game was a huge liberation.

125) Regardless of the discipline – the better we are at recovering, the greater potential we have to endure and perform under stress.

126) At LGE, they had discovered that there is a clear physiological connection when it comes to recovery-cardiovascular interval training can have a profound effect on your ability to quickly release tension and recover from mental exhaustion. What is more, physical flushing and mental clarity are very much intertwined.

127) To this day, virtually every element of my physical training revolves around one form or another of stress and recovery.

128) In your performance training, the first step to mastering the zone is to practice the ebb and flow of stress and recovery. This should involve interval training as I have described above, at whatever level of difficulty is appropriate for the age and physical conditioning of the individual.

129) Create a rhythm of intervals like the one I described with my biking. With practice, increase the intensity and duration of your sprint time, and gradually condense rest periods – you are on your way.

130) So if you are reading a book and lose focus, put the book down, take some deep breaths, and pick it up again with a fresh eye.

131) Some simple meditation practice in which your mind gathers and releases with the ebb and flow of your breath.

132) For one thing, now that your conscious mind is free to take little breaks, you’ll be delighted by the surges of creativity that will emerge out of your unconscious. You’ll become more attuned to your intuition and will slowly become more and more true to yourself stylistically. The unconscious mind is a powerful tool, and learning how to relax under pressure is a key first step to tapping into its potential.

133) If you spend a few months practising stress and recovery in your everyday life, you’ll lay the physiological foundation for becoming a resilient dependable pressure player.

134) Not only do we have to be good at waiting, we have to love it. Because waiting is, not waiting, it is life.

135) To have success in crunch time, you need to integrate certain healthy patterns into your day-to-day life so that they are so completely natural to you when the pressure is on. The real power of incremental growth comes to bear when we truly are like water, steadily carving stone. We just keep on flowing when everything is on the line.

136) Let me emphasize that your personal routine should be determined by your individual tastes.

137) The alien feeling of the environment seemed to heighten the threat of my opponents. I was feeling off-balance so I went into my routine, which at that point was a thirty-minute visualization exercise. I came out of it raring to go.

138) I had learned from Jack Groppel at LGE to eat five almonds every forty-five minutes during a long chess game, to stay in a steady state of alertness and strength.

139) Only you know your own body, but the key to nutrition in unpredictable environments like Taiwanese martial arts tournaments is to always be prepared for      exertion by being nourished, but never to have too full a stomach and thereby dull your senses.

140) In life, after all, things don’t always go according to schedule. Ideally we should be able to click into the zone at a moment’s notice.

141) The next step of the process is to gradually alter the routine so that it is similar enough so as to have the same physiological effect, but slightly different so as to make the “trigger” both lower-maintenance and more flexible. Th key is to make the changes incrementally, slowly, so there is more similarity than difference from the last version of the routine. This way the body and mind have the same physiological reaction even if the preparation is slightly shorter.

142) This process is systematic, straightforward, and rooted in the most stable of all principles: incremental growth.

143) I trained myself to be completely prepared after a deep inhalation and release. I also learned to do the form in my mind without moving at all. The visualization proved almost as powerful as the real thing.

144) The ideal for any performer is flexibility. If you have optimal conditions, then it is always great to take your time and go through an extended routine. If things are less organized, then be prepared with a flexible state of mind and a condensed routine. Presence has taught me how to live.

145) There are those elite performers who use emotion, observing their moment and then channeling everything into a deeper focus that generates a uniquely flavored creativity.

146) How to use the most decisive emotions, one that can make or break a competitor – ANGER

147) First we learn to flow with distraction. Then we learn to use distraction, inspiring ourselves with what initially would have thrown us off our games. Finally we learn to re-create the inspiring settings internally. We learn to make sandals.

148) It took me sometime to realize that blocking out my natural emotions was not the solution. Instead of being thrown off by or denying my irritation, I had to somehow channel it into a profound state of concentration.

149) The next step in my growth process would be to stay true to myself under increasingly difficult conditions.

150) There were two components to this work. One related to my approach to learning, the other to performance. On the learning side, I had to get comfortable dealing with guys playing outside the rules and targeting my neck, eyes, groin etc. This involved some technical growth, and in order to make those steps I had to recognize the relationship between anger, ego and fear. I had to develop the habit of taking on my technical weaknesses whenever someone pushed my limits instead of falling back into a self-protective indignant pose. Once that adjustment was made, I was free to learn. Dirty players were my best teachers.

151) On the performance side, I had made some strides, but still had a long way to go. First of all, I had to keep my head on straight no matter what. Feelings of anger and fear and elation emerge from deep inside of us and I think blocking them out is an artificial habit. In my experience, competitors who make this mistake tend to crumble when pushed far enough.

152) The only way to succeed is to acknowledge reality and funnel it, take the nerves and use them. We must be prepared for imperfection. The Soft Zone approach is much more organic and useful than denial.

153) It has been my observation that the greatest performers convert their passions into fuel with tremendous consistency.

154) Instead of being dominated by or denying my passions, I slowly learned how to observe them and feel how they infused my moment with creativity, freshness, or darkness.

155) Instead of running from our emotions or being swept away by their initial gusts, we should learn to sit with them, become at peace with their unique flavors, and ultimately discover deep pools of inspiration.

156) While initially this may have been disorienting, now I used it to sharpen my game, up the intensity, funnel my primal heat into a penetrating focus.

157) I highly recommend that you incorporate the principles of Building Your Trigger into your process. Once you are no longer swept away by your emotions and can sit with them even under pressure, you will probably notice that certain states of mind inspire you more than others.

158) There is, however, a process we can follow to discover our unique path. First, we cultivate The Soft Zone, we sit with our emotions, observe them, work with them, learn how to let them float away if they are rocking our boat, and how to use them when they are fueling our creativity. Then we turn our weaknesses into strengths until there is no denial of our natural eruptions and nerves sharpen our game, fear alerts us, anger funnels into focus. Next we discover what emotional states trigger our greatest performances. Introspect. The Make Sandals.

159) The real art in learning takes place as we move beyond proficiency, when our work becomes an expression of our essence.

160) While this principle of penetrating the macro through the micro is a critical idea in the developmental process, it is also an absolutely pivotal foundation for a great competitor.

161) Watching yourself on video, you can spot tells or bad habits. You can refine your techniques by breaking down what works and what doesn’t.

162) What I think about creativity, it is always in relation to a foundation. We have our knowledge. It becomes deeply internalized until we can access it without thinking about it. Then we have a leap that uses that we know to go one or two steps further. We make a discovery. Most people stop here and hope that they will become inspired and reach that state of “divine insight” again. In my mind, this is a missed opportunity. Imagine that you are building a pyramid of knowledge. Every level is constructed of technical information and principles that explain that information and condense it into chunks. Once you have internalized enough information to complete one level of the pyramid, you move on to the next. Say you are ten or twelve levels in. Then you are have a creative burst like the ones Dan and I had in the ring. In that moment, it is as if you are seeing something that is suspended in the sky just above the top of your pyramid. There is a connection between that discovery and what you know-or else you wouldn’t have discovered it-and you can find that connection if you try. The next step is to figure out the technical components of your creation. Figure out what makes the magic tick.

163) In the end, mastery involves discovering the most resonant information and integrating it so deeply and fully it disappears and allows us to fly free.

The Art Of Learning – Part I

Here I am presenting notes from the book “The Art of learning” by Josh Waitzkin. These notes are applicable to any skill/discipline you are trying to master.

1) Bruce nurtured my love for chess, and he never let technical material smother my innate feeling for the game.
– You should trust your guts at first to learn new things, how would you approach something if you didn’t know how to do that thing from technical information.
2) As a six and seven year old boy I had two powerful currents to my chess education, and the key was to make them coexist peacefully – the street tough competitor had to fuse with the classically trained, patient player that Bruce was inspiring.
3) They kept me out of tournaments until I had been playing chess for a year or so, because they wanted my relationship to the game to be about learning and passion first, and competition a distant second.
– You must learn the game first for process and be passionate about learning, results and competitions don’t matter.
4) I thrived under adversity.My style was to make the game complex and then work my way through the chaos.
5) I was unhindered by internal conflict – a state of being that I have come to see as fundamental to the learning process. Bruce and the park guys had taught me how to express myself through chess, and so my love for the game grew every day.
6) The boating life has also been a wonderful training ground for performance psychology. Living on the water requires constant presence, and the release of control.
7) I learned at sea that virtually all situations can be handled as long as presence of mind is maintained. On the other hand, if you lose your calm when crisis hits seventy miles from land, or while swimming with big sharks, there is no safety net to catch you.

8) a) What is the difference that allows some to fit into that narrow window to the top?
b) What is the point? If ambition spells probable disappointment, why pursue excellence?
ANS – In my opinion, the answer to both questions lies in a well-thought-out approach that inspires resilience, the ability to make connections between diverse pursuits, and day-to-day enjoyment of the process.

9) Two theories of intelligence a) Entity  b) incremental
10) Children who are entity theorists are prone to use language like “I am smart at this”. They see their overall intelligence or skill level at a certain discipline to be a fixed entity, a thing that can not evolve. Incremental theorists are prone to use language like “I got it because I worked very hard at it”. A child with a learning theory of intelligence tends to sense that with hard work, difficult material can be grasped. Children who associate success with hard work tend to have a “Mastery-oriented response” to challenging situations, while children who see themselves as just plain smart or dumb or good or bad at something, have a “learned helplessness orientation”.
11) What is compelling about this is that the results have nothing to do with intelligence level.
12) Entity theorists tend to have been told that they did well when they have succeeded, and that they weren’t any good at something when they have failed.
13) Learning theorists, on the other hand, are given feedback that is more process oriented. Julie learns to associate efforts with success and feels that she can become good at anything with some hard work.
14) The key to pursuing excellence is to embrace an organic, long-term learning process, and not to live in a shell of static, safe mediocrity.
15) In the long run, painful losses may prove much more valuable than wins – those who are armed with a healthy attitude and are able to draw wisdom from every experience, “good” or “bad”, are the ones who make it down the road.
16) Author was gradually internalizing a marvelous methodology of learning – the play between knowledge, intuition, and creativity.
17) For children who focus early on openings, chess becomes about results.
18) Their dialogues with teachers, parents and other children are all about results, not effort. They consider themselves winners because so far they have won.
19) I have used chess to illustrate this entity/incremental dynamic, but the issue is fundamental to the pursuit of excellence in all fields.
20) A key ingredient to my success in those years was that my style on the chessboard was a direct expression of my personality.
21) I was a free flow performer, unblocked by psychological issues and hungering for creative leaps.
22) Just as muscles get stronger when they are pushed, good competitors tend to rise to the level of the opposition.
23) My whole career, my father and I searched out opponents who were a little stronger than me, so even as I dominated the scholastic circuit, losing was part of my regular experience. I believe this was important for maintaining a healthy perspective on the game.
24) While a fixation on results is certainly unhealthy, short term goals can be useful developmental tools if they are balanced within a nurturing long-term philosophy
25)How can we balance long-term process with short-term goals and inevitable setbacks?
26) There is nothing like a worthy opponent to show us our weaknesses and push us to our limit.
27) Internalize a process-first approach by making everyday feedback respond to effort over results. Praise good concentration, a good day’s work, a lesson learned. When one wins a tournament game, the spotlight should be on the road to that moment and beyond as opposed to the glory. It is ok for a child (or adult) to enjoy a win.
28) We enjoy the win fully while taking a deep breath, then we exhale, note the lesson learned, and move on to the next adventure.
29) If someone loses, how should his/her mom handle this moment? First of all, she shouldn’t say that it doesn’t matter, because that person knows better than that and lying about the situation isolates that person in his/her pain. So empathy is a good place to start.
30) Disappointment is a part of the road to greatness.
31) Through introspective dialogues, one will learn that every loss is an opportunity for growth. He will become increasingly astute psychologically and sensitive to bad habits.
32) Growth comes at the point of resistance. We learn by pushing ourselves and finding what really lies at the outer reaches of our abilities.
33) I dove deeper and deeper into chess. Of course there were plateaus, periods when my results leveled off while I internalized the information necessary for my next growth spurt, but I didn’t mind.
34) The Soft Zone – A man wants to walk across the land, but the earth is covered with thorns. He has two options – one is to pave his road, to tame all of nature into compliance. The other is to make sandals. Making sandals is the internal solution. Like the soft zone, it does not base success on a submissive world or overpowering force, but on intelligent preparation and cultivated resilience.
35) If your opponent is pushing you, making you angry – I have to come to believe that the solution to this type of situation does not lie in denying our emotions, but in learning to use them to our advantage. Instead of stifling myself, I needed to channel my mood into heightened focus – and I can’t honestly say that I figured out how to do this consistently until years into my martial arts career when dirty opponents tried to take out my knees, target the groin or head-butt me in the nose in competition.
36) When uncomfortable, my instinct is not to avoid the discomfort but to become at peace with it.
37) In game after game, beginners fall to pieces after making the first mistake. With older, more accomplished players the mistakes are subtler, but the pattern of error begetting error remains true and deadly.
38) Musicians, actors, athletes, philosophers, scientists, writers understand that brilliant creations are often born of small errors. Problems set in if the performer has a brittle dependence on the safety of absolute perfection or duplication. Then an error triggers fear, detachment, uncertainty, or confusion that muddies the decision-making process.
39) Numbers to leave numbers OR form to leave form – A process in which technical information is integrated into what feels like natural intelligence. Sometimes, there will literally be numbers. Other times there will be principles, patterns, variations, techniques, ideas.
40) During my study of the critical positions, I noted the feeling I had during the actual chess game. I explained above how in the pressure of tournaments, the tension in the mind mounts with the tension in the position, and an error on the board usually parallels a psychological collapse of sorts.
41) I was having trouble with the first major decision following the departure from prepared opening analysis and I was not keeping pace with sudden shifts in momentum. My whole chess psychology was about holding on to what was, because I was fundamentally homesick. When I finally noticed this connection, I tackled transitions in both chess and life. In Chess games, I would take some deep breaths and clear my mind when the character of the struggle shifted. In life, I worked on embracing change instead of fighting it. With awareness and action, in both life and chess my weakness was     transformed into a strength.
42) A key component of high-level learning is cultivating a resilient awareness that is the older, conscious embodiment of a child’s playful obliviousness.
43) This journey from child back to child again, is at the very core of my understand of success.
44) The most critical factor in the transition to becoming a conscious high performer is the degree to which your relationship to your pursuit stays in harmony with your unique disposition. There will inevitably be times when we need to try new ideas, release our current knowledge to take in new information- but it is critical to integrate this new information in a manner that does not violate who we are.
45) The path to artistic insight in one direction often involves deep study of another– the intuition makes uncanny connections that lead to a crystallization of fragmented notions.
46) Two ways of taming a wild horse. One is to tie it up and freak it out. This is the method some like to call shock and awe.
47) Then there is the way of the horse whisperers.
48) A competitor needs to be process-oriented, always looking for stronger opponents to spur growth, but it is also important to keep on winning enough to maintain confidence. We have to release our current ideas to soak in new material, but not so much that we lose touch with our unique natural talents. Vibrant creative idealism needs to be tempered by a practical, technical awareness.
49) When I watched my first tai chi class, was that the goal was not winning, but, simply, being.
50) The idea is that a particular art has created a superior method of breath control and this method should be followed religiously. William Chen’s humble vision of this issue is that breathing should be natural. Or, more accurately, breathing should be a return to what was natural before we got stressed out by years of running around a hectic world and internalizing bad habits.
51) It is Chen’s opinion that a large obstacle to a calm, healthy present existence is the constant interruption of our natural breathing patterns.
52) Tai Chi Meditation is among other things, a haven of unimpaired oxygenation.
53) The essence of Tai Chi Chuan as a martial art is not to clash with the opponent but to blend with his energy, yield to it, and overcome with softness.
54) The martial philosophy behind Push Hands, in the language of the Tai Chi Classics, is “to defeat a thousand pounds with four ounces”.
55) If aggression meets empty space it tends to defeat itself.
56) The problem is that we are conditioned to tense up and resist incoming or hostile force, so we have to learn an entirely new physiological response to aggression.
57) One of the most challenging leaps for Push Hands students is to release the ego enough to allow themselves to be tossed around while they learn how not to resist.
58) In order to grow, student needs to give up his current mind-set. He needs to lose to win. The bruiser will need to get pushed around by little guys for a while, until he learns how to use more than brawn. This is called as Investment in loss.Investment in loss is giving yourself to the learning process.
59) So the aim is to minimize repetition as much as possible, by having an eye for consistent psychological and technical themes of error.
60) In those early Tai Chi years, my mission was to be wide open to every bit of information. I tried my best to learn from each error, whether it was my own or that of a training partner.
61) A large part of Tai Chi is releasing tension from your body through the practice of the meditative form.
62) With practice, the stillness is increasingly profound and the transition into motion can be quite explosive-This is where the dynamic pushing or striking power of Tai Chi emerges.
63) First as I got used to takings shots from Evan, I stopped fearing the impact. My body built up resistance to getting smashed, learned how to absorb blows, and I knew I could take what he had to offer. Then as I became more relaxed under fire, Evan seemed to slow down in my mind. I noticed myself sensing his attack before it began. I learned how to read his intention, and be out of the way before he pulled the trigger. As I got better and better at neutralizing his attacks, I began to notice and exploit weaknesses in his game, and sometimes I found myself peacefully watching his hands come toward me in slow motion.
64) It’s clear that if in the beginning I had needed to look good to satisfy my ego, then I would have avoided that opportunity and all the pain that accompanied it.
65) Most critically, Evan was unwilling to invest in loss himself. He could have taken my improvement as a chance to raise his game, but instead he opted out.
66) Two most important concepts in any skill – Beginner’s mind and Investment in loss.
67) It is not so difficult to have a beginner’s mind and to be willing to invest in loss when you are truly a beginner, but it is much harder to maintain that humility and openness to learning when people are watching and expecting you to perform.
68) This was a huge problem for me in my chess career after the movie came out. Psychologically, I didn’t give myself the room to invest in loss.
69) My response is that it is essential to have a liberating incremental approach that allows for times when you are not in a peak performance state.
70) What is not so well known, is that Jordon also missed more last-minutes shots to lose the game for his team than any other player in the history of the game. What made him the greatest was not perfection, but a willingness to put himself on the line as a way of life. He was willing to look bad on the road to basketball immortality.
71) The learning principle is to plunge into the detailed mystery of the micro in order to understand what makes the macro tick.
72) The most common error in the learning of martial arts: to take on too much at once.
73) The Tai Chi system can be seen as a comprehensive laboratory for internalizing good fundamentals, releasing tension, and cultivating energetic awareness.
74) The key was to recognize that the principles making one simple technique tick were the same fundamentals that fueled the whole expansive system of Tai Chi Chuan.
75) My understanding of process, in the spirit of numbers to leave numbers method of chess study, is to touch the essence of a technique, and then to incrementally condense the external manifestation of the technique while keeping true to its essence. Over time expansiveness decreases while potency increases. This is called as “Making Smaller Circles”
76) Sometimes you have to watch in slow motion, over and over, to see any punch at all. They have condensed large circles into very small ones, and made their skills virtually invisible to the untrained eyes.
77) Michael Adams knows how to control the center without appearing to have anything to do with the center. He has made the circles so small, even Grandmasters cannot see them.
78) It is rarely a mysterious technique that drives us to the top, but rather a profound mastery of what may well be a basic skill set. Depth beats breadth any day of the week, because it opens a channel for the intangible, unconscious, creative components of our hidden potential.
79) Distraction should be converted into fuel for high performance. In the chess scene, the shaking jolted my mind into clarity and I discovered the critical solution to the position. In the push hands moments, my broken hand made time slow down in my mind and I was able to reach the most heightened state of awareness of my life.
80) There critical steps in a resilient performer’s evolving relationship to chaotic situations. First we have to learn to be at peace with imperfection.
Next, in out performance training, we learn to use that imperfection to our advantage. The third step of this process, as it pertains to performance psychology, is to learn to create ripples in our consciousness, little jolts to spur us along, so we are constantly inspired whether or not external conditions are inspiring. So a deep mastery of performance psychology involves the internal creation of inspiring conditions.
81) It is very important for athletes to do visualization work, in a form appropriate to their discipline, but often when we are caught up in the intense routine training and competition, it feels like we have no time for internal stuff.
82) The importance of undulating between external and internal(or concrete and abstract; technical and intuitive) training applies to all disciplines, and unfortunately the internal tends to be neglected.
83) In all athletic disciplines, it is the internal work that makes the physical mat time click, but it is easy to lose touch with this reality in the middle of the grind.
84) Any moment that one piece can control, inhibit, or tie down two or more pieces, a potentially critical imbalance is created on the rest of the board. On a deeper level, this principle can be applied psychologically whenever opposing forces clash. Whether speaking of a corporate negotiation, a legal battle, or even war itself, if the opponent is temporarily tied down qualitatively or energetically more than you are expending to tie it down, you have a large advantage. The key is to master the technical skills appropriate for applying this idea to your area of focus.

Thread-safe code

Yes, just like every other programmer, I have been asked “Is this code thread safe?” and many times I have pondered in my head , what that actually means. Honestly I am not competent enough in multi-threading programming and even answering this question. But then there comes a time when you learn about this and say “Yes, the code is thread safe and it will execute correctly in case of simultaneous execution by multiple threads.”

Wikipedia says about thread-safety

“A piece of code is thread-safe if it only manipulates shared data structures in a manner that guarantees safe execution by multiple threads at the same time “

Most of the problems arise in multi-threaded environment when accessing shared data.

Here is an example of the code which can be safe in single threaded environment, but not in multi threaded.

public class Counter {
   private static int count = 0;
   public static int incrementCount() {
      return count++;

count is a shared integer variable here. In a multi-threaded environment, it can lose the right value during the update operation. Increment operation for count performs read, add and update. In case if two threads are accessing incrementCount method and not synchronized, they can cause wrong value of count.

How to make this code thread safe

public class Counter {
   private static int count = 0;
   public static synchronized int incrementCount() {
      return count++;

synchronized adds that mutual exclusion between threads while accessing incrementCount method. So at one time,only one thread can access the method. Instead of making the whole method synchronized, only part of the code can also be made synchronized.


Are you master of your domain? well, that doesn’t matter if you are good with one language. Your left brain makes you work for learning new language, so have you decided to travel to Spain or Italy and want to speak with locals in their language? It is a good idea to learn basics of their language.

I took Italian at the age of 30 and oh boy, it was hard to practice that language at that age. When you grow up as a kid, your brain is developing and at that age, it grasps the nuts and bolts of languages faster than when you are grown up. It might also be with discipline.

Duolingo is an Android and iOS app which offers simple writing, reading,pronunciation, listening exercises of language that you want to practice. I loved the user interface of this application since it is very easy to use and simple with images and text. From an user perspective, the application has been designed in a game format and that means you can go to next level only if you finish that particular level. Very amazing.

If you are a language nerd, I would totally recommend this particular app if you are looking to practice or have lost touch with a language which you love. I use the app for practicing Italian since I am not good with speaking it, but i can write it, so the app helps me with pronunciation and listening.

Rating – 9 / 10