Thursday, April 21, 2011

Cold Shooting Through Foot

Generate Excel files with Python


pyExcelerator is a Python module created by Roman V. Kiselyov to read and write data in Excel format. You need a superior to the 2.4 version of python. The advantage (say) to use this module to other as CSV is that it allows unicode formats, reads / writes well in both OpenOffice and Microsoft Office and has a very simple API.


Install module Ubuntu

$ sudo apt-get install python-Excelerator


Basics

Once installed, go back to basics. Begin to write something. Saying that if we unload the module http://sourceforge.net/projects/pyexcelerator/ in it there are many examples that can guide us to what we will do. ____________________________________________



import from pyExcelerator

* # Instance objects
the workbook = Workbook () worksheet = workbook.add_sheet
( "my first sheet" )

# Write a row
worksheet.write ( 1 , 1 , "Example" )
# Save the content
workbook.save ( 'file.xls' ) ______________________________________



What you do is instantiate a workbook and a sheet. We can create as many worksheets as you want. Then write in the position (1.1) Example word and save the name file.xls.


Format

can also write in different fonts, colors, italics , etc. This can be done by the Font class module. With the font, we show you all properties necesarias. 

______________________________________
 
from  pyExcelerator import  *

# Instance the objects
workbook = Workbook()
worksheet = workbook.add_sheet( "my first sheet" )


# Style  

font = Font()
font.name  = "Arial"
font.colour_index = 1
font.bold = True
style = XFStyle()
style.font = font
# Write

worksheet.write ( 1 , 1 , "Example" , style)

# Save the content
workbook.save ( 'file.xls' )

______________________________________

This can also be done on the style object, as used internally Font.


Reading CSV

able to read and process the data, we parse_xls function, which we pass a file and coding, which can be utf-8. This function returns all the leaves worksheet and values, so we have to go and for example, inserted into an array. Listed below are a complete example of how to do this. The following code is an adaptation of the author's code examples directory.


Complete Example ______________________________________

# -*- coding: utf-8 -*-

# This example adapted from WAS Roman V. Kiselyov
# in examples section project

from  pyExcelerator import  *

