Erlang maps basics

erl> maps: for python>>>dict() people

just watch and think series:

How to create a new map in erlang?

 47>
 47>
 47> MyNewMap = maps:new().
 #{}
 48> MyNewMap
 48> .
 #{}
 49> maps:put(name, "Navaneethan", MyNewMap).
 #{name => "Navaneethan"}
 50> MyNewMap.
 #{}
 51> MyNewMap2 = maps:put(name, "Navaneethan", MyNewMap).
 #{name => "Navaneethan"}
 52> MyNewMap2.
 #{name => "Navaneethan"}
 53> MyNewMap.
 #{}
 54> maps:put(age, 26, MyNewMap2).
 #{age => 26,name => "Navaneethan"}
 55> MyNewMap2.
 #{name => "Navaneethan"}
 56> % RETURNS NEW MAP. Not updating into old one.%
 

Part2 in Maps(remove, put, update, without,values,to_list ):

 56> maps:remove('name',MyNewMap).
 #{}
 57> maps:remove(name,MyNewMap).
 #{}
 58> MyNewMap.
 #{}
 59> maps:remove(name,MyNewMap2).
 #{}
 60> MyNewMap2.
 #{name => "Navaneethan"}
 61> MyNewMap2 = maps:put(name, "Navaneethan", MyNewMap).
 #{name => "Navaneethan"}
 62> MyNewMap2 = maps:put(age, "26", MyNewMap).
 ** exception error: no match of right hand side value #{age => "26"}
 63> MyNewMap2.
 #{name => "Navaneethan"}
 64> f(MyNewMap2).
 ok
 65> MyNewMap2 = maps:put(age, "26", MyNewMap).
 #{age => "26"}
 66> MyNewMap2.
 #{age => "26"}
 67> MyNewMap2 = maps:put(work, "Python", MyNewMap2).
 ** exception error: no match of right hand side value #{age => "26",work => "Python"}
 68> MyNewMap3 = maps:put(work, "Python", MyNewMap2).
 #{age => "26",work => "Python"}
 69> maps:to_list(MyNewMap3).
 [{age,"26"},{work,"Python"}]
 70> maps:update(work,"erlang",MyNewMap3).
 #{age => "26",work => "erlang"}
 71> MyNewMap3.
 #{age => "26",work => "Python"}
 72> %Update Returns New one.%
 72> maps:values(MyNewMap3).
 ["26","Python"]
 73> ReqKeys = [name, 'book', age, 'age'].
 [name,book,age,age]
 74> maps:with(ReqKeys, MyNewMap3).
 ** exception error: undefined function maps:with/2
 75> MyNewMap3.
 #{age => "26",work => "Python"}
 76> maps:with([name], MyNewMap3).
 ** exception error: undefined function maps:with/2
 77> maps:with(ReqKeys, MyNewMap3).
 ** exception error: undefined function maps:with/2
 78> maps:without(ReqKeys, MyNewMap3).
 #{work => "Python"}
 79>

Points to be noticed:

This is erlang map which is similar to the python dictionary.Here we do some mandate operations with map.

If you pass your map to in built function in maps module, it returns new map which is unbounded.(line:62 & 67)

Rest of the things are similar like other programming languages.

Tagged with:
Posted in erlang

Erlang day1

Erlang day1:

  1. Erlang shell an introduction
  2. How to use the erlang shell?
  3. few basic data structure tricks

Erlang shell an introduction:

In order to get your erlang shell,you have to install the erlang OTP for your platform(Windows/Linux).
Once installed erlang software, you can type erl to launch the shell.
In erl you can do the experiments in erlang.

watch the screen & read the below marks:

erl day 1

Few things keep remember:

The new values can’t be assigned to the bounded varialbes.Use always a unbound variable to store the value.Varialbes starts with caps(i.e Var).
_ is always used to unregister the value.The value will be omitted if it is assigned to the underscore.

Data structures are atoms, tuple, list.

  • tuple: It is represented by {}. e.g {1,2,3,4}.
  • atom: This is just a variable which is used name the data to match the pattern.
    eg.  {person, Name} = {person, "navaneethan"}.
    

    in this above example two tuples are matched with help of atom person, so the variable Name will be bounded to the value navaneethan.Finally, this pattern match is successful.

  • list: []
    e.g: [1,2,3,4].

Few weird things with tuples and lists:

  • Two tuples are compared with the no of elements on each tuple.
  • Two lists are compared with Dictionary associate property.
Tagged with:
Posted in erlang

an intro to Erlang

an intro to Erlang:

