12 October, 2011

Dehydration

Definition


Its the art of shortening a word on basis of sound.

Description


There are rules for shortening as explained in detail further down in this article, for example, silents are ignored, from consecutive-duplicate consonants only one is taken, inner vowels are removed etc.

Reading them involves some guess work, therefore they are appropriate in short texts only, where due to smaller context guessing is more accurate.

Building Blocks of English Language


Consonants have what we can call "hard sounds", such as "s", "n", "p" etc. Vowels have what we can call "soft sounds", such as "i", "e" "o" etc. None of the consonants or vowels can make a word on its own in english language, they need each other. Consonants make the bases, vowels connect them("soon", "peon", "sin", "sit", "net" etc) or appear as suffix or prefix ("eat", "ant", "emergent" etc).

There are five letters in english language which are always a vowel, and there is "y" which is sometimes vowel and sometimes consonant. For example in "yet", "yellow", "yup" etc "y" is a consonant, and in "party", "symphony", "sybase", "myopia" etc "y" is a vowel.

Other than consonants and vowels there is a third building block of english language, its the "Combination of letters that combiney produce a single sound". Examples are:


  • "tion" as in "station", "mention", "tradition" etc.

  • "sh" as in "sharp", "shave", bushes" etc.



Rules



  1. Remove all vowels that appear in between the consonants in a word.

  2. Keep all those vowels that appear at beginning of word and have sound, such as "art" remains "art", "application" becomes "applctn", "ottoman" becomes "ottmn" etc.

  3. Keep all those vowels that appear at end of word and has a sound, such as "see" remains "see", "happily" becomes "Hply", "attache" becomes "atche" etc. Remove those that don't have sound, such as "sine" becomes "sn", "advocate" becomes "advct" etc.

  4. If there are two consonants or two vowels together that have same sound then keep only one of them, such as "suppress" becomes "sprs", "cinderella" becomes "cndrla" etc.

  5. If a consonant or vowel is silent then remove it.

  6. For combination-of-words that combinely produce a single sound, consider them as made up of letters that can make up that sound, not the actual letters, then apply rules to them. Such as "station" is considered as "stashn" and becomes "stshn", "sharp" becomes "shrp", "tradition" is considered as "tradishn" and becomes "trdshn" etc.



Implementations



advocate advct
advocates advcts
add ad
address adrs (keep one consonant)
bench bnch
button btn
cancel cncl
clear clr
court crt
computerized cmptrzd
code cd
comments cmnts
date dt
data dt
diary dry
download dnld
directory drctry
edit edt
empty empty
error err
file fl
father fthr
general gnrl
hidden hdn
index indx
inner inr
insert insrt
inserted insrtd
info inf
information infrmtn
judgement jdgmnt
last lst
list lst
message msg
mother mthr
notification ntfctn
notify ntfy
name nm
nic nc (nic is an abbrevation)
num nm
number nmbr
old old
order ordr
person prsn
party prty (keeping the ending "y")
release rls
row rw
radio rd
random rndm
stream strm
success scs
specific spcfc
signing sgng
table tbl
text txt
type tp
upload upld
update updt
value vl
year yr
partitioon prtshn
protectorate prtctrt
chair chr


Relation to Programming


I am developing this convention for later use in naming of variables. It would be used in naming local variables, means variables declared inside a function, not the parameter-variables.

Similarities


You have already seen something similar before. In microsoft world, a convention very similar is already in use since decades. Take a look:

button btn
textbox txt
directory dir
information info
calendar cdr
clear clr
screen scr

Although this convention is similary to my dehydration convention, its not the same. Some differences are:


  1. The shortform is sometimes restricted to three characters. In dehydration there is no such limit.

  2. Sometimes the second word is totally absent from the shortform. For example "txt" for textbox. In dehydration it would be "txtbx".


Why this convention



  1. Due to no limit on number of characters the frequency of name-collision is low. Name-collision is when the same shortform refers to multiple longforms.

  2. Its easy to make the sound of the word in mind, that helps in reading.

10 October, 2011

System Complexity

What is a system?

A system is a group of parts that act together to accomplish a common goal.

Examples:



  1. Company made up of employees


  2. Sentence made up of words


  3. Team made up of players


  4. Cloth made up of threads


  5. Organ made up of Cells


Note: A part can be a system itself.


Need of system


Specialization

Some parts can do somethings that other parts cannot.

Example:

It needs so much special skills and experience that a person cannot be a chartered accountant and a nuero surgeon at the same time in one life time. A hospital which needs both, has to hire two different people.


Simultaneity

In some situations, multiple tasks need to be done at the same time to achieve the desired result.
Example:

In an office there has to be a guard that has to keep an eye on the door, exactly at the same time a peon has to make tea, exactly at the same time a clerk has to fill a voucher.


Readiness

Some works need to be done constantly without any break.

Example

The borders of a country need to be guarded constantly without a minute’s break. A part cannot work continuously because after sometime of working the part burns out and needs to be repaired. There has to be shifts.


Advantages of System


Risk Reduction

If a part is in a system, then the chances of damage to that part is greatly reduced, because in case of a problem the other parts can come for rescue.

Example:

A person living in a village has greater chances of surviving an illness or injury or a famine, than a person living alone in a jungle.


Resiliency

Resiliency to the whole group, if one part fails another part can continue providing same services until the first part is repaired or replaced.

Example:

If a farmer has many different types of crops sown simultaneously on different acres, then in case of an infestation some of the crops are likely to be saved. If the farmer has sown only one type of crop, then it would be an all or nothing situation.


Quality


Specialization brings quality in output. Taking advantage of reduction in responsibilities, a part can invest more time in education, and can also narrow down the area of education to know a lot about a very little set of things

Example:

A large corporation is capable of hiring specialized, highly educated personnel with very limited area of responsibility. A small company cannot afford that and have to have mediocre level people where every person wear multiple hats.




Economy


Taking advantage of reduction in responsibilities, a part can choose to do what its best in. Also, since number of duties is decreased, time formerly spent in context-switching, setting-up and moving to new workplace is reduced.

Example:

In an economy where trading is safe and frequent, different regions can afford to grow only those crops that their lands are better in, and rely on other regions to provide other crops they need through trade. A self-sufficient village on the other hand, has to grow all it needs and have to sufferent in quality and quantity as a result.


Power

A group of parts working together has very high chance of defeating an individual part working alone. It is simple power-in-number thing. Also the parts can surround the enemy part and attack all at once instead of a linear one-by-one approach.

Example:

The surrounding thing is the essence of German army technique to win over all Europe except UK in a matter of months. The trick was to always encounter enemy forces in small parts, so though the German army was small in number overall, yet in every battle individually it was in majority. Note that there is no advantage in having more resources if all of those resources cannot be used at once when needed.


Disadvantages of System


Complexity


Complexity is number of connections between parts in a system. If no part of a system has any connection to any other part, then the complexity of the system is exactly zero. It not matter how many parts are there in the system.


The problem with connections is, as number of connections grow, the number of paths also grow.

Defining Paths
A path is a flow of execution.

Example:

The vegetable that reaches my table every day has the following path:

Farm -> Farm Market -> Transport Vehicle -> City Whole Sale Market -> Local Vegetable Shop.


When the complexity grows, the path becomes long and multiple paths come into existence where there was only one part formerly. Let us suppose the farmer now instead of waiting for annual flood, choose to buy artificial fertilizers:

Mine -> Fertilizer Factory -> Transport Vehicle -> Fertilizer Whole Sale Market -> Village Fertilizer Shop -> Farm -> Farm Market -> Transport Vehicle -> City Whole Sale Market -> Local Vegetable Shop

So far, there is only one part though the length of part has increased. The longer the path becomes, more at the ways to short-circuit it to make smaller paths.

Mine -> Fertilizer Factory -> Transport Vehicle -> Fertilizer Whole Sale Market -> Village Fertilizer Shop -> Farm -> Farm Market -> Transport Vehicle -> City Whole Sale Market


Note that in above, some people choose to buy vegetable directly from the wholesale market, therefore a short circuit. The other path still exists where people still buy from local vegetable shop instead of going to the wholesale market. We have two paths now instead of one. It can become more complicated.

Mine -> Farm -> Farm Market -> Transport Vehicle -> City Whole Sale Market -> Local Vegetable Shop


In the above, some of the farmers choose to mine the minerals on their own (or recycle excretions), while other farmers are still buying fertilizers from the market. Therefore a new path is created, and the two existing ones still exists.


Of course some of the farmers may choose to buy directly from wholesale market, in which case we get 4 paths. There are many combinations.


As number of connections between parts of a system grow, the number of paths also grow. Same thing could happen in multiple ways utilizing different flows of execution. The number of words that are needed to explain the system grows. The number of test cases grows. It becomes harder and harder to capture all paths.


To tackle complexity, there has to be a manager. An overriding executer that can initiate, rollback, pause, resume, stop any flow. Flow is when the path is being utilized. Flow is like current, path is like wire.


How to Handle Complexity in a Computer Program


In a computer program there are methods that perform actions. If any method can call any other method then paths increase and so do the complexity. We have to divide methods in two types:



  1. Methods that can call other methods


  2. Methods that cannot call other methods.

The First Type of Methods


These are the paths. When you want to change a path, change the body of this method.

Example:

Suppose the business logic is this:



  1. User input data in a form.


  2. Form is sent to code-behind.


  3. Code-behind validate user input.


  4. Code-behind insert data in database.


  5. Success message is displayed.

What we need to do is make five methods of the second class and call them one by one from the first type of method. The function that validates data cannot for example insert it in database. The function that validates data just return a true/false to the first type of method.


Why use this scheme where methods are divided in two types? Because we can easily change the path, and because we can find out very easily that what is going on.


Let us suppose there is a change in business logic. Now, we have to redirect user to another web-page instead of displaying success message on the same page. How to do it? Very simple, make a new method that redirect user. In the first type of method, replace the call to the method that display success message to the call to the method that redirects


How to Document This?


Use a Sequence Diagram. Sequence Diagram shows the flow. Don’t get yourself confused with the concept of “message passing” and “objects” yet. Just try to make a Sequence Diagram without any object-oriented stuff!


