Sunday, June 22, 2014

5 Favorite DevOps Memes

In the DevOps webisphere, there are plenty of blogs, articles, commentary, pundits and ideas floating around to keep you busy until your head explodes. We here at ScriptRock tend to have a somewhat cynical perspective on things because we've spent years trying & failing to 'do DevOps' (by the way.... DevOps is NOT a verb for the good of the order) which is what lead us to creating the company to begin with. Our culture promotes having fun and we try to keep a sense of humor about stuff. We all know that a picture is worth a thousand words, so here are our top 5 favorite internet memes related to DevOps.

DevOps meme - worked fine in Development

 

Screen_Shot_2014-05-02_at_1.58.39_PM

 

DevOps meme - automation

 

DevOps meme - you went full DevOps

 

DevOps meme - say DevOps one more time

 

 

Original :scriptrock.com

Thursday, June 19, 2014

25 Newest Bedrooms That We Are In Love With

Oh designers, what would we do without you? Before we stopped drooling over these 20 gorgeous bedrooms, you have churned out another set that sent us back to dreamland. It is a privilege watching over your work and seeing such creativity on a daily basis. Our kudos to the architectural visualization community!
Not a lot of space to play with but this room uses rich textures and soft feels to create that premium look.
Not a lot of space to play with but this room uses rich textures and soft feels to create that premium look.
bedroom study tv placement

Not sure how many homes would be able to pull this off but boy does it look cool to have a tree near your bed!
Not sure how many homes would be able to pull this off but boy does it look cool to have a tree near your bed!
exposed concrete wall bedroom
It is not easy to pull off black in the bedroom but this would be one way to do it.
It is not easy to pull off black in the bedroom but this would be one way to do it.
The raw look of this loft is tempting. We can imagine an artist living here.
The raw look of this loft is tempting. We can imagine an artist living here.
luxurious bedroom lighting
bedroom plant garden
small bedroom design
large bedroom design
bedroom art design
Lavish natural lighting makes up for the lack of colors in this room.
Lavish natural lighting makes up for the lack of colors in this room.
Take a wild guess as to what this guy must be doing for a living.
Take a wild guess as to what this guy must be doing for a living.
Eke has been a regular these days in our features. One reason we like them so much is that they deal with realistic sized interiors.
Eke has been a regular these days in our features. One reason we like them so much is that they deal with realistic sized interiors.
bedroom flooring and rug
white bedroom study
rustic bedroom design
bedroom luxury look
classy white bedroom design
bedroom wallpaper designs
black and red bedroom
large bedroom furnishing
attic bedroom ideas
Loving the wall art.
Loving the wall art.
minimalist bedroom

If you think these rooms are a little too spacious for you to adapt inspiration from, we recommend you check out our space saving bedrooms post.

Source : home-designing[dot]com

Monday, June 16, 2014

Paid internship ethical or not?

That internship plays an important role in getting a job is known to everyone. But what's new is that students are now paying money to companies to get a first-hand job experience.

 

And those who just want an experience certificate without having to slog, are paying the organisations a sum to get a recommendation letter that they can show during placement interviews.

Paid internship ethical or not?

Paid internship ethical or not?

The era when students used to work hard in companies for an experience certificate is clearly ending. Now, both students and companies have adopted a professional approach, as students are willingly spending a few thousands to be on board a company that teaches them basic work skills for a fee anywhere between `4,000-`6,000.

One might argue the validity of paid internships and whether it serves the right purpose. But organisations say that they put in their time and energy to train a rookie, so the money they charge for it is minimal. According to firms, students are provided with expert guidance and helped with their preparation for placement interviews. For that, charging a basic fee should not be considered unethical. While most students agree to this, there are also some who say that paid internships don't help and it's only a money-making gimmick by companies.

We invest our time and energy, charging a fee is necessary:

 

Organizations

 

Representatives of various government and private sector organisations that provide paid internship say that the fee for students is nominal. Says Ramanathan, additional general manager at BHEL (Bharat Heavy Electricals Limited), Bhopal, "Students are given a training program that lasts for three-four weeks. They are trained in design methodologies, exposure procedure, etc, and the students are charged `500 per week. We give them a certificate at the end of the course. We usually don't give them any live project and they don't contribute to the firm's revenue, so we don't give them stipend. We have to put in a lot of time in training them, and we give them expert guidance that they probably don't get at their colleges. So, it becomes essential for us to charge them a fee."

A thought seconded by GC Pandey, general manager at BSNL, who adds, "We provide a vocational training course to engineering students. They come to us to gain hands-on experience, and we charge them between `6,500-`7,500 for a program that runs for two to four weeks. This program was launched two years back and we run it between April to mid-July. Since then we have been getting a lot of students." Talking about the concept of paid internship, GC Pandey adds, "This program has quite an affordable fee. Moreover, we also run a separate program in which five best students from each college are provided free training. But we can't train everyone for free."