I have started Erlang last weekend.Few things will amaze you if you start following it.You would get inspired of it’s powerful features.I would like to share with you my thoughts also what I learned in this one day.

Erlang creations:

Using erlang, there are quite # of powerful tools were built for real time usage.For example,

  • Facebook chat 100million requests are being handled
  • simpledb in AWS were implemented
  • Delicious bookmarking tool
  • sms component in TMobile
  • rabbitmq
  • couchdb
  • It has been tested in all sides in ATM AXD301 machine.

What erlang gives to us?

It is the concurrent programming language. It derives many features from various type of programming language to be focused o concurrent application implementation effectively.

So, Erlang guts are

  • No shared memory
  • Functional programming language
  • immutable and pattern matching

No sharing

There is nothing about shared memory in erlang virtual machine.The process communication is handled through message passing in asynchronous way to avoid synchronization overhead.So, it is the server side programming language, where you can derive the needful specific behavior(event handler, finite state machine) from erlang library to implement your server.

immutable and pattern matching

variables can’t be reassigned.The value of the variable can’t be changed.It has the feature called pattern matching to extract the data from the clause.

Functional programming language

Dynamic type system is used in erlang. Functional programming features are the core in erlang.

useful links

http://learnyousomeerlang.com/content

Thanks.

Tagged with:
Posted in erlang

10min python: dis assembler

10min python: dis

what is dis?

dis is the disassembler. It shows to you how the python interpreter executes your python code in human readable format.

why do we need it?

To understand and optimise your python code to make it easier to the world.

how it works?

There is an inbuild module called dis which has the job and does it.It just reads the compiler understandable code(means byte code) and converting into mneumonics which is the cpu understandable language.

def your-function():
    pass

>>>dis.dis(your-function)

example:

In [3]: import dis

In [4]: help(dis)

In [5]: def show_mybytes(a, b):
   ...:     l = []
   ...:     l.append(a)
   ...:     l.append(b)
   ...:     c = a + b
   ...:     l.append(c)
   ...:     return l
   ...: 

In [6]: show_mybytes(4,5)
Out[6]: [4, 5, 9]

output:


In [8]: dis.dis(show_mybytes)
  2           0 BUILD_LIST               0
              3 STORE_FAST               2 (l)

  3           6 LOAD_FAST                2 (l)
              9 LOAD_ATTR                0 (append)
             12 LOAD_FAST                0 (a)
             15 CALL_FUNCTION            1
             18 POP_TOP             

  4          19 LOAD_FAST                2 (l)
             22 LOAD_ATTR                0 (append)
             25 LOAD_FAST                1 (b)
             28 CALL_FUNCTION            1
             31 POP_TOP             

  5          32 LOAD_FAST                0 (a)
             35 LOAD_FAST                1 (b)
             38 BINARY_ADD          
             39 STORE_FAST               3 (c)

  6          42 LOAD_FAST                2 (l)
             45 LOAD_ATTR                0 (append)
             48 LOAD_FAST                3 (c)
             51 CALL_FUNCTION            1
             54 POP_TOP             

  7          55 LOAD_FAST                2 (l)
             58 RETURN_VALUE        

In [9]: 

in this above example, first column is line no of our python code statements.Second column is the neumonic instraction address position(I think but not sure), third column is the mneumonic instructions for the cpu, last column is human understanble format mapping between python code to assembly code

Tagged with: , ,
Posted in 10min, Python

10min python: settrace

10min python:

what is settrace?

settrace traces each execution instruction of python script

Where we can use it?

If you want to trace the execution sequence and it’s control over your entire script, this should be the right utility.It does similar to Django’s middleware property

How to use it?

import sys

def callback(frame, event, arg):
    '''
    do your magic using frame, event, arg
    '''

sys.settrace(callback)
#your script starts from here

example?

import sys


def mycallback(frame, event, arg):
    print "event is %s" %event
    print "args are %s" %arg
    print "current exe line funcname: %s" %frame.f_code.co_name
    print "current execution line: %s" %frame.f_lineno
    print "caller line no: %s" %frame.f_back.f_lineno
    print "caller file name: %s" %frame.f_back.f_code.co_name
    '''
    return callback function is important to trace the sequence of all instraction from entry to exit, if return is `None` only one instruction will be traced
    '''
    return mycallback 


def function(arg1, arg2):
    print "Input: ",arg1, arg2
    return arg1 + arg2

sys.settrace(mycallback)
print function(4,5)
sys.settrace(None)

output

settrace in pythonkudos links:

http://pymotw.com/2/sys/tracing.html