We have to make a separate Sequence Diagram for every functionality. Some of the functionalities are:


  • Customer can add a new order.

  • Customer can view orders.

  • Customer can change an order.

  • Customer can delete an order.

  • A report of orders last year that exceed Rs. 100,000.

  • Audit trailing.

  • Searching in orders.


In an event-driven programming, user can initiate almost any functionality. We have to put the first type of method in the event-handler.


What Architecture This Is Called?


The above scheme is very close to the MVC architecture. In MVC, controller is the logic that controls the workflow i.e. the path. Model and View are not allowed to call each other directly. All interaction between Model and View has to go through the controller. Of course there are variations in MVC which do allow Model and View to call each other directly but that kill the purpose.

Do not think too much about the concept of objects yet. Do not consider Model, View and Controller as objects. Consider them as functions.

Lets give this scheme a name. Lets call it "Director-Actor Procedural Design". Director is the method that calls other methods. Actor is the method that do not call another method but do the work itself.

Director do not do any work. It delegates the work to actors and orchestrate the workings of the actors. It decides whether and when to call who. It also handle exceptions, because it knows what to do, that is, what other method to call in case of an exception. It also allocate and deallocate resources. Actor cannot allocate the resources itself, because the same resource may need to be used by another actor first, for example an actor initializes an object with values and then the new actor uses that object. If the second actor allocate its own resource then it would be a new object which we do not want. Actor cannot deallocate resource because in case of an exception control goes back to the director and then only the director can deallocate the resource.

There are no director-directors, means there is no super director that calls a director. The directors are called asnchronougly by event handlers.

The directors are the effective event handlers, means almost the entire work that need to be done in an event handler is done by a director. There is no logic in the eventhandler except passing the values of related controls to the director, means there is no if-else or loop in eventhandlers. The only work of eventhandler is to call the right director and pass on the values of related controls.

Director is control-type-agnostic, means director don't have to know what controls are displayed to user, be it a group of radio buttons or a drop down list. User can select an option anyway, by checking a radio button, by selecting an option from drop down list or by clicking a button, whatever. Its the work of the form and the event handler in that form to extract the values from the controls and send it to the appropriate director. Therefore, if user interface changes, means your company decide to use a web page instead of a web form for example, you do not need to change the director.

Director is also database-provider-agnostic. It not matter to director whether you are using Sql Server, Oracle, MS Access or even flat file database. The inner workings of database is handled by the stored procedures layer and the calling of those stored procedures is handled by the model layer.


Similarities With MVC


The above do very much look like the MVC pattern. Director is very much same as the Controller in the MVC. The differences are the Controller need not be an object, it could be a method, and, only the directors can call only the actors.


Similarities With Object-Oriented-Programming


The central theme of object-oriented-programming is not to limit who calls who, the central theme of object-oriented programming is what data a function act on, this is called encapsulation. All the other stuff in object-oriented programming is built around this basic concept. Inheritance, and polymorphism are not in their full glow without encapsulation.

The above scheme is based on limiting who calls who. This is independent of what data the functions are acting on. There can even be no data the function is acting on, for example the function is creating a file, or displaying something on screen etc, i.e. there are no variables. The function can be pure, means the function only acts on its input data and not change anything in environment. Means the function don’t change anything in file system, database and network. The above scheme works in all such scenarios.



Back To Ways of Reducing Complexity


A little recap


It was decided to have two types of methods. First one, named Directors, can call other methods. The second one, named Actors, cannot call other methods. It was also decided that the first type would manage the workflow.

We can put a prefix to names of both types of methods. For directors the appropriate prefix is “Handle”, for actors the appropriate prefix is “Do”. So a validation method is called “DoValidation”, an insert method is called “DoInsert”, a file writer method is called “DoWriteFile” etc. The handlers are like these: “HandleSubmit”, “HandlePageLoad”, “HandleCancel”, “HandleRefreshGrid”, “HandleDelete” etc.

So for every desired situation, we have a handler. The handler manages resources and executes operations by asking doers to do what they are supposed to do. A desired situation is an anticipated situation, such as “user clicks on submit button”, “user sends invalid input”, “user wants to load the page” etc. In event-driven programming, an anticipated situation is already associated with an event handler therefore that event-handler would have to call a director.

So, you are a software developer, you can make softwares and websites. A colleague of you in your company is an accountant; he can write vouchers and make ledger entries. Another colleague of you in the same company is a marketer, he can run a media campaign or do a user survey. All three of you are there in the company’s office, sitting idle, waiting for manager to tell you when to work and what to work on. The point is, all three of you are operatives, doers, actors, you do things but you don’t decide when to do it, you also don’t decide what to work on. Your manager should tell you what to do, for example decide whether its a new ERP or a new website. Your manager should tell the accountant in what bank’s what account number he must work on. Your manager should tell the marketer which people to act on and when.

You, your accountant friend and your marketer acquaintance are methods. You take inputs. You cannot order each other to work. You don’t decide when to work. You can't handle unexpected situations on your own, such as a power failure, you have to report back to manager and manager then decide what to do.


We have two sets of synonyms in our scheme:



  1. Directors, Handlers, Managers, Executors.


  2. Actors, Doers, Operatives.