Mahesh Pant, regional manager (trainee) for west at Bosch India, says, "The regular rate for internship at our organization is `750 per day. However, we try and give students as much respite as we can. Like, we charge `3,700 for a six-day program, and a 12-day training with us costs `5,000. Students are guided by experts and complete practical training is provided, which can never be provided free of cost. The organisation can't put in money from its own pocket."

So, do students also get any assistance in placement with companies? To which, Mahesh says, "Once a student is here, we are responsible for clearing their doubts in the subject. We don't provide a job guarantee in our company, but if the student is sincere we guide him/her in their future prospects."

Students approaching consultancy firms for paid internships

Rajesh Sharma*, owner of a consultancy firm, says, "An increasing number of students is opting for paid internship. We get numerous calls from students asking us for companies that are providing internships. They are willing to pay if they get to intern in a company even for a month, and are also ready to pay us in big amounts if we recommend them to a reputed firm. Many private firms have started charging from students for internship."

Akshay Sahu*, a management student at IMS, DAVV, remarks, "My seniors had told me that an internship certificate is important to get selected during placements, so I applied at a company for a month's training. They said that if I wanted to learn, they won't charge anything, but I'll have to work for them seriously for 45 days. And if I just wanted a certificate, they'll issue one for which I'll have to pay `3,000. Mujhe toh sirf certificate chahiye tha, itne din tak wahan roz kaun kaam karta. So, I paid them the amount and got a certificate with a letter of recommendation in marketing. As a bonus, they also suggested me the type of questions employers generally ask and the answers that I should prepare. It worked in my favour as the visiting HRs asked similar questions and I answered them confidently. I got selected with a good package."

So what if we have to pay? we get to learn

Students preparing for their placement interviews say an internship certificate gives them an upper hand among other students, and for that if they have to pay a fee, they're willing to do so. Ruchika Chaurasia, an engineering student, says, "I did my internship at a software company. They charged me `3,000 for teaching me basics of manufacturing industries. It was totally worth it, as I got real work exposure that I wouldn't have got sitting in my college. It also adds to your confidence when you face visiting companies during placement interviews."

Siddharth Randive, another engineering student who recently interned at BHEL, adds, "One of my seniors told me that a public-sector unit in Bhopal is providing internship on weekly chargeable basis. I applied there and paid `3,000 for a two-week training period. It was a learning experience. They gave me an assignment on steam turbine and I was asked to find out ways to increase the efficiency of the turbine and also help them rectify problems in its functioning. Considering the things that I got to learn during my internship, the amount they charged me was negligible. I'm glad I took it up."

Abhishek Agrawal, who is pursuing his diploma at Vaishnav Polytechnic, adds, "I'm an electronics student, and I wanted to intern in my core field. I applied at a national channel to get a first-hand experience of signal transmission. I also paid their internship fee `1,250, which hardly amounts to anything compared to the practical knowledge they gave me. They liked my work, and have told me to apply at their firm once I get my diploma. Mere toh poore paise wasool ho gaye!"

It's a waste of time and money: Displeased students

But not all students who take up these programs are happy. Some of them divulge that often the training given by organisations is not at an advanced level. Sonali Manore, a final-year student at LNCT (Lakshmi Narain College of Technology), rues, "I had paid `2,000 for a one-month training program at a government firm and I was disappointed with the way things were carried out there. There were around 60 students in one batch and apart from a two-day visit to the technical department; we just had to attend lectures. Aadhey se zyaada bachche toh class hi nahi attend karte thay. It was a sheer wastage of time and money. But since a training certificate is important, everyone sat through the entire course."

Sameer, another engineering student at Malwa Institute of Technology (MIT), says, "I had to pay `6,000 for a live project in Java at one of the best firms in the city. Although I got a good training in the subject, I had also expected some placement assistance from them. But that never happened. These days, companies are too professional to give personal attention to a trainee."

Original : indiatimes.com

Thursday, June 12, 2014

Urine: An Ever-Flowing Stream of Fuel Cell Material?

urinating-statue

To most people, urine is a waste fluid that’s promptly flushed away as soon as it’s expelled (unless you abide by the “yellow let it mellow” rule). But to scientists, your pee could be the golden font that advances carbon fuel-cell technology.

Korean scientists have demonstrated that carbon, a precious fuel cell material, can be extracted from dried urine and that it is a powerful conductor of electricity.

The findings, published Monday in Nature, offer an economical way to advance fuel cell technology, and could also improve the environment if deployed on a large scale.