class   Excel ( object ):
     def   __init__ (self, name_space= '0' ):
        self.column = 0
        self.row = 0
        self.workbook = Workbook()
        self.worksheet = self.workbook.add_sheet(name_space)

     def   write_row (self, content):
        self.column = 0
         for  i in  content:
            self.worksheet.write(self.row, self.column, i)
            self.column += 1
        self.row += 1

     def   write_with_format (self, content, bold= False , name= 'Arial' , colour_index= 4 ):
        font = Font()
        font.name = name
        font.colour_index = colour_index
        font.bold = bold
        style = XFStyle()
        style.font = font
        self.column = 0
         for  i in  content:
            self.worksheet.write(self.row, self.column, i, style)
            self.column += 1
        self.row += 1    

     def   save (self, filename= 'file.xls' ):
        self.workbook.save(filename)

     @ classmethod
     def   read (self, filename, coding= 'utf-8' , verbose= False ):
         for  sheet_name, values in  parse_xls(filename, coding):
            matrix = [[]]
             if  verbose:
                 print   'Sheet = "%s"'  % sheet_name.encode(coding,   'backslashreplace' )
                 print   '----------------'
             for  row_idx, col_idx in   sorted (values.keys()):
                v = values[(row_idx, col_idx)]
                 if   isinstance (v, unicode ):
                    v = v.encode(coding, 'backslashreplace' )
                 else :
                    v = `v`
                v = '%s'  % v.strip()
                last_row, last_col = len (matrix), len (matrix[- 1 ])
                 while  last_row <= row_idx:
                    matrix.extend([[]])
                    last_row = len (matrix)
                 while  last_col < col_idx:
                    matrix[- 1 ].extend([ '' ])
                    last_col = len (matrix[- 1 ])
                matrix[- 1 ].extend([v]    
             if  verbose:
                 for  row in  matrix:
                    csv_row = ', ' .join(row)
                     print  csv_row
         return  matrix

if  __name__ == '__main__' :
     print 'Generating xls ........... ' ,
header = [ ' Name ' , ' Surname ' , ' ID ' ]
excel = Excel ()
excel.write_with_format (header, bold = True )
data = [ u'Tutú ' , u'Tiñi ' , '1239812H ' ]
excel.write_row (data) data =
[ u'Kaká' , u 'Asd' , '8712382H ' ]
excel.write_row (data)
excel.save ()
print 'ok'

print 'Reading data ........... '
Excel.read ( ' file.xls' , verbose = True )
print '................... ok '
______________________________________

This module contains many more things. Formula writing, images, styles, conversion to html, etc. In the examples section of the project can be seen in detail all this.


References
  • pyExcelerator project

Thursday, March 24, 2011

Dressy Dresses And Booties

Schizotypal personality TRANSTRON

It is a mental health condition in which a person has difficulty with interpersonal relationships and disturbances in thought patterns, appearance and behavior.
Causes and risk factors

The exact cause is unknown. It is believed that genes are involved, because this condition is more common in relatives of schizophrenics.

The schizotypal personality disorder should not be confused with schizophrenia. People with this personality disorder may have bizarre beliefs and behaviors, but are not disconnected from reality and usually do not hallucinate.

hallucinations, delusions (fixed beliefs and false) and lost contact with reality are hallmarks of psychosis. People with schizotypal personality disorder generally do not have psychotic symptoms.

Between 30 and 50% of people with schizotypal personality disorder also suffer from major depressive disorder. A second personality disorder, and paranoid personality disorder is also common with this condition.


Symptoms People suffering from schizotypal personality disorder can be very disturbing and odd behavior may resemble that of people with schizophrenia. For example, can also unusual preoccupations and fears, like fear of being monitored by government agencies.

However, it is more common for people with this disorder behave in a slightly strange and have unusual beliefs (aliens, witchcraft, etc..). These They cling so tightly to these beliefs that this prevents them from developing interpersonal relationships.

People with schizotypal personality disorder become disturbed by the difficulty in establishing and maintaining close relationships. This is different from people with schizoid personality disorder, not wishing to engage in interpersonal relationships. Signs and tests


Some of the common signs of schizotypal personality disorder include:


discomfort in social situations Inappropriate displays of feelings of close friends
No Odd behavior or appearance

beliefs, fantasies, or preoccupations


foreign language Treatment

Some people may serve antipsychotic medications. Psychological therapy (psychotherapy) is a large part of treatment. The guidance in social skills can help some people cope with social situations.
Expectations (prognosis)

The schizotypal personality disorder is usually a long-term (chronic). The outcome of treatment varies with the severity of the disorder. Complications


Poor social skills Lack of interpersonal relationships


Call

care Talk to your doctor or a mental health professional if:

have trouble forming and keeping relationships due to unusual beliefs.
suspect that your child may have this problem.



Prevention There is no known prevention. Be aware risks, such as family history of schizophrenia, may allow early diagnosis.

2010 Yamaha Waverunner® Vx110 Deluxe

DEPENDENT PERSONALITY DISORDER

is a long-term condition (chronic) condition in which people depend too much on others to meet their physical and emotional needs.
Causes and risk factors

The dependent personality disorder usually begins in childhood and their causes are unknown. One of the personality disorders more frequent and is equally common in men and women. Symptoms


People with this disorder do not trust their own ability to make decisions. You may be devastated by separation and the loss of someone and can do whatever, even suffering abuse, to stay in a relationship.

symptoms of dependent personality disorder may include:


Avoid being alone avoid personal responsibility
be easily hurt by criticism or disapproval
Focusing too much on the fears of being abandoned
Becoming very passive in interpersonal relationships
Feeling very upset or helpless when relationships end
Having difficulty making decisions without the support of other
Have problems expressing disagreements with others



Signs and tests Like other personality disorders, the dependent personality disorder is diagnosed based on a psychological evaluation as well as the history and severity of symptoms. Treatment


psychological therapy (psychotherapy) is considered the most effective treatment gradually help people with this condition make more independent choices in life. Medication can help treat other conditions such as anxiety or depression.
Expectations (prognosis)

Improvements are usually seen only with long-term therapy. Complications

Alcohol or drug


Depression Increased likelihood of sexual abuse or physical and emotional abuse

Call

care for an appointment with a physician or mental health professional if you or your teenager has symptoms of dependent personality disorder. Alternative Names


personality disorder-type dependent

Lauren London Natural Hair

DISORDER OF DEPRESSION

rastorno avoidant personality
version Print itSend this page to a
amigoCompartir
is a psychiatric condition in which a person has a lifelong pattern of being very shy inadequate, and sensitive to rejection.
Causes factors
risk
Personality disorders are patterns of behavior for life that cause problems in relationships and at work.

Approximately 1% of the population has avoidant personality disorder and occurs equally in men and women. The cause is unknown. Symptoms


People with personality disorders Avoidant can not stop thinking about their own shortcomings and form relationships with others only if they believe they will be rejected. Loss and rejection are so painful that these people prefer to be alone rather than risk trying to connect with others. Signs and tests


disorder A person with avoidant personality may:

Be easily hurt when people are critical or disapproving
Refrain too intimate
be reluctant to engage with people
Avoid activities or occupations that involve contact with others
Be shy in social situations for fear of making a mistake Make
potential difficulties seem worse than they are
maintain the view that it is socially good, which is not as good as other people or that is unattractive



Treatment Antidepressants can often cause people to be less sensitive to rejection. However, psychological therapy (psychotherapy) is considered the most effective treatment for this condition.

Psychodynamic therapy, which helps patients understand their thoughts and feelings, and cognitive behavioral therapy (CBT) can help. Also, a combination of medication and psychotherapy may be more effective than either treatment alone.
Expectations (prognosis)

People with this disorder may develop some ability to relate to others and this can be improved with treatment. Complications


Without treatment, a person with this disorder may become resigned a life characterized by total or near total isolation. They may go on to develop a second psychiatric disorder such as substance abuse or a mood disorder like depression. Call
care

Ask your doctor or psychiatrist if shyness or fear of rejection overwhelms your ability to function in life and in interpersonal relationships. Alternative Names


avoidant personality disorder

Double Rod Curtains Too Short

avoidant personality

Depression can be described as feeling sad, blue, unhappy, depressed or collapsed. Most of us feel this way once in a while for short periods

Clinical depression is a mood disorder in which feelings of sadness, loss, anger, or frustration interfere with everyday life for an extended period of time.

See also: Adolescent depression


Depression among the elderly Depression
more general considerations



Symptoms of depression include:

or irritable mood under constant
Loss of pleasure in usual activities, difficulty falling
sleep or oversleeping
dramatic change in appetite, often with weight gain or loss and fatigue

lack of energy Feelings of worthlessness, self-hate, and inappropriate guilt Extreme difficulty concentrating

agitated or slow physical movement
Inactivity and withdrawal from usual activities, feelings of hopelessness

abandonment Recurrent thoughts of death or suicide

Low self-esteem is common with depression, as well as sudden bursts of anger and lack of pleasure in activities that make you happy, including sex.

is possible that depressed children do not have the classic symptoms of depression in adults. Watch especially for changes in school performance, sleep and behavior. If you think your child might be depressed, it's worth talking to your doctor.

The main types of depression include: Major depression

: must be submitted 5 or more symptoms listed above, for at least two weeks to diagnose this type of depression. Major depression tends to continue for at least 6 months if untreated. (Depression is classified as minor depression if you have fewer than 5 of these symptoms for at least 2 weeks). In other words, minor depression is similar to major depression, except that first only 2 to 4 symptoms.)
Atypical depression: occurs in approximately one third of patients with depression. Symptoms include overeating and oversleeping. These patients tend to have a sense of being weighed down and react strongly to rejection.
Dysthymia: a form of depression usually milder than last years if not treated.