Should A Handler Method Call Another Handler Method


Now it is getting complex. We have only one level of hierarchy uptil now. We have handlers that calls doers and that’s it. No handlers are allowed to call other handlers. The question is, what if a workflow is part of a larger workflow.

Many operations in add and edit are same. In both you have to validate user input. In both you have to show a success message if task is successful, otherwise show an error message.

I do not recommend doing this level of software reusing. Handlers shouldn’t call other handlers, period. It is because to implement this, we have to change body of the operatives. We have to put conditions in operatives to do certain things when called by one handler and do some other things when called by some other handler and do common things when called by any handler. The point of separating the two types of methods is that one is independent of another. If both are dependent on each other then there is no advantage of separation. Infact its not a separation.
The biggest problem in softwares is that things are interrelated. One change in one part results in a lot of changes in other parts. We want to minimize impact of changes. There are ways to do this, such as object-oriented-programming where we can change private methods without any effect outside the object. We can also write automatic testing code to be sure that all effects are accounted for. Still, the essence of problem is not tackled. Object-oriented-programming do not reduce who call who very effectively, a private method can call a method in some other object. Automatic testing can give us extra eyes but it not make the garden greener. Some of the situations can be overlooked in testing.

The real solution is to reduce dependencies. What is dependency? Dependency is when behavior of one thing changes when behavior of another thing changes. For example: virus in my computer effects my productivity because I depend on my computer to do my work, but virus in a doctor’s computer do not effect his productivity because he do not use computer to do his work.

Dependencies in software is the cost of code reuse. When we reuse a method, we call it from more than one places. In most situations, the body of that method has to react differently depending on who is calling it.

The solution is to make one thing independent of another. The other thing would still be dependent on the first one and that is ok, that is code reuse. We have to make two-way dependency one-way. How? Make the actors small. This can only be accomplished if the Single Responsibility Principle is followed at the method level, means one method do exactly one thing.

Example:

Insert and Update:

You have an “insert” operation and an “update” operation. You have to do user-input validation in both cases. The validation operation is same in both cases except that in case of update you have to validate the id of the record. The id of the rercord can be in form of value of an item in drop down list or it can be in a hidden field, whatever. You have to make sure that the Id of record is there and that its numeric and that its non-negative, before you start the update operation.

You should make a method that validates all fields except the id field. Then you should make a separate method that validates only the id field. Now, in the insert workflow, you call only the first method and in update method you call both the methods. As a bonus, you get a ready-made validation function for the delete workflow. Note that in the delete workflow you only have to validate the id.

Create File If Not Exist Then Write In It:

In some situation you have to write in a file if it exists, and if it not exist then create the file first then write in it. These are two separate operations: Create File if not exist, Write in file. There should be two methods.

Allow User to Type Numeric Keys With Or Without Dot:

In a web page this is client-side scripting. You catch the key user pressed, if its not numeric you cancel the event. There can be two situations, one in which user can type an integer only, such as Id of a record, count of something etc, that is, things which cannot be decimal. The other situation is when user can input a decimal, such as price of an item. You want to validate the key in both cases and decide whether to cancel the event.

You should make two methods, one valids numeric keys only without dots, the other validate dot keys only. Then in situation where you need to validate both write something like this:


if(! (DoIsValidNum(txtData.value) DoIsValidDot(txtData.value)))
evt.Cancel = true;
When you validate only numerically then:


if(!DoIsValidNum(txtData.value))


evt.Cancel = true;



Summary




  • Things better exist in a system, than alone. Its good for them (risk-reduction) and for the system(resiliency).


  • There are situations where systems are unavoidable, such as: Specialization, Simultaneity and Readiness.


  • Effectiveness of a system is directly proportional to number of interactions between its parts. Unfortunately, complexity of the system is also proportional to that.


  • There is a way to reduce complexity while keeping effectiveness at the same level. It is to allow only one kind of workers to use other workers.


  • In a computer program:



    • We should have only one type of methods, the Directors, which could call other methods, the Actors, that do things.


    • A Director shouldn't be allowed to call another Director.


    • An Actor should perform only one work.


    • A Director shouldn't do any work, except orchestrating the working of the Actors.


    • Director should decide when and what Actors to call, in what order, what to pass to them and what to do with the returned value.


    • Exception handling should be done by Directors only.



23 September, 2011

Silver Links

The Currency


Traditionally, in asian empires atleast, the unit of currency was one tola silver. Infact the word "rupiya" comes from the hindi word "ropa" which means "silver".

One tola = 11.664 grams

One tola silver = Rs. 1300

One Pound = 454.55 grams = 7000 grains (always of wheat in this article)

One gram = 15.4 grains

One tola = 179.63 grains approx 180 grains



Link to Food


Referring to The Easy Food Article it can be easily noted that price of food for one day per person is equal to 1/10 the price of 1 tola of silver. Ofcourse due to inflation as price of food varies so do the price of silver. So a person needs 3 tola per month for food which is equal to Rs. 3900. It is when the food is purchased in raw form and cooked at home and no labor cost of cooking is included. In case of eating food from a hotel the cost doubles.



Link to Clothing