Urine Power

Fuel cells — devices which harvest energy from a chemical reaction — often use platinum as a catalyst, making them expensive to produce. Researchers have been exploring ways to replace the metal with carbon. However carbon nanostructures, created synthetically, can also be quite expensive.

Now researchers from South Korea have proven that equally effective carbon compounds can be extracted from urine — making them a cheap stand-in for platinum or synthetic carbon.

To test the potential of pee, scientists collected urine samples from healthy individuals. Then, they heated individuals’ samples to evaporate the water, leaving behind a dried, yellowish deposit. Next, they super-heated various test samples of dried urine in a range between 700 and 1,000 degrees Celsius for six hours to carbonize the urine.

The heating process caused salts and other elements to gasify and leave behind carbon. Urine is loaded with other elements besides carbon, which makes the leftover carbon highly porous — ideal for fuel cell catalysts. As an added bonus, the gasified salts solidified and clung to the furnace wall after cooling; researchers say it’s possible to harvest these remnants for commercial use as de-icing salts.

Most importantly, the urine carbon was an excellent conductor of electricity, especially the batch that was heated to 1,000 degrees. Researchers said this is the first time carbon was extracted from urine using this simple method.

An Abundant Resource

Roughly 300 to 400 milligrams of urine carbon can be extracted from a single liter of urine, which means a single person can generate up to 0.2 ounces of the fuel catalyst a day. Multiply that by everyone using the restroom at this very moment, and you have yourself an abundant resource.

Researchers said urine could easily be collected at public restrooms and dried outdoors by the sun to create the yellowish powder that starts the process. Where these open fields of urine will reside is another question. But researchers say their findings could help put our waste, which pollutes waterways with phosphates and pharmaceuticals, to good use.

It’s certainly a lot to contemplate for your next trip to the lavatory

Original : discovermagazine.com

Tuesday, June 10, 2014

10 of the most useful cloud databases

IDC predicts that big data is growing at an annual rate of 60% for structured and unstructured data. Businesses need to do something with all that data, and traditionally databases have been the answer. With cloud technology, providers are rolling out more ways to host those databases in the public cloud, freeing users from dedicating their own dedicated hardware to these databases, while providing the ability to scale the databases into large capacities. "This is a really huge market given all the data out there," says Jeff Kelly, a big data expert at research firm Wikibon. "The cloud is going to be the destination for a lot of this big data moving forward."

Some concerns remain for what some call database as a service (DBaaS), specifically around sensitive information being stored in the cloud and around cloud outages. But still, an emerging market of cloud database services and tools seems to be picking up steam. Here, Network World looks at 10 cloud database tools. Some of these are providers of direct relational, SQL or NoSQL databases, while others are niche focused on various open source databases. Please note this list is not meant to be exhaustive, as some big players, like Oracle, HP and EMC/VMware are still rounding out their cloud-based products and strategies for these tools.

Amazon Web Services

Amazon Web Services has a variety of cloud-based database services, including both relational and NoSQL databases. Amazon Relational Database (RDS) run either MySQL, Oracle or SQL Server instances, while Amazon SimpleDB is a schema-less database meant for smaller workloads. On the NoSQL side, Amazon DynamoDB is its solid-state drive (SSD)-backed database that automatically replicates workloads across at least three availability zones. AWS CTO Werner Vogels says DynamoDB is AWS's fastest growing service in AWS history. Amazon also offers a variety of auxiliary data management services, such as its newly announced data warehouse named Redshift, as well as Data Pipeline, which helps users integrate data from multiple sources for easier management.

More information: Amazon Web Services' databases

EnterpriseDB

EnterpriseDB focuses on the open source PostgreSQL databases, but its real claim to fame is its ability to work with Oracle database applications. With EnterpriseDB's Postgres Plus Advanced Server, organizations can use applications written for on-premise Oracle databases through EnterpriseDB, which runs in clouds from Amazon Web Services and HP. It has binary replication and scheduled backups as well.

More information: EnterpriseDB

Garantia Data

Garantia offers a gateway service for users to run open source Redis and Memcached in-memory NoSQL databases services in AWS's public cloud. Using Garantia's software allows for automatic configuration of these open source data platforms by helping developers scale nodes, create clusters and architect for fault tolerance.

More information: Garantia Data

Google Cloud SQL

Google's cloud database service is centered on two major products: Google Cloud SQL, which Google describes as a MySQL-like fully relational database infrastructure, and Google BigQuery, an analysis tool for running queries on large data sets stored in its cloud.

More information: Google cloud databases

Microsoft Azure