Other common forms of depression include:

Postpartum depression many women feel somewhat down after having a baby, but true postpartum depression is more severe and includes symptoms of major depression.
premenstrual dysphoric disorder (TDP), depressive symptoms occur one week before menstruation and disappear after you menstruate.
Seasonal Affective Disorder (SAD) occurs most frequently during autumn and winter and disappears during the spring and summer, most likely related to lack of sunlight.

Depression can also alternate with mania (known as manic depression or bipolar disorder).

Depression may be more common in women than in men, although this may be because women are more likely to seek help for this problem. Depression is especially common during the teenage years.


Common Causes Depression often runs in families, which may be due to your genes (inherited), learned behavior, or both. Even if your genes make you more prone to depression, a stressful or unhappy life event usually triggers the onset of a depressive episode.

Many factors can cause depression include: Alcohol or drug


situations or stressful life events, such as:
divorce, including parental divorce
death of a friend or family illness in the family

abuse or neglect

job loss social isolation (a common cause of depression in the elderly)
breaking with a boyfriend or girlfriend to lose a subject

ailments and medical treatments as
underactive thyroid (hypothyroidism)
certain cancers

prolonged pain trouble sleeping
steroid medications

Home Care

If you are depressed for two weeks or longer, you should contact the doctor, who can offer treatment options. Regardless of the type and severity of depression, the following self-care steps may help: Sleep well