Lets move on to other calculations. After food ofcourse we should talk about clothing. In Pakistan clothes are cheaper than in most of the world because we have abundant production of cotton. In Pakistan a person can make a suit (shalwar-qameez, the national clothing) in as little as Rs. 650 including the tailor cost. In this calculation its better to take some better quality clothing, so Rs. 1300 is taken as the figure, that is double than average.

A few things need to be explained. Even though a suit can be purchased tailor-made in Rs. 650 in Pakistan, in most of the world it would take double the cost. Therefore we take a figure that can be used in any country of world. Living in a country with abundance of cotton we can have the luxury of wearing better quality clothes in the same price. The suit talked here is for average person, means 4 sq meters of cloth is used. For a grown up man it means 6 sq meters cloth but the Rs. 1300 figure is for the average person. The cloth is of average quality, that is, no designer clothing, no fancy stuff, no expensive embroidery in women clothing etc. Also it should be noted that the intention of the clothing here is to wear it usually at home. Its not specifically party clothing.

The figure above is for the actual suit. Cost of under garments, socks, shoes is not included. I assume that an equal amount should be set aside for it. Ofcourse it takes 50% to 67%, not equal but lets keep some room for some designing, embroidery etc so that party clothes can also be accounted for.

An equal amount, that is Rs. 1300 must also be kept aside for use of clothing that is not wore. It includes bed covers, curtains, cushions etc.

So, how much clothes do a person needs. Having one new suit on every festival, that is on the two eids is two new suits per year. That is the bare minimum before wearing rags. Its better to make 4 new clothes every year, one in every 3 months. Therefore it comes down to Rs. 3900 in every 3 months. The breakup is: Rs. 1300 for suit; Rs. 1300 for undergarments, shoes, socks etc; Rs. 1300 for bedcovers, cushions, curtains etc. It means Rs. 1300 per month or 10 u.
Ofcourse a person can go for 5 or 6 suits per year instead of the calculated 3 by pressing the other amounts. There is room in the other amount to handle this. The other amount s (the Rs. 2600) can be reduced to 75% or even 50% without must damage. Ofcourse instead of increasing the quantity the quality can be increased. The point is, 10 u or 1 tola silver must be set aside per person per month. This ofcourse is for the average person, when taking into account the poors and also the richs and also the middle class.



Link to Services


So, 3 tola silver per month per person for food, 1 tola for clothes, what else? Well we must keep 1 tola aside for services. The services includes barber service, maid service, maintenance service of the locality etc. Children education service is not actually consumed because its an investment for future so not included here. Utility bills are included. Transportation costs are not.



Link to Cash-In-Hand


Another 1 tola must kept aside as cash-in-hand stuff. This is to entertain guests, carry out usual wear and tear of house like plumbing etc and to have some extra food on weekly holidays. Entertainment costs are not included here.



Recap


Altogether, for every person, there has to be 6 tola of silver every month just to carry out the necessities. To account for entertainment, transportation costs 1 tola each must be added. So, 8 tola per month is a good figure. Infact 9 tola per month is a very sufficient amount and can with some difficulty handle the education cost of school going children too.

If there are five members in a family, then the income of family should be 45 tola or Rs. 58,500 per month.



Case Studies


Lets study some usual cases. A salary of Rs. 10,000 for a family of 5 or even 4 is so less that there is no way a house can be run in that. Infact the salary of labor is set to Rs. 300 per day at minimum by govt. In such families there are usually two incomes because women have to work too. Altogether the income not doubles because women are paid less so its like 15,000 to 18,000. Its 12 to 14 tola. That comes out to 2 or 3 tola per person. That can either fulfill food requirement or not even that. Such families have to either consume less quality food or let go some of the nutrition or take some kind of help. Consuming less quality food is ok as long as person is healthy and young but can be problematic for ill or old people. Less quality food is usually half the price of average quality food accounted in the above calculation. Some of the nutrition can be let go for some months but in longer durations it results in complex health problems. Taking help from outside is an option, for example maids and watchmen do take food from houses of their masters.
For a living without outside help and with sustainable health condition in long term, the bare minimum lies somewhere between 4 and 5 tola. There is no room left for entertainment and parties though. 4.5 tola means Rs. 5850 per person, so for a family of 5 it means Rs. 29,250. Infact no family of 4 today can live in any amount less than Rs. 20,000 (approx 16 tola).



The Pressing


How much can we press it? By taking out honey and dry fruits and some other expensive stuff we can reduce the food cost to 2 tola. The quality of remaining food is maintained but not all nutrients are achieved. Today some vitamin pills can be taken at cheaper cost than taking the vitamins from food, so 2 tola is a doable thing. It not go less than 2 tola no matter how you arrange it. The clothing can be easily reduced to half but not any more than that as long as the person still go to work and have some social life. So, 2 tola for food and half tola for clothing. Utility bills must be paid and its not easy to cut one’s own hairs, also some kind of transportation to and from work have to be there. Whatever we do, 1.5 tola have to be there for the combined services and transportation cost. So, 2 tola for food, half tola for clothing, 1.5 tola for utility bills and transportation costs. 4 tola is really the bare minimum. It can very easily slip to 4.5 tola if some guests come or person miss a bus or some essential crockery is broken. Actually 4.5 tola is what it would actually be though the theoretical amount is still 4.5 tola. In a family of 4, that means Rs. 23,400. If a family near you claims to live in less than that then please note that there have to be some costs that are shifted elsewhere, may be the family is getting clothes in gifts, or the utility costs are in some way reduced or there is some hidden help or a secret but small extra income.