Microsoft uses its SQL Server technology to provide a relational database, allowing customers to either access a SQL database on its cloud, or hosted SQL server instances on virtual machines. Microsoft also emphasizes hybrid databases that combine data both on a customer's premise and with the Azure cloud through SQL Data Sync. Microsoft has a cloud-hosted NoSQL database service named Tables as well, while Blobs (binary large object storage), are optimized for media files such as audio and video.

More information: Microsoft Azure

MongoLab

In the NoSQL world, there are a variety of database platforms to choose from, including MongoDB. MongoLab gives users access to MongoDB on a variety of major cloud providers, including AWS, Azure and Joyent. Like other gateway-type services, MongoLab also integrates with various platform as a service (PaaS) tools at the application tier. MongoLab run on either shared or dedicated environments, with the latter being slightly more expensive.

More information: MongoLab

Rackspace

Rackspace's database comes in either a cloud or managed hosted offering via Cloud Databases, which is the name of its product. Rackspace emphasizes the container-basedvirtualization of its Cloud Databases, which it says allow for higher performance of the database service compared to if it was run entirely on virtualized infrastructure. Cloud Databases also incorporates a SAN storage network and it's based on an OpenStack platform. This month, Rackspace announced a NoSQL database in its cloud from provider Cloudant.

More information: Rackspace Cloud Databases

SAP

Enterprise software giant SAP is now playing in the cloud with HANA, a platform built on in-memory technology. Its cloud database from HANA complements the company's other on-premise database tools, including Sybase, and is available in Amazon Web Services' cloud. HANA includes other non-database apps too, including business management tools and application development.

More information: SAP HANA

StormDB

Unlike other databases in the cloud, StormDB runs its fully distributed, relational database on bare-metal servers, meaning there is no virtualization of machines. StormDB officials claim this leads to better performance and easier management because users do not have to choose the size of virtual machine instances their database runs on. Despite running on bare metal, customers do share clusters of servers, although StormDB promises there is isolation among customer databases. StormDB also automatically shards databases in its cloud. The company is currently in a free beta.

More information: StormDB

Xeround

Xeround (pronounced zeh-round) is a management tool for deploying easily scalable MySQL databases across a variety of cloud providers and platforms. Its software allows for high availability and scalability and it works across a variety of cloud providers including AWS, Rackspace, Joyent and HP, as well as on OpenStack and Citrix platforms.

More information: Xeround

Original : networkworld.com

Monday, June 9, 2014

Where can parents find information or support groups for mental illness in children?

American Academy of Child and Adolescent Psychiatry

http://www.aacap.org

American Association of Suicidology

http://www.suicidology.org

1-202-237-2280

American Foundation for Suicide Prevention

http://www.afsp.org

American Psychiatric Association

http://www.psych.org

American Psychological Association

http://helping.apa.org

Autism Society of America

7910 Woodmont Ave. Suite 650

Bethesda, MD 20814

Phone: 301-657-0881 or 800-3AUTISM

Fax: 301-657-0869

http://www.autism-society.org/

Children and Adults with Attention Deficit Hyperactivity Disorder

http://www.chadd.org/

Depression and Related Affective Disorders Association

2330 West Joppa Road, Suite 100

Lutherville, MD 21093

Phone: 410-583-2919

Fax: 410-614-3241

http://www.drada.org

drada@jhmi.edu

FEAT Families for Early Autism Treatment

Lifetime Advocacy Network

National Alliance for the Mentally Ill

2101 Wilson Boulevard Suite 302

Arlington, VA 22201

HelpLine: 800-950-NAMI [6264]

http://www.nami.org/

National Autism Association

20 Alice Agnew Drive

Attleboro Falls, MA 02763

Phone: 877-622-2884

Fax: 774-643-6331

http://nationalautismassociation.org/

National Federation of Families for Children's Mental Health

9605 Medical Center Drive

Rockville, MD 20850

Phone: 240-403-1901

Fax: 240-403-1909

National Society for Children and Adults with Autism

1234 Massachusetts Avenue N.W., Suite 1017

Washington, DC 20005

Phone: 202-783-0125

REFERENCES:

Amr, M., A. El-Mogy, T. Shams, et al. "Efficacy of vitamin C as an adjunct to fluoxetine therapy in pediatric major depressive disorder: a randomized, double-blind, placebo-controlled pilot study."Nutrition Journal 12 (2013).

Antshel, K.M., S.V. Faraone, and M. Gordon. "Cognitive behavioral treatment outcomes in adolescent ADHD." Journal of Attention Disorder May 2012.

Antshel, K.M., T.M. Hargrave, M. Simonescu, P. Kaul, et al. "Advances in understanding and treating ADHD." BMC Medicine 9.72 (2011): 1-12.

Antshel, K.M., T.M. Hargrave, M. Simonescu, P. Kaul, et al. "Advances in understanding and treating ADHD." BMC Medicine 9 (2011): 72-84.