Eat a nutritious and healthy

Exercise regularly Avoid alcohol, marijuana and other psychoactive drugs
involved in activities that make you happy, even if you feel like it
Spending time with family and friends
If you are a religious or spiritual person, talking to clergy or spiritual advisors who can help give meaning to painful experiences
Consider meditation, tai chi or related activities as ways to relax
Add fatty acids omega-3 diet, which can be obtained in supplements of sale free or eating fish such as tuna, salmon or mackerel

If your depression occurs in autumn or winter, try light therapy using a special lamp that mimics sunlight.

If you have moderate to severe depression, the most effective treatment plan will likely involve a combination of psychotherapy, lifestyle changes and medications.
Call your doctor if

Call your local emergency number (911 in the United States), a national helpline in cases of suicide or go to the nearest emergency room if you have thoughts of harming themselves himself or others.

Call your doctor if:

hear voices that do not exist.
have frequent crying spells with little or no provocation.
have had feelings of depression that disrupt work, school or family for more than two weeks.
have three or more symptoms of depression.
think that one of the medications you are currently taking may be causing depression. However, DO NOT change or stop medications without consulting your doctor. Cree
should reduce the consumption of alcohol, a family member or friend has asked to do so, he feels guilty about the amount of alcohol consumed or alcohol drink first thing in the morning.

What to expect at the doctor's office

It is a complete medical history, a psychiatric interview and a physical examination to try to classify your depression as mild, moderate or severe and to see if there is a treatable underlying cause ( as alcohol abuse or an underactive thyroid). In general, hospitalization is recommended if suicide seems possible.

Expect some exploration of issues and events associated with feelings of depression. The doctor will ask about:

depressive mood and other symptoms (sleep, appetite, concentration, energy).
Possible stressors in life support systems in place.
If you have ever crossed your mind thoughts about ending his life.
consumption of alcohol and drugs and medications you are currently taking, if any.

Treatment varies with the cause and severity of depressive symptoms, as well as her personal preferences. For mild depression, counseling and care measures without medication may be sufficient. The most effective therapy for moderate to severe depression is a combination of antidepressant medication and psychotherapy (counseling).