Note: This article was written using prices in Pakistani rupees in Karachi as of 23rd Sep 2010.

Per Person Per Day Food Requirement - The Easy Version

The mass taken in the following calculation is 50 kg per person. This is the average mass of population when taking into account the entire population including men, women and children. Mass of a grown up man is 75 kg on average, of a grown up woman is 62.5 kg.

40 calories per kg body-weight per day is for average work. Farming requires 50 calories and office work 30. At the two extreme ends, an athlete requires 60 and a person in comma 20.

Food has macro nutrients, micro nutrients, fiber, water. This is the water present inside the food itself i.e. not the water drunk separately. Usually 10 to 20 percent of food by mass is fiber and an equal amount is water.

Per day per person, macro nutrients are consumed in grams, micro nutrients in micro or milli grams, fiber in grams, water in grams.

The three macro nutrients are carbohydrates, proteins, fats. The two micro nutrients are vitamins, minerals.

Calories come from macro nutrients only. Micro nutrients are used for repairing of body. Fiber is used for diluting the food so that it can be digested easily. Water is used for cleaning and cooling.

Even though all macro nutrients provide energy, not all of the macro nutrients are used for the actual physical work of body. Only energy from carbohydrates is used for actual physical work. Energy from proteins is used only if energy from carbohydrates is not enough; usually proteins are used for providing the stuff that repairs the body. Fats are used as an energy reserve and to make the fats layer below the skin, this layer kills most of the germs and viruses that tries to penetrate the body and keep body warm. Vitamins act as catalysts. Nutrients are also used as stuff to repair the body along with proteins.

In spite of energy used for physical work comes from carbohydrates and not from proteins or fats, since they are also needed therefore in calculation of food requirements they are also calculated, so the following calculation is valid and highly applicable.

One calorie is 4.2 joules. One Calorie (with capital c) is 1000 calories. In food calculations calories is always Calories. Therefore, in this article wherever (other than this paragraph) calorie is written with small c or capital c it means the larger unit, the Calorie. One calorie is the amount of energy needed to raise temperature of 1 gram of water 1 degree Celsius. One Calorie is the amount of energy needed to raise temperature of 1 kg of water 1 degree Celsius.

Carbohydrates would be referred as CH, proteins as P, fats as F in the charts below.

Ideal Proportion of Calories from Macro Sources:


CH: 56% = 1120 calories = 280 grams (4.0 calories / gram).
P: 14% = 280 calories = 70 grams (4.0 calories / gram).
F: 30% = 600 calories = 65 grams (9.2 calories / gram).

Total: 100% = 2000 calories



Item Grams CH P F Calories Rs/Kg Rs

Fruit 250 31.25 - - 125 90 22.50
Milk 250 12.20 8.30 9.10 167 66 16.50
Wheat 125 83.33 15.00 3.44 425 38 4.75
Oats 63 33.50 5.00 - 154 68 4.25
Rice 63 43.75 6.25 2.72 225 130 8.13
Pulses 63 31.25 15.63 4.08 225 100 6.25
Chicken 16 - 3.91 0.20 18 250 3.91
Fish 16 - 2.81 - 11 250 3.91
Mutton 16 - 3.91 0.20 18 400 6.25
Beef 16 - 12.50 - 50 300 4.69
Oil 31 - - 31.25 288 130 4.16
Sugar 8 7.81 - - 31 130 1.01
Honey 8 6.25 - - 25 1040 8.13
Butter 8 - - 6.25 58 350 2.73
Dry Fruits 8 - 1.56 3.90 42 1040 8.13
Spices 31 15.63 6.25 3.13 116 100 3.13

Total 969 265 81 64 1976 104.27
54% 16% 30%


All minerals needed by body can be achieved by above mentioned honey. Vitamins can also be achieved from the above mentioned items. Fiber and water are present in all of the above items except oil and sugar. Fiber and water are not present in oil and sugar because both of them have 100% place occupied by one or more macro nutrients.

Amount:


The amount calculated above is Rs. 104.265. It should be noted that the calculation in case of fruits and meat is for the actual thing, not for the shells and seeds and bones etc. It should be noted that the food purchased from market has about one third of such stuff. Therefore in case of fruits an addition of Rs. 11.25 must be taken into account because fruits must be bought 375 grams instead of 250 grams. In case of meat the majority of non-eaten stuff is bones and there is some fat still present when the food reaches the table. We can take a ballpark figure of one third there too. Total amount estimated for meat is Rs. 18.76 therefore Rs. 9.38 must be added because instead of 62.5 grams 93.75 grams meat must be purchased. Total additions therefore is Rs. 11.25 + Rs. 9.38 = Rs. 20.63. The final amount therefore becomes Rs. 104.265 + Rs. 20.63 = Rs. 125.