Behrens, D., L.J. Graham, and P.O. Acosta. "Improving Access to children's mental health care: lessons from a study of eleven states." George Washington University March 2013.

Bhatia, S.K., and S.C. Bhatia. "Childhood and adolescent depression." American Family Physician75.1 Jan. 2007: 73-80.

Breslau, J., M. Lane, N. Sampson, and R.C. Kessler. "Mental disorders and subsequent educational attainment in a US national sample." Journal of Psychiatric Research 42 (2008): 708-716.

Briggs-Gowan, M.J., A.S. Carter, J.R. Irwin, et al. "The brief infant-toddler social and emotional assessment: Screening for social-emotional problems and delays in competence." Pediatrics 29.2 (2004): 143-155.

Caspi, A., et al. "Role of genotype in the cycle of violence in maltreated children." Science 297 (2002): 851-854.

Christian, R., L. Saavedra, B.N. Gaynes, et al. "Future Research Needs for First- and Second-Generation Antipsychotics for Children and Young Adults. Future Research Needs Paper No. 13. (Prepared by the RTI-UNC Evidence-based Practice Center under Contract No. 290 2007 10056 I.)" Rockville, MD: Agency for Healthcare Research and Quality; February 2012.

Church, D., M.A. De Asis, and A.J. Brooks. "Brief group intervention using emotional freedom techniques for depression in college students: a randomized controlled trial." Depression Research and Treatment 2012.

Clark, M.S., K.L. Jansen, and J.A. Cloy. "Treatment of childhood and adolescent depression."American Family Physician 85.5. (2012): 442-448.

Copeland, W.E., D. Wolke, A. Angold, and J. Costello. "Adult psychiatric outcomes of bullying and being bullied by peers in childhood and adolescence." Journal of the American Medical Association 70.4 (2013): 419-426.

 

Duckworth, K., D. Gruttadaro, and D. Markay. "A Family Guide: What Families Need to Know About Adolescent Depression, second edition." National Alliance for the Mentally Ill 2010.

Geller, B., R. Tillman, K. Bolhofner, and B. Zimerman. "Child bipolar I disorder: prospective continuity with adult bipolar I disorder; characteristics of second and third episodes; predictors of 8-year outcome." Archives of General Psychiatry 65.10 Oct. 2008: 1125-1153.

Gladstone, T.R.G., W.R. Beardslee, and E.E. O'Connor. "The prevention of adolescent depression."Psychiatric Clinics of North America 34.1 Mar. 2011: 35-52.

Loe, I.M., and H.M. Feldman. "Academic and educational outcomes of children with ADHD." Journal of Pediatric Psychology 32.6 (2007): 643-654.

Merikangas, K.R., J.P. He, D. Brody, et al. "Prevalence and treatment of mental disorders among US children in the 2001-2004 NHANES." Pediatrics 125.1 Jan. 2010: 75-81.

Merikangas, K.R., E.F. Nakamura, and R.C. Kessler. "Epidemiology of mental disorders in children and adolescents." Dialogues in Clinical Neuroscience 11.1 Mar. 2009: 7-20.

Perlmutter, S.J. "Childhood anxiety disorders." Neuropsychopharmacology: The Fifth Generation of Progress (2000).

Ueno, K. "Mental health differences between young adults with and without same-sex contact: a simultaneous examination of underlying mechanisms." Journal of Health and Social Behavior 51.4 Dec. 2010: 391-407.

Woodward, L.J., and D.M. Fergusson. "Life course outcomes of young people with anxiety disorders in adolescence." Journal of the American Academy of Child and Adolescent Psychiatry40.9 (2001): 1086-1093.

Zeigler Dendy, C.A. "ADHD, executive function and school success." Children, Parenting, Students, Teens. July 6, 2012.

Zinn, A., J. Decoursey, R. George, and M. Courtney. A study of placement stability in Illinois. Chapin Hall Center for Children at the University of Chicago. Chicago, IL,  2006.

 

Original : medicinenet.com

 

Wednesday, June 4, 2014

10 Most Common Mistakes that Python Programmers Make

About Python

Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive forRapid Application Development, as well as for use as a scripting or glue language to connect existing components or services. Python supports modules and packages, thereby encouraging program modularity and code reuse.

About this article

Python’s simple, easy-to-learn syntax can mislead Python developers – especially those who are newer to the language – into missing some of its subtleties and underestimating the power of the language.

With that in mind, this article presents a “top 10” list of somewhat subtle, harder-to-catch mistakes that can bite even the most advanced Python developer in the rear.

(Note: This article is intended for a more advanced audience than Common Mistakes of Python Programmers, which is geared more toward those who are newer to the language.)