Your primary care doctor can refer you where a psychiatrist if his depression is moderate to severe or does not improve with initial treatment.

For more information on treatment, see: major depression


Prevention healthy lifestyle habits can help prevent depression or decrease the chances of that happening again. Psychotherapy and antidepressants can reduce the likelihood that you will be depressed again.

Psychotherapy can help in times of grief, stress or discouragement. Family therapy may be particularly important for teens who feel blue. Keep

connections with others is particularly important in preventing depression. Alternative Names


Melancholy, Sadness, Grief, Despair

(ENCYCLOPEDIA MEDLINEPLIUS INFORMATION)

Wednesday, March 9, 2011

Do Herpes Outbreaks Get Worse

Words


I howl at our moon one I love you,
soggy taste of your kisses,
with the fragrance of your body.

I loose in your chest
light, free, without reservation ...
perpetual spring romance.

Unraveling my dreams and
the line with bright colors,
as I wrap them in a passionate journey ...
you.

Sunday, March 6, 2011

Price Of Vodaphone Simcards In India

Python code coverage analysis

A powerful tool that has perl module Devel:: Cover. A module for python equivalent Coverage. Such programs, which makes is a code coverage analysis, it is mainly to test. This is very useful to know if our test of the application covering the entire code (ideally) and if not, how we need to get there, highlighting the parts of code executed and which not.

To install, we get off the sources and compile or use the repository.

$ sudo apt-get install python-coverage

It's very easy to use. The program has a little help:

$ python-coverage help
Coverage.py, version 3.2
Measure, collect, and report on Code Coverage in Python programs.

usage: coverage [options] [args]

Commands:
annotate Annotate source files with execution information.
    combine     Combine a number of data files.
    erase       Erase previously collected coverage data.
    help        Get help on using coverage.py.
    html        Create an HTML report.
    report      Report coverage stats on modules.
    run         Run a Python program and measure code execution.
    xml         Create an XML report of coverage results.

Use "coverage help " for detailed help on any command.
Use "coverage help classic" for help on older command syntax.
For more information, see http://nedbatchelder.com/code/coverage

Reporting

The first thing to do is run the program. This it will do is create a file. Coverage with coverage information.

$ python-coverage run example02.py

To see the results, we use the option to report:

$ python-coverage report - m example02.py Name Stmts Exec

----------------------- Missing Cover example02
------------------ 14 14 100%

Then we can generate the html file:

$ python-coverage-d html coverhtml
coverhtml $ firefox / index.html


Use the API

This does not end here. If you want you can make a program to run the analysis in the program you want and then generate a report.

The API is well explained, and the truth is quite sencillo.Un example: __________________________________________________


   # -*- coding: utf-8 -*-   
import
Coverage cov = coverage.coverage ()
cov.start () def
square (List):
"" "Find the picture of the numbers listed
>>> l = [ 0 , 1 , 2 , 3 ]
>>> square (l)
[0, 1, 4, 9]
"" "
return [n ** 2 for n into list]

def _test ():
imports doctest
doctest.testmod ()

_test ()

cov.stop ()
cov.html_report (directory = 'covhtml' ) _______________________________________________



$ python mycov.py

The program creates a directory covhtml with the results.



References
  • Python-coverage
  • API python-coverage

Monday, February 28, 2011

Costco Brush Set 2010

graphlog extension for Mercurial

I found a very useful extension command line that prints the log with all routes (branchs and clones) for the project has passed. It is placed in extension. Hgrc within our project.

[extensions] =
hgext.graphlog

Now, we use the option of mercurial GLOG:

$ hg @ GLOG
, changeset: 434: d407c539f293
c99
changeset:   433:e31e18f8b57d





Sunday, February 27, 2011

David's Bridal 99 Dollar Gowns Sale

perpetual romance auscentes


I face blank sheets,
half-used pencils and words
tasteless ...

only
gimmicky phrases inside my body bounce
pierce me like bees from within,
but not let you go ...