Note: This article was written using prices in Pakistani rupees in Karachi as of 23rd Sep 2010.

13 June, 2011

Optimum Resiliency

This post is about the optimum point of resiliency, in terms of redundancy. These are three concepts in the first line, let me explain them one by one:

(1) Resiliency: Resiliency is the ability of a system to handle problems while operating normally or near-normally. Its the extend to which the system can pass through unexpected and rare but huge problems, intact. A normal repairing system for normal day-to-day issues-solving is some other kind of resiliency I am not talking here. I am talking about surviving through problems when the problems hit all of a sudden and there is no time of repairing. I am talking about the first-class set of problem, the huge ones, the rare ones, like earth quakes, country breaking up in parts, tsunamis, even nuclear attacks. These kinds of problems are very rare to occur but they do occur, even nuclear bombs have been already used twice. Since these huge problems are very rare in occurance people tends to set aside little resources for them and when these problems occur entire systems simply wipes out.

(2) Optimum Point: Optimum in the sense of economics. Sure you can build very resilient systems (factories, companies, political parties, countries etc) if you not have to worry about economics but in real world financial laws must be obeyed.

(3) Redundancy: Redundancy is setting aside extra sub-systems to be replaced when a working sub-system fails. As long as the working sub-system don't fail, the redundant sub-system would sit idle. One very simple way to achieve resiliency is through redundancy. There are other ways too, like making strong systems but today I want to talk about only that kind of resiliency that is due to redundancy.

In natural world we see resiliency every where. In our bodies there are two eyes for example while one is enough for day to day operations. In a family there is a father and a mother, even though for most part only one is enough. In water supply we have rain water, river water, ground water etc. In a govt we have district, provincial and federal. In armed forces we have army, rangers, police. Multiple engines in an aircraft. Multiple types of food categories for each component of food, for example for carbohydrates we have grains, fruits, honey, sugar, vegetables etc, for proteins we have meat, pulses, egg, milk etc. Multiple items of food in each food category, for example multiples types of grains such as rice, wheat etc in grains.

One important thing that we must note about resiliency is that the redundant sub-system can readily work in the place of failed sub-system without any modification of the redundant sub-system, means it should be mission-ready all the type, we can't afford any adjusting time.

Another thing to note is that its always a sub-system that is redundant, not the entire system. Its because in middle of operation its hard enough to switch on a new sub-system and sometimes we can't simply jump to a new system altogether, for example, in middle of flight, if one engine fails, we can switch on another engine, but shifting to another aircraft altogether is pretty hard. Same way its hard enough to dig a well for water if a canal from a river fails and its near-to-impossible level of hard to squeeze water out of stored grains or leaves.

Another thing to consider is that, there are levels of redundancy even in sub-systems' level of redundancy. There is a primary redundancy, which can be switched on right away and start working and then there is a secondary level of redundancy that need adjustment to get switched on and start working. For example, in a family, a mother can replace most operations of a father, but an elder sister need some time to perform functions of a mother. Squeezing water out of grains or leaves or milk can be considered a secondary level of redundancy. In wartime, women can be sent to fight at extreme situations but requires deep training and mental adjustment.

So, what is the optimum level of redundancy? Before that, we must find out what is the minimum acceptable level of redundancy. In my opinion, its a factor of two for primary resiliency. We see that everywhere in nature: mother-father as engine of family, two eyes, rain water - canal water etc. Its like flying a two-engine aircraft, would you feel safe in that? The answer is, it depends on the environment in which you are flying. In clear sky, low altitude and peace time you may be confident but to be a bomber pilot in a night air raid on enemy's capital you better have a four engine plane. So, in my opinion, the maximum level of primary level redundancy in sub-system that you should be asking for is 4 and you should be happy at level 2 for all but extreme situations.

Understanding secondary level of redundancy, we may say that its those sub-systems that cannot perform for that role in normal situations but have potential to be transformed to perform at that role. For example, a toy factory in 1942's stalingrad was not intended to work as a weapons factory, but in the heat of world war 2's invasion of germans it was quickly transformed in a tanks factory and worked in that role till the end of war. It may also be considered as the role of a deputy, a deputy has potential to work as the officer but in normal situations it should not, only once the officer becomes unavailable (due to death, injury, missingness or retirement) that the deputy should start operating as the officer.

So, how much redundancy is optimum at secondary level? I think its a strict 2. Having 2 deputies is good enough. In normal situations, having one deputy is enough, its like having 2 redundant sub-systems at primary level. In extreme situations, having two deputies is optimum and enough, its like having 4 redundant sub-systems at primary level. Lets look to nature for some lessons, there are two eyes while one is enough, so there is a primary-level redundancy of 2. There are also two ears that can work somewhat like eyes, so there is a secondary-level redundancy of 1. Note that I didn't said secondary-level redundancy of 2 though there are two ears. Its because I am using cumulative in multiplication sense here, there are two ears but I am comparing them with two eyes as I have already taken in consideration primary-level redundancy of 2. Also note that the nearest physical sensory organ to eye is ear and the next nearest is too far to be considered.