Common Mistake #1: Misusing expressions as defaults for function arguments

Python allows you to specify that a function argument is optional by providing a default value for it. While this is a great feature of the language, it can lead to some confusion when the default value is mutable. For example, consider this Python function definition:

>>> def foo(bar=[]):        # bar is optional and defaults to [] if not specified
...    bar.append("baz")    # but this line could be problematic, as we'll see...
...    return bar

A common mistake is to think that the optional argument will be set to the specified default expression each time the function is called without supplying a value for the optional argument. In the above code, for example, one might expect that calling foo() repeatedly (i.e., without specifying a bar argument) would always return 'baz', since the assumption would be that each timefoo() is called (without a bar argument specified) bar is set to [] (i.e., a new empty list).

But let’s look at what actually happens when you do this:

>>> foo()
["baz"]
>>> foo()
["baz", "baz"]
>>> foo()
["baz", "baz", "baz"]

Huh? Why did it keep appending the default value of "baz" to an existing list each time foo() was called, rather than creating a new list each time?

The answer is that the default value for a function argument is only evaluated once, at the time that the function is defined. Thus, the bar argument is initialized to its default (i.e., an empty list) only when foo() is first defined, but then calls to foo() (i.e., without a bar argument specified) will continue to use the same list to which bar was originally initialized.

FYI, a common workaround for this is as follows:

>>> def foo(bar=None):
...    if bar is None:# or if not bar:
...        bar = []
...    bar.append("baz")
...    return bar
...
>>> foo()
["baz"]
>>> foo()
["baz"]
>>> foo()
["baz"]

Common Mistake #2: Using class variables incorrectly

Consider the following example:

>>> class A(object):
...     x = 1
...
>>> class B(A):
...     pass
...
>>> class C(A):
...     pass
...
>>> print A.x, B.x, C.x
111

Makes sense.

>>> B.x = 2
>>> print A.x, B.x, C.x
121

Yup, again as expected.

>>> A.x = 3
>>> print A.x, B.x, C.x
323

What the $%#!&?? We only changed A.x. Why did C.x change too?

In Python, class variables are internally handled as dictionaries and follow what is often referred to as Method Resolution Order (MRO). So in the above code, since the attribute x is not found in class C, it will be looked up in its base classes (only A in the above example, although Python supports multiple inheritance). In other words, C doesn’t have its own x property, independent of A. Thus, references to C.x are in fact references to A.x.

Common Mistake #3: Specifying parameters incorrectly for an exception block

Suppose you have the following code:

>>> try:
...     l = ["a", "b"]
...     int(l[2])
... except ValueError, IndexError:  # To catch both exceptions, right?
...     pass
...
Traceback (most recent call last):
 File "", line 3, in
IndexError: list index out of range

The problem here is that the except statement does not take a list of exceptions specified in this manner. Rather, In Python 2.x, the syntax except Exception, e is used to bind the exception to the optional second parameter specified (in this case e), in order to make it available for further inspection. As a result, in the above code, the IndexError exception is not being caught by the except statement; rather, the exception instead ends up being bound to a parameter named IndexError.

The proper way to catch multiple exceptions in an except statement is to specify the first parameter as a tuplecontaining all exceptions to be caught. Also, for maximum portability, use the as keyword, since that syntax is supported by both Python 2 and Python 3:

>>> try:
...     l = ["a", "b"]
...     int(l[2])
... except (ValueError, IndexError) as e:  
...     pass
...
>>>

Common Mistake #4: Misunderstanding Python scope rules

Python scope resolution is based on what is known as the LEGB rule, which is shorthand for Local, Enclosing,Global, Built-in. Seems straightforward enough, right? Well, actually, there are some subtleties to the way this works in Python. Consider the following:

>>> x = 10
>>> def foo():
...     x += 1
...     print x
...
>>> foo()
Traceback (most recent call last):
 File "", line 1, in
 File "", line 2, in foo
UnboundLocalError: local variable 'x' referenced before assignment

What’s the problem?

The above error occurs because, when you make an assignment to a variable in a scope, that variable is automatically considered by Python to be local to that scope and shadows any similarly named variable in any outer scope.

Many are thereby surprised to get an UnboundLocalError in previously working code when it is modified by adding an assignment statement somewhere in the body of a function. (You can read more about this here.)

It is particularly common for this to trip up developers when using lists. Consider the following example:

>>> lst = [1, 2, 3]
>>> def foo1():
...     lst.append(5)   # This works ok...
...
>>> foo1()
>>> lst
[1, 2, 3, 5]