think and think of you,
laugh and cry my eyes as the flash of your lashes. A gentle touch
sincere
ruffles me up dreams.

And yet ... I leave
words that describe minimally
I feel for you,
Recobeco hide in
rationality that binds me, and not my imagination loose.

Friday, February 25, 2011

Can I Do Exercise If I Have Herpes?

Something about me, a more

Many treatments have been followed in patients with tlp very few that i have to leave this world of self-destruction. have come to take drugs to give them, and if they work, because sometimes you do not know what to do with myself am ellos.Yo tlp and have tried numerous medications with the hope of a miracle (and it's almost like you would call my recovery).
I spent eleven years in a psychiatric lost and without vida.Los meaning to my doctors had me evicted and only expected to stay viva.A over that period of my life I spent in the hospital, I got hurt a lot of veces.Era seems as if he was not improving and that no mi.En to nothing once the injuries were so terrible that they had had to operate and I get an ostomy bag.
I thought nobody cared about me, really gave them was distinta.Segun igual.La to heal my program had to be aware of the damage I was inflicting, its consequences, even if it meant having to get in peligro.Despues Dim finished operation and distressed by the fact that he carried a bag that had my stools reminding me error.Así I spent five years in foul trouble años.Cinco that helped me realize how lucky I was to have a body that had gone on a charm, until I wanted estropeé.adie operator and removes the bag because it did not trust I could go back to relapse in MS lesions.
That makes two final años.Al me off and now I care and I care a whole.
Maybe I have to say that my misery was my salvation, I do not know exactly peroha was used to that now is a person felicidad.Y ABTA for it we

Wednesday, January 26, 2011

Lying Down Makes You More Sick When Throwing Up

is extinguished? Cahuita

Today it rains, there is no money to go for a walk so we have to stay locked and use your imagination to have some fun. There is no doubt going to be late for movies ... we love to stay dormant in front of the screen as we tell stories. Eat rich food we prepare both, cuddles and caresses between and is even more tasty. The weather is cold but the warmth your company comforts me, I adore.

Today was sunny, the sky is beautifully blue, almost cloudless. In the evening you arrive, today is a day to go but neither walks in the mood to do anything. I spent the whole day at the computer doing work and reading for the U, my eyes are tired and sleepy. You come to school, going through the bustle of the city, walking in the sun, to stand in the bus and just want to sleep. The sun will stay there ... outside, together with the beautiful afternoon, today we are not in the mood .




Every other one not, are so
vulnerable.

The happy times are depleted because tiredness
the scares.

is as if a light breeze off
try our sailing slowly.

How Do You Remove Mucus From Babys Throat

Working with branchs in mercurial


One way to work in parallel, several developers are using branchs. In mercurial, other than each have their own clone, it is also possible to have one or more independent branches. The working is as follows:
branch is created:


$ hg branch new_branch
new_branch Where is the name you want to give. To find out which branch we are working, we use the same command without arguments:


$ hg branch

New_branch
Now, the line of work is as shown in the figure below:



The way to work in the branch as if we were in default, with the difference that made the commit and push without affecting the main branch (default). So how we can merge those changes?. We merge from the branch to the new_branch $ hg merge new_branch
default.



down one branch switch between them

If we want to make us a clone

when branches are created, by default we'll leave the default branch. To switch to another branch do the following: -f $ hg branch new_branch


This puts us on the branch you want. Now we need to update to bring us the latest changes:

$ hg update

Similarly, we can switch from one branch to another by these two steps.
Then the normal work:



$ hg ci-m "..."
$ hg pull $ hg push


If we want to bring changes to any branch, we merge with the branch you want:

$ hg branch
new_branch
default $ hg merge

When we want to close down the branch, run the commit of the following:


hg commit $ - close-branch
-m 'Branch closed new_branch'


References A very good tutorial on different ways to work with branchs in mercurial, (one branch is to "physical").
A guide to Branching in Mercurial
http://mercurial.selenic.com/wiki/NamedBranches

Monday, January 17, 2011

What A Mri Is Looking For

Add Django style sheet

To add stylesheets, the directory of images and javascript files so that Django knows where is everything and directions. One way to solve this is: suppose we have the following hierarchy of directories within the main project.


$ tree templates /
templates /

, , :
settings.STATIC_ROOT +' templates / images'
}),
( r'js / (? P \u0026lt;path> .*)$' , 'django.views.static.serve' also we have to include at the beginning of the file urls.py
,
{'DOCUMENT_ROOT'
:
settings.STATIC_ROOT + 'templates / js'
}) _______________________________________________________
the amount needed to use the variable STATIC_ROOT: _______________________________________________________


 
import settings _______________________________________________________
Now we have to define this variable in settings.py . What we do is put as the path to the application: _______________________________________________________
STATIC_ROOT = '/ path / to / app /'
_______________________________________________________ And finally, we need to update the list TEMPLATE_DIRS with the url to the directory template: _______________________________________________________
STATIC_ROOT + 'templates /' , _______________________________________________________
With this, we have all you need to use CSS in your application. When reference is made to pick what style sheet in html, it should point to the root of the template, which would read:
\u0026lt; link
href = " / css / style.css "rel
=" stylesheet "type