So, what we learned today? Let me summarize. Other than the basic concepts and definitions, we learned that there are classes of redundancy, lowest is the economy class, then there is a crisis class and then there is a luxury class. When there is no class there is no redundancy but there can still be time-consuming repairing. So, the first line of defense is normal repairing, this solves out day to day expected problems but requires downtime and reduction in operations for the time the repairing is take place. An example for a natural system is an eye, lets suppose there is only one eye in a human being. From time to time, this eye requires repairing, for example when it gets red from over work, or when it gets a minor disease or when some dust gets in it. An example from humans is like keeping a guard, lets suppose we need guard only 8 hours a day. Even for that time we can't expect our guard to be available every day of year. He may get sick and requires downtime to get repaired. We can expect maximum 75% availability. Why 75%? Well 365 days a year, 15 dayz gazetted holidays, 350 days means 50 weeks, one off day per week, 300 days, 30 days of casual leaves, 270 working day is like 75% of 365.

Moving forward, we can have an extra guard or an extra eye. I am not saying that the new guard work in some other duty time of day than the first guard. I am saying that the new guard is available only at the duty time when the first guard is already available so we have a redundancy. This is primary-level redundancy of 2, I call it economy class of redundancy. This works great as long as there is no crisis like a war time or dust storm or frequent robberies. The combined downtime of the two sub-systems now reduce to perhaps 1/16 of the total time, that is instead of 25% off-days of the single guard, we get 25% of 25% off-days of the entire team of guards. Why 1/16, lets get that mathematically:

Suppose we have a system of two balls, one small (lets say a tennis ball) and one large (lets say a football). Obviously these two represents the two sub-systems, the two guards or the two eyes. Now, lets suppose each of these balls can be of any of the four colors. Lets take any four colors, for example RED, GREEN, BLUE, YELLOW. Ok, now lets suppose that one of these colors represents downtime and the other three represents available-to-work time. I would take YELLOW as a symbol of downtime. Now lets suppose that on any given day, the probability of downtime is same as the probability at any other day of the year.

To start the experiment, lets put a large number of balls of each type and color in an opaque bag. Lets suppose we have 1000 balls and the probability of getting each type of ball and each color of ball is same. Now lets draw two balls, one after another. What is the probability of getting both balls of YELLOW color? Since the two experiments involve different types of balls (tennis and football) the experiments are mutually exclusive. To draw one ball of any given color when total number of colors for the ball is 4, the probability is 1/4. To draw two balls of the same color, the probability is 1/4 x 1/4 in a mutually exclusive system, that is 1/16. Its equal to a downtime of 365/16 = 23 days per year. Large but manageable.

Note that we are calculating the effect on downtime by considering primary-level redundancy alone. We are not considering the effect of secondary-level redundancy. We should not depend on the secondary-level of redundancy in our calculations.

The next class of redundancy is the crisis class, specially designed to handle crisis. Its having 4 redundant sub-systems at primary-level when only one is needed. Its why there are 4 engines in a passenger aircraft and in a bomber plane. The downtime is reduced to 1/4 x 1/4 x 1/4 x 1/4 = 1/256 or 0.4% approx. Though we are considering resiliency-through-redundancy it should be noted that we not need to have 4 redundant systems to get same level of downtime. We can alternatively make our sub-systems extra strong to endure twice as much pressure as considered normal.

The next class of redundancy is the luxury level. Its to have extreme mental peace. Its having 16 redundant primary-level sub-systems when only one is needed. Such a level of redundancy is very, very rarely seen in man-made systems and never seen in natural systems. Having such a system, the downtime is reduced to 1/256 x 1/256 x 1/256 x 1/256 = 1/65536 x 1/65536 or 1 in 16 million. Such a level of redundancy is needed when we are making a starship that has to travel for lets say 30 years before reaching the nearest non-solar star alpha centauri 4.2 light years away.

So, what level of resiliency is recommended for human-made systems? I think we should consider two ways: resiliency through quality and resiliency through redundancy. I have talked enough about resiliency through redundancy and conclusion for that is, either 2 or 4. 2 is enough and another 2 on the secondary-level. I must make my point clearer.

All in all, there are four ways to get resiliency:

(1) Repairability: There should be an abundance of spare parts and repair mechanisms must be automatic and in place. Simply said, the system must be able to make parts needed for repair on the fly. At this level, a supply of twice as many spare parts should be present as currently in active use in system.

(2) Quality: The next level of defense is quality. Only those things should be taken that are of the best quality. In the quality calculations, half of the stuff made is of average quality, quarter is of worse quality and quarter is of best quality in the three categories discussed. The best quality stuff is usually twice as expensive as the average quality stuff and four times as expensive as the worse quality stuff. This can be easily seen in food, best quality stuff is tastier, larger and more colorful. Here the cost is twice than it would be if average quality stuff is taken. Consequently, average life would be double than average. Also power output would be double, its like running a car on petrol than on cng.

(3) Redundancy: Keep 2 sub-systems of every sub-system instead of one.

(4) System: Keeping an entire system redundant. Its important when for example we are going on for war, we must never engage more than one half of our forces in offense because we don't know what level of counter-offense enemy would do. We must keep an extra working space-craft for every space-craft we send in space.