bye bye!

 

Tagged with: ,
Posted in 10min, Academic, Python

Knowledge is for Sharing

Knowledge is for sharing.

"Just even if you are the best programmer in the world, not sharing means then nothing more useful by you."
"The wealth of the tree is considered upon producing the fruits."

Here Shathimaan does his job. He made a book called i want 2 do project, tell me what 2 do which is the composed version of his experience.

I appreciate him first.

I ordered this book last week for Rs 399. I got it delivered by today. Initially, i felt little disappointed when i took first look of the book.Since, it has very less no of pages for the cost Rs 399.I started it, it went very well, everything was explained in crispy manner, no less in clarity. All flavors are mixed in the manner which will make strengthen the understanding of getting things done.

I realized in the midst of the chapter that I was wrong on my initial disappointment. :(

I would say shortly, This book is like a “ABCD for the software programmers”. Everyone should have passed this understanding, before taking their weapons. I am happy at least I am getting understand right now. Thank you Shakthi Kannan for this wonderful piece. I am sure, this creature will make more creatures in open source industry.

Tagged with: ,
Posted in Free Software, General, open source

Must read of RR Interview – (Imp to India)

THE INTERVIEW

Rajas Mehendale, Sister Nivedita School, Dombivali East: The mere rumour of US cutting down on Federal stimulus saw the rupee crash; when will we see Indian policy affecting other countries so intensively?

Raghuram Rajan: It’s a great question. I have been saying that the US should worry about the effect of its policies on the rest of the world. If I stood by that, we would not be very happy down the line when Indian policies affect the rest of the world adversely. We would like to live in a world where countries take into account the effect of their policies on other countries and do what is right broadly rather than just what is right given the circumstances of the country. My guess is that by the time you are old enough to get a job, we will be a significant force in the world economy. We are a country that has kept its borders relatively open and is opening up even more. So flows in and out will be important and we will have a lot of influence on the world. I suspect when you are my age, we will be one of the two or three greatest economies in the world and you as central bank governor will have to decide the kind of policies that are appropriate for the world and not just for India at that time.


Warren D Silva, Rose Manor Garden School, Santa Cruz: The number of train accidents are on the rise. Are they being caused by economic growth?

Raghuram Rajan: You are linking train accidents to growth. Clearly increased activity has some adverse effects – pollutions, train accidents, road accidents. When there were no cars on the roads, we did not have too many accidents. While there are adverse effects of growth, there are positive effects. What you have to weigh is the adverse effects against the positive effects. The mistake that a number of activists make is by looking at a very narrow piece – the piece they are activists about. ‘I am worried about pollution or worried about this species being extinct’. Those are important issues, but those have to be traded off against the benefits of growth. That appropriate trade-off comes from debate and it is important that whatever you are fighting for, you certainly should fight for it, but be prepared to listen to the other side also. There is a middle ground and the middle ground means protecting the environment, protecting the species from going extinct, but at the same time giving the poor the opportunity to earn a living, which is very necessary for them to have a better life. Just because we have a better life, we should not succumb to, what is called ‘Nimby’ – not in my backyard. ‘I am going to protect my neighbourhood because it is good, clean, great, wonderful, and keep out everything else’, even though this has longer term destructive effects for a large number of people. So think about the broader perspective even when you are fighting for local issues.


Pranav Rajkumar, Thakur Vidya Mandir: In India and various parts of Mumbai there are so many slums and poor people; why should it be wrong to create more extra money and distribute it among these people?

Raghuram Rajan: Whether it is money, food, clothing, whatever, certainly some amount of distribution is warranted in a poor country. But if are to really distribute something, the best thing to distribute is opportunity. Can we distribute opportunity? And this goes back to the saying, if you give somebody fish, he will be back tomorrow for more; if you teach him to fish, he will be independent, he won’t have to come back. It does mean a certain basic level of nutrition, access to school, access to better education, access to scholarships. Those are very important, they give a chance to break away. But they should not feel they are permanently in a situation where they are continuously going to get. It makes them lose respect for their situation. But if they can become independent, they have both self respect and respect of others. I think we should aim to broaden opportunity; we should look for children falling behind and make sure they have the chance to succeed.


Zaib, Cathedral & John Connon School: Why is there still inflation even if there isn’t enough money to go around? People are poor but there is still inflation?

Raghuram Rajan: I have to think about your question. So, they don’t have money, they have demand. If they had money, the demand would be expressed. But the real problem is they do not have jobs either. They are not contributing to supply, they are not producing those goods which could be bought. Essentially, as a result, they are excluded from the economy. They are not responsible for the inflation, but they are not also helping bring it down because they do not have the jobs that would create the supply and bring down inflation. Inflation is being caused by others, so I would not blame the poor for the inflation that we see.


Manuja Sawant, Yashodam High School: How did you feel when you became the governor of RBI and what changes would you like to bring about holding this respectable position?

Raghuram Rajan: That is a hard question to answer. Partly, I feel a great sense of responsibility because I became governor at a time when there was a lot of turmoil in the markets and suddenly you start thinking that your decisions will have a lot of impact either for the good or the bad. So it does put a lot of pressure on you to think about how you will make the right decisions. Over time you think about what value you can add in whatever position you are than the position itself. I think it is the weight of responsibility itself as well as the challenge of adding value – those are the things that you think about at such times.


Jhanvi Agarwal, Dr Pillai Global Academy: You made a long journey from learning in California to working in India today, can you share your experience?

Raghuram Rajan: Chicago, I should say – Midwest. When I graduated from college, the allure of studying further, or learning more, of writing was very strong for me. The best places in the world to do that were in foreign universities – more specifically in the United States. I went abroad. At the same time while you engage in a career there, I think many Indians who go abroad feel that there is something they can do for their own country. I started a conference in India but also started talking to government officials. But ultimately you realise that there is an enormous amount you can do here. In industrial countries, because in they are already so well-off, in terms of public policy, you can only make small differences. But here you can make enormous changes. If you multiply those changes with the 1.2 billion people that we have, the effect you have, hopefully for the good, in the longer term is so much more. Many Indians return to India with the hope of making a difference. Many of them I encounter now in the financial sector. Many of them give up lucrative jobs outside, because they find it exciting and self-fulfilling. I am not in any way suggesting that they are doing charity or doing anything noble in that sense. They are expressing themselves, they are getting value from it but it is also beneficial for our country. So they come back, they start interesting projects, one that I am particularly excited about is one where somebody who worked with a telecom firm came back and is working with banks making it easier to send remittances from a bank to a villager in a very remote area. The villager just goes to an ATM, punches in a number and gets his money out. These kinds of people add enormously to our economy. That sort of describes a little bit of my journey and more importantly the journey of others.


Shreyas, Guardian School, Dombivali: In social media we come across posts that ask us to promote indigenous goods. Does it really help the economy of the country?

Raghuram Rajan: I don’t have a problem with a movement that. If people want to buy local or buy domestic that is their choice. If they want to help the neighbourhood shop by going there, that is their choice. But, to force it by saying ‘We are going to keep out imports’ or ‘We are going to prevent you from exercising choice’ is more problematic. It is problematic partly because you are reducing choice, forcing people to buy domestic stuff regardless of how well made it, you are and perpetuating the monopoly of the producer and reducing incentive to improve. We went through that in the 60s and 70s. You are also pushing up costs. Remember a number of goods become input for other goods. If I make shoddy goods, that becomes a shoddy input for another goods that also becomes shoddy. So by forcing people to buy domestic you can perpetuate a culture of shoddiness in the economy. Better to allow competition. If customers want to buy domestic that is their choice, but it should be out of free will rather than government diktat.


Teertha, Greenlawns High School, Breach Candy: Faulty notes are being printed, how does the market get it and why is the value so high?

Raghuram Rajan: Counterfeit notes are printed by people who should not be printing notes. It is being done in a dingy basement somewhere illegally by those who are trying to fool people. Typical notes have security features and when you take your notes to a bank, the bank teller or a machine can separate the bad notes from the good. Then they return the bad notes to us and we give them good notes. That way we try to keep good notes in circulation. Who is doing this? It’s illegal. People do it, we catch them and put them away in jail for a long time. But, some of this does happen. It is not big, the rupee figure may sound big but as a fraction of the total currency, it is not big.


Tanya, Ryan Global School: What gave you an idea to write a non-fiction book, ‘Saving Capitalism from Capitalists?’

Raghuram Rajan: I made a commitment to my daughter to write fiction at some point. ‘Saving Capitalism from the Capitalist’was basically saying that all too often it is not your Marxist, Communist radical flailing against the capital system who is responsible for the capitalist system not working as well as it should. It is the big capitalist –the big bankers or the big industrialists — who finds that once they have made it, it is very convenient to shut down the competition that makes capitalism as vibrant as it is. They look for special favours from the government, they look for tax exemptions, and they look for regulations that keep other people from entering. In a sense, once they have climbed up the ladder they want to pull up the ladder after them to make sure that nobody else climbs. That often is how the capitalist system breaks down rather than because the Marxists from outside are saying ‘bad capitalist’. That was the thesis in our book – in economy after economy, the reason it had become clogged up was because the economy had become dominated by a few who were essentially pulling up the ladder.


Parina Muchchala, Gopi Birla Memorial School: In the past many governors have been hiking rates to combat inflation. Would you be more innovative in your approach?

Raghuram Rajan: We have supply side problems – large projects have been stalled, and also on the food side there are constraints on the distribution of food, which prevent production from being as high as it should be. Those are being addressed. The other reason is too much demand. There are many ways of constraining demand. A tighter fiscal deficit is a way of constraining demand. We think that will happen. Another way to curtail demand is by rising rates. Do we have other tools? I think problems arise when central bankers get overly innovative in the tools they use. I think is better to be boring and do what is conventional because if you try the unconventional you may create a whole set of new problems. As far as growth goes, we are addressing it through a variety of reforms that will make finance more easily available but I don’t think the answer for us on the demand side is doing something different.


Saksham Khaitan, Children’s Academy: How do you plan to integrate urban and rural areas? For instance the withdrawal of the pre-2005 notes, those in the urban areas are aware of it, but how do you plan to achieve it in the rural areas?

Raghuram Rajan: Let me be clear that the withdrawal of the pre-2005 notes is primarily to address the issue of counterfeit notes. The post-2005 notes have better security features and to have notes with improved security features we are withdrawing the earlier notes. Withdrawing of notes is different from de-monetisation. What we are saying is that to the extent you continue to have these notes, it is still money. Five years down the line if somebody finds some pre-2005 notes, that point they can take them to the bank and exchange it. They can also take it to a shopkeeper if he is willing to accept it, he can bring it to the bank.


Manjuka Agarwal, SVKM International School: What attracted you to the economic sector as a child?

Raghuram Rajan: You must all be wondering ‘Why did he pick up such a boring profession’, right? I think one of the things that many of you seem to be very much alive to, are the issues in the country and you must be thinking – there are problems here and there must be a way to solve them. If you are thinking that, you have already started thinking the way I was thinking much later in life. We see a lot of poverty, we see that we are big country but we are not there in the pantheon of nations. How do we make people richer and the country better off? If we start thinking about that, economics is a good profession where some of the answers can be found and you can start devising policies to make a difference. That was really why I went into it. I thought I would have the answer, but as you grow up, you realise things are little more complex and there is no silver bullet and there are a lot of things to be done. Then your job becomes one of trying to preach, of trying to convince other as well as trying to do something yourself. I think it is a very worthwhile profession; we need many more economists in the country.


Anirrudh Keni, Jankidevi High School: Recently you increased repo rate by 25 basis points and I was wondering if you increase interest rates on loans by 0.25% , what are you trying to achieve?

Raghuram Rajan: Since you used jargon, let me explain to those who may not understand – repo rate is the interest rates we set. The higher we move the interest rate; it is as if the less money we print. Not quite the same but think of it the same way. It works in two ways. By keeping the cost of money high, the repo rate has an effect by setting expectations. A lot of what central banks do is managing expectations. If I tell you, I am intent on keeping inflation contained and I will do what it takes, eventually people start to believe it. And as people start to believe it, when they determine prices for what they are selling -goods or labour – they take that into account and moderate their price increase. Initially, we will have more impact on expectation and then later on prices.


Dhruv, Lodha High School: There are situations where a person is making faulty notes and gets the news that you are exchanging pre-2005 notes. So the bank will exchange the faulty note for a new note. So what safety features can be there?

Raghuram Rajan: When people come in with fake notes, if the person at the counter identifies them; they will basically make a note of that. If lots of notes are received on a regular basis then the police will take action. So don’t worry, we are not going to accept a ton of bad notes and give them good notes in return.


Ajeeta Yadav, Mazidun High School, Airoli Navi Mumbai: How can a common man contribute to the development of a country’s economy?

Raghuram Rajan: I think everyone contributes by doing what they can do. Privately it is in terms of doing a good job which in your case is studying, playing hard, being good to your friends. Apart from private roles we also have a role as public minded citizens. Even as you enjoy the rights of your citizenship you also have responsibilities to make sure that democracy works as advertised, to point out the wrong doing that is happening and a responsibility to help those who have fallen behind and for whom there are no government programmes.

Tagged with: , ,
Posted in General, Problems

If not python, then what?

Visitors
  • 29,100 hits
Follow

Get every new post delivered to your Inbox.

Join 236 other followers