=" text / css "

   

/
>

   



References
   
Django-doc



Friday, January 7, 2011

All Black Small Gages

mini-C Parser in Python

I've been learning for some time a module to make the lexer and parser of a compiler in Python. This is a relatively easy tool to use (compared to others like antlr) and very similar in syntax to LEX and YACC. In fact, the name comes from
  Python PLY-Lex-Yacc.      There are many tutorials and examples of this module, so my intention here is not to explain how to use and little else.     install    What We   ply to install the module for Python. This can be done from the Ubuntu repositories or through the tar.gz of the project page.        $ sudo apt-get install python-ply 


lexical analyzer import
as  lex

# list of tokens
tokens = (
    
# Reserverd words
     'ELSE' ,
    
'IF'
,
    
'INT' ,      'RETURN' ,      'WHILE'
,      'VOID'
,
         # Symbols

    
'PLUS'
,      'MINUS'
,
    
'TIMES'
,
       'DIVIDE'  ,        'LESS'  ,       
'LESSEQUAL'
,      'GREATER'
,
     'GREATEREQUAL' ,
     'EQUAL' ,
     'DEQUAL' ,
     'DISTINT' ,
     'SEMICOLON' ,
     'COMMA' ,
     'LPAR' ,

'RPAREN' ,
'LBRACKET' ,
'RBRACKET' ,
'LBLOCK' ,
'RBLOCK' ,
# Others
; 'ID' ,
'NUMBER' ,
)
What's done is make an array of all tokens of the language. In this case has taken a subset of C, which we called cminus.

Now, as expected, there should be regular expressions for all these tokens. One way to do this (this is new from version 3 PLY) take all those tokens only be a sentence and do it directly in the form:
# Regular expressions rules for a simple tokens
t_PLUS = r '\\ +'

t_MINUS = r'-'
t_TIMES = r' \\ * '
t_DIVIDE = r' / '
t_EQUAL =
r '='

t_LESS = r '\u0026lt;'
t_GREATER = r '>'
t_SEMICOLON = ','


t_COMMA = r ' , '

t_LPAREN = r' \\ ('
t_RPAREN =
r '\\)'
   
t_LBRACKET = r '\\ ['
   
t_RBRACKET = r '\\]'
   
t_LBLOCK = r '{'
   
t_RBLOCK = r '}'
   
 For all other tokens, what we do is a function. Note that all the rules begin with t, this is because the module takes everything that contains that t_TOKEN creates the corresponding transition diagram. Some of them are:   
  def  
 t_ELSE  (t):   