>>> lst = [1, 2, 3]
>>> def foo2():
...     lst += [5]      # ... but this bombs!
...
>>> foo2()
Traceback (most recent call last):
 File "", line 1, in
 File "", line 2, in foo
UnboundLocalError: local variable 'lst' referenced before assignment

Huh? Why did foo2 bomb while foo1 ran fine?

The answer is the same as in the prior example, but is admittedly more subtle. foo1 is not making anassignment to lst, whereas foo2 is. Remembering that lst += [5] is really just shorthand for lst = lst + [5], we see that we are attempting to assign a value to lst (therefore presumed by Python to be in the local scope). However, the value we are looking to assign to lst is based on lst itself (again, now presumed to be in the local scope), which has not yet been defined. Boom.

Editor's note: want posts just like this delivered straight to your inbox? Subscribe below to receive our latest engineering articles.

We will never share your email with any 3rd party or spam you

Common Mistake #5: Modifying a list while iterating over it

The problem with the following code should be fairly obvious:

>>> odd = lambda x : bool(x % 2)
>>> numbers = [n for n in range(10)]
>>> for i in range(len(numbers)):
...     if odd(numbers[i]):
...         del numbers[i]  # BAD: Deleting item from a list while iterating over it
...
Traceback (most recent call last):
   File "", line 2, in
IndexError: list index out of range

Deleting an item from a list or array while iterating over it is a faux pas well known to any experienced software developer. But while the example above may be fairly obvious, even advanced developers can be unintentionally bitten by this in code that is much more complex.

Fortunately, Python incorporates a number of elegant programming paradigms which, when used properly, can result in significantly simplified and streamlined code. A side benefit of this is that simpler code is less likely to be bitten by the accidental-deletion-of-a-list-item-while-iterating-over-it bug. One such paradigm is that of list comprehensions. Moreover, list comprehensions are particularly useful for avoiding this specific problem, as shown by this alternate implementation of the above code which works perfectly:

>>> odd = lambda x : bool(x % 2)
>>> numbers = [n for n in range(10)]
>>> numbers[:] = [n for n in numbers ifnot odd(n)]  # ahh, the beauty of it all
>>> numbers
[0, 2, 4, 6, 8]

Common Mistake #6: Confusing how Python binds variables in closures

Considering the following example:

>>> def create_multipliers():
...     return [lambda x : i * x for i in range(5)]
>>> for multiplier in create_multipliers():
...     print multiplier(2)
...

You might expect the following output:

0
2
4
6
8

But you actually get:

8
8
8
8
8

Surprise!

This happens due to Python’s late binding behavior which says that the values of variables used in closures are looked up at the time the inner function is called. So in the above code, whenever any of the returned functions are called, the value of i is looked up in the surrounding scope at the time it is called (and by then, the loop has completed, so i has already been assigned its final value of 4).

The solution to this is a bit of a hack:

>>> def create_multipliers():
...     return [lambda x, i=i : i * x for i in range(5)]
...
>>> for multiplier in create_multipliers():
...     print multiplier(2)
...
0
2
4
6
8

Voilà! We are taking advantage of default arguments here to generate anonymous functions in order to achieve the desired behavior. Some would call this elegant. Some would call it subtle. Some hate it. But if you’re a Python developer, it’s important to understand in any case.

Common Mistake #7: Creating circular module dependencies

Let’s say you have two files, a.py and b.py, each of which imports the other, as follows:

In a.py:

import b

deff():
   return b.x

print f()

And in b.py:

import a

x = 1

defg():
   print a.f()

First, let’s try importing a.py:

>>> import a
1

Worked just fine. Perhaps that surprises you. After all, we do have a circular import here which presumably should be a problem, shouldn’t it?

The answer is that the mere presence of a circular import is not in and of itself a problem in Python. If a module has already been imported, Python is smart enough not to try to re-import it. However, depending on the point at which each module is attempting to access functions or variables defined in the other, you may indeed run into problems.

So returning to our example, when we imported a.py, it had no problem importing b.py, since b.py does not require anything from a.py to be defined at the time it is imported. The only reference in b.py to a is the call to a.f(). But that call is in g() and nothing in a.py or b.py invokes g(). So life is good.

But what happens if we attempt to import b.py (without having previously imported a.py, that is):

>>> import b
Traceback (most recent call last):
   File "", line 1, in <module>
   File "b.py", line 1, in <module>
   import a
   File "a.py", line 6, in <module>
print f()
   File "a.py", line 4, in f
return b.x
AttributeError: 'module' object has no attribute 'x'

Uh-oh. That’s not good! The problem here is that, in the process of importing b.py, it attempts to import a.py, which in turn calls f(), which attempts to access b.x. But b.x has not yet been defined. Hence the AttributeError exception.

At least one solution to this is quite trivial. Simply modify b.py to import a.pywithing():

x = 1

defg():
   import a# This will be evaluated only when g() is called
   print a.f()

No when we import it, everything is fine:

>>> import b
>>> b.g()
1# Printed a first time since module 'a' calls 'print f()' at the end
1# Printed a second time, this one is our call to'g'

Common Mistake #8: Name clashing with Python Standard Library modules

One of the beauties of Python is the wealth of library modules that it comes with “out of the box”. But as a result, if you’re not consciously avoiding it, it’s not that difficult to run into a name clash between the name of one of your modules and a module with the same name in the standard library that ships with Python (for example, you might have a module named email.py in your code, which would be in conflict with the standard library module of the same name).

This can lead to gnarly problems, such as importing another library which in turns tries to import the Python Standard Library version of a module but, since you have a module with the same name, the other package mistakenly imports your version instead of the one within the Python Standard Library. This is where bad stuff happens.

Care should therefore be exercised to avoid using the same names as those in the Python Standard Library modules. It’s way easier for you to change the name of a module within your package than it is to file a Python Enhancement Proposal (PEP) to request a name change upstream and to try and get that approved.

Common Mistake #9: Failing to address differences between Python 2 and Python 3

Consider the following file foo.py:

import sys

defbar(i):
   if i == 1:
       raise KeyError(1)
   if i == 2:
       raise ValueError(2)

defbad():
   e = None
   try:
       bar(int(sys.argv[1]))
   except KeyError as e:
       print('key error')
   except ValueError as e:
       print('value error')
   print(e)

bad()

On Python 2, this runs fine:

$ python foo.py 1
key error
1
$ python foo.py 2
value error
2

But now let’s give it a whirl on Python 3:

$ python3 foo.py 1
key error
Traceback (most recent call last):
 File "foo.py", line19, in
   bad()
 File "foo.py", line17, in bad
   print(e)
UnboundLocalError: localvariable'e' referenced before assignment

What has just happened here? The “problem” is that, in Python 3, the exception object is not accessible beyond the scope of the except block. (The reason for this is that, otherwise, it would keep a reference cycle with the stack frame in memory until the garbage collector runs and purges the references from memory. More technical detail about this is available here).

One way to avoid this issue is to maintain a reference to the exception object outside the scope of the exceptblock so that it remains accessible. Here’s a version of the previous example that uses this technique, thereby yielding code that is both Python 2 and Python 3 friendly:

import sys

defbar(i):
   if i == 1:
       raise KeyError(1)
   if i == 2:
       raise ValueError(2)

defgood():
   exception = None
   try:
       bar(int(sys.argv[1]))
   except KeyError as e:
       exception = e
       print('key error')
   except ValueError as e:
       exception = e
       print('value error')
   print(exception)

good()

Running this on Py3k:

$ python3 foo.py 1
keyerror
1
$ python3 foo.py 2
value error
2

Yippee!

(Incidentally, our Python Hiring Guide discusses a number of other important differences to be aware of when migrating code from Python 2 to Python 3.)

Common Mistake #10: Misusing the __del__ method

Let’s say you had this in a file called mod.py:

import foo

classBar(object):
      ...
   def__del__(self):
       foo.cleanup(self.myhandle)

And you then tried to do this from another_mod.py:

import mod
mybar = mod.Bar()

You’d get an ugly AttributeError exception.

Why? Because, as reported here, when the interpreter shuts down, the module’s global variables are all set to None. As a result, in the above example, at the point that __del__ is invoked, the name foo has already been set to None.

A solution would be to use atexit.register() instead. That way, when your program is finished executing (when exiting normally, that is), your registered handlers are kicked off before the interpreter is shut down.

With that understanding, a fix for the above mod.py code might then look something like this:

import foo
import atexit

defcleanup(handle):
   foo.cleanup(handle)


classBar(object):
   def__init__(self):
       ...
       atexit.register(cleanup, self.myhandle)

This implementation provides a clean and reliable way of calling any needed cleanup functionality upon normal program termination. Obviously, it’s up to foo.cleanup to decide what to do with the object bound to the name self.myhandle, but you get the idea.

Wrap-up

Python is a powerful and flexible language with many mechanisms and paradigms that can greatly improve productivity. As with any software tool or language, though, having a limited understanding or appreciation of its capabilities can sometimes be more of an impediment than a benefit, leaving one in the proverbial state of “knowing enough to be dangerous”.

Familiarizing oneself with the key nuances of Python, such as (but by no means limited to) the issues raised in this article, will help optimize use of the language while avoiding some of its more common pitfalls.

You might also want to check out our Insider’s Guide to Python Interviewing for suggestions on interview questions that can help identify Python experts.

Original : toptal.com