r'else'
          
return
    t   
   def   
 
 t_IF  (t):       
r'if'
          
return
    t   
   def   
 
 t_NUMBER  (t):       
r'\d+'
    t.value =
int
(t.value)
    
   return     t       
def  
t_ID (t):      r'\w+(_\d\w)*'
    
return  t
def  
t_newline (t):      r'\n+'
    t.lexer.lineno +=
len (t.value) t_ignore = ' \t
'

def   t_comments (t):
    
r'/*(. t.lexer.lineno + = 1 def
t_error
(t): print " Lexical error: "+

str (t.value [ 0 ]) t.lexer.skip ( 1 )



Parsing Now we give an order to all these tokens that we are coming. This is achieved using a grammar. Specify PLY grammars is very similar to that used in YACC. '''not_terminal: list_of_terminals not_terminals'''
For example,
"" "program: PROGRAM ID SEMICOLON EOF block" "" PLY What does is take the first string in each production analyze and create the parser. For example, some of the production of C-minus are: ______________________________________________________ import
ply.yacc
as yacc from cminus_lexer

import token import  cminus_lexer def
  p_program
(p):     'program : declaration_list'

    pass
def   p_declaration_list_1 (p):     'declaration_list : declaration_list declaration'  

pass


def

 
p_declaration_list_2
(p):
   
'declaration_list : declaration'

   

pass



   def       p_declaration  (p):       
'''declaration : var_declaration                  
pass

def   p_var_declaration_1 (p):
    'var_declaration : type_specifier ID SEMICOLON'
    pass

def   p_var_declaration_2 (p):
    'var_declaration : type_specifier ID LBRACKET NUMBER RBRACKET SEMICOLON'
   
   pass       
   def        p_type_specifier_1  (p):       
'type_specifier : INT'    
pass

def   p_type_specifier_2 (p):    
'type_specifier : VOID'    
pass
def

  p_fun_declaration (p):     'fun_declaration : LPAR ID arRP type_specifier compount_stmt params' pass



def p_empty (p): 'empty' pass



______________________________________________________ Note that nonterminals are in lower case and the terminals are in upper case. This is by convention. In addition, tokens are created above in the lexical analyzer. In the PLY production is necessary to place a fool to do the role of epsilon . (P → epsilon ). This does nothing. This is a parser that simply checks that the syntax is correct, but if it is incorrect, we need to sing the error. We do this by producing p_error ()
. ______________________________________________________
def

p_error (p): if p is

Not  
None
:         print   "Syntax error at line "  + str
(p.lexer.lineno) +  
" Unexpected token  "  + str
(p.value)
      
 else    :            print     "Syntax error at line: " Str + 
(cminus_lexer.lexer.lineno) ______________________________________________________

Once we have all written rules, we call the parser. The first time you run, will build a py file with the parser, called
parsetab.py
and another with the lexical and syntactic information call
parser.out
. ______________________________________________________ parser = yacc.yacc ()
if
  __name__ == '__main__' :   data =   '''     
        // Comment C99 style         int gcd (int u, int v) {             if (v == 0)                 return u  
            else                 return gcd(v, v-u);         }
    '''
   parser.parse (data, tracking = True  ) ______________________________________________________  
To run the program, invoke the parser and it will take the sample code above and you will pass the parser.
cminus_parser.py $ python Syntax error at line 6
 Unexpected token else 


 complete Code 


can see the entire code in the repository: Http://bitbucket.org/jjfumero/cminus The next step is to build the AST. The strategy here is to build as it makes the parser.

References

PLY
Tutorial for a mini-lisp
    

Tuesday, January 4, 2011

Green Green Episode 13 Stream



Glide infinitely
one after another.

play chase,
to break into a whisper of foam
and vanish
between the coral shore.


The sea is like a naughty child,
hug awkwardly trying
and drags me into a gentle sway.

out!
not going to be that the child is besotted
and take you to live with him.