Custom Table View Cell using Interface Builder with RubyMotion

custom-cell-sample-app

I’m a RubyMotion newbie and I wanted to create a custom table view cell which simply had three labels – a title, a subtitle and a third label on the right side of the cell. I found a few help around for creating custom table view cell programmatically, which helped me do the job, but it didn’t look as nice as I wanted. Moreover, the benefits of using Interface Builder to easily layout and style the labels was something I was looking for. Fortunately, I was able to get around it myself after fiddling about it. Thought I’d share it for those who are looking for similar.

This post assumes you already have a table view controller in your project to which you want to add a custom table view cell. So I won’t go into much detail of adding them.

I use ib gem to use Interface Builder with RubyMotion. If you don’t, I highly recommend you do. My aim is to add a custom cell with three labels inside a table view controller, call it BooksController.

Create the table view controller

Create the table view cell class

Build the interface

Now, open Interface Builder using the rake ib command in Terminal from the root of your project. The ib gem will automatically create the appropriate interfaces and properties for you to be used inside IB.

Set Custom class for the table view controller in IB

Assuming you have a table view controller added to your storyboard, choose the table view controller and open Identity inspector on the right. Set the class to your controller name – “BooksController” for me.

Set datasource and delegate of the table view controller

Perhaps this is already done for you or drag them from Outlets inspector to the controller itself.

Set Custom class for cell

Now choose the table view cell on the storyboard and set the class to the class you created – CustomBookCell in my case.

Set Identifier for cell

In the Attributes inspector, set the Identifier of the cell to the identifier you specified in the code – BookCell for me.

Set tableview cell Style to Custom

In the Identity inspector, set the Style to Custom from the drop down.

Add three Labels to cell

Now add the three labels we need on the cell by dragging them from the Object library.

Style the labels as necessary

Feel free to make them look good.

Add auto layout constraints

Once the labels are in place, it is a good idea to set the auto layout constraints. This is easy as pie with IB and another great reason to use IB. Simply select the three labels together and choose from menu Editor -> Resolve Auto Layout Issues -> Reset to Suggested Constraints.

Drag outlets from Connections inspector to the labels as required

Finally, open Connections inspector and now you should see the outlets you created in your custom cell class under Outlets. Drag them to their respective labels.

Save and quit Interface Builder and fire up the app in simulator. You should now see the table view with your custom cell.

A sample app for this is available on Github.

PyCon India 2014 – Days of Future Past

Banglore cantonment station was busy as usual, Taxi wala blocking passengers with their offers. People running away not to get caught in their trap. Sreekanth, Tevin, Nidhin with me trying best for a taxi and a good bargain. Even though we were tired of the eight hour journey in an over cooled AC coach. Nuventure had already arranged all the facilities for the python team to attend the conference. Unfortunately VC and Joju had to face unpredicted issues and back out from the journey.

Train was late for 40 minutes. We had to reach Nimhans Conventional Center in 20 minutes fighting with the heavy morning traffic. Nidhin and me got our workshops scheduled to start at 9:30.

We were impatient whenever we got blocked at red light. Our driver completed the ‘Voyage’ in 40 minutes and we are at Nimhans. Me and Nidhin rocketed to the workshop Auditorium, missing breakfast. Quickly finishing up the check in formalities of event. We went to concerned auditoriums for our sessions.

Day 1

Writing security tools in python by Yashin Mehaboobe was the first session I was running for. Passion for computer security was inside me when I first breached my home computer’s bios password, locked by my elder brother, using Kobian motherboard’s keyboard based bios restoring in 2001.

Yashin could explain situations where we need to write our own tools while many third party or ready made are available. Basic security tasks like Port Scanning, Socket programming, Banner Finger printing, Brute forcing passwords, Packet Crafting, Packet spoofing, Packet Sniffing etc were covered in the session. He showed us how powerful libraries like KeyCzar, impacket help hackers do their jobs.

Extracting EXIF data using Pillow library was very easy. He quickly covered some basic data mining/scrapping with BeautifulSoup and lxml libraries, How Py2Exe, Py2Elf libraries help to pack executable files as single binaries. The session was simple even a python beginner could follow the content.

When I came out of the session, I could find Nidhin, discussing with an enthusiastic college boy at the nearest stall, the details of workshop, Scrape Anything, he attended. Sreekanth and Tevin had already moved to the hotel after finishing up the Registration procedure.

We chatted for some time about our sessions and moved to food corner, where PyCon organizers arranged delicious Vegetarian food. We had some dosas and various side dishes. (Trust me I don’t remember food names much).

The conference along with Workshops were zipped in three days. All the workshops were scheduled on 27th. Two auditoriums were occupied with workshops running parallel. Conference and speeches were programmed on 28th and 29th. Finishing the food, we roamed around the stalls. Most of the stalls were getting ready for the Conference, expected to start next day.

I got back to the venue after my Friday Prayer. Nimhans’s lobby getting filled with Pythonista’s all around the globe. Next workshop was scheduled at 4:30, and I got plenty of time to explore the Convention Center. Situated at the heart of Banglore, Nimhans CC has been venue for many open source conferences and events.

Ben Postlethwaite and Alex Vados from Plotly were setting up their kiosk. I had used plotly graphs for some of my projects, Plotly draws cooler interactive graph for the input data provided. Very much helpful for BigData fans. Inquired more about Javascript based graph plotting options and issues I had faced, Ben showed me some of the upcoming features of Plotly on his Vagrant development environment.

My mobile had already drained off and Mac book pro running with 10% power. Wandering along the venue for a power socket, I met Pratyush Who has been working as a Chartered Accountant and spending his life as a pythonista. Hardcore fan of Django, founder of Screener.in, helping many investors for their investment options. He explained me differences between Fundamental investment and Technical investment and how some guys use best of both. Also showed me a nice Firefox plugin Vimperator for making the browser to Vi compatible interface. I gave some instructions, cloud options and async libraries for the scalability of screener project.

I was amazed when two kids around 11 and 9 ages talking to people about pygame and their adventures at the lobby while waiting for the charging to get completed. The alarm @ 16:30 woke me up and I had to attend the Test your webapp with Selenium session.

Anisha Narang’s session was a real workshop. We had a partial code to download and test the webapp, Coding along with many others in the flow. Many volunteers to help out if anyone got blocked in the middle. Even though I had heard the word selenium many times, I haven’t tried it till the conference. Using selenium is very efficient to do Single Page or Multipage web application functionality testing.

I had written many unittests for API’s at Nuventure as part of our test driven development, using python libraries like re, unittests, BeautifulSoup and lxml. But haven’t tested UI functionality via full automated way. Anisha showed us how pyselenium is so handy to test webapps functionality with Firefox, Chrome Browser or Headless one. The workshop showed how effectively we could Emulate Button click or key press and run the web application on intended flow.

I met Baiju Muthukadan who is an active FOSS activist and open source contributor. He explained me how object oriented programming could be used to extend pyselenium’s functionality, and why ‘Go’ language is gaining popularity with its inbuilt concurrency and increased performance. We had a chitchat about how Grunt, Gulp, Jenkins, Ansible affect the productivity and automation. Talked a little about private clouds and architecture of applications.

Sreekanth and Tevin was at a session, Decorators demystified, which me and Nidhin had a glimpse. Anand Chitipothu, maintainer of web.py framework was explaining from beginner to advanced. He visualized simple decorators like memoize help to compute in a faster way. Explained usage of decorator in the architecture of flask framework.

Our room was booked at Madivala, around 3.5 KM away from NHCC. The travel back  on the line bus was tragedy. Took more than 40 minutes to reach hotel.

The 30 minute long bath helped me to recover from the tiredness of the rush day. I sat on the couch, tried to make some notes of the day. The sweet aroma from Air conditioner and Tandoor Chicken from stomach pulled me to the bed.

Day 2

Morning ride, back to the venue was not that bad. A 10 minute flash in the auto. May be the weekend and Dussehra holidays  dragged people away from the city. We reached  at venue around 9.15 and  stunned when we saw the queue of ‘Python aspirants’.

We got the files and a ‘QR coded’ ID. We rushed for the food and felt disappointed with the ‘long queue’, They were providing wide variety of food items for the day.

Fighting with the queue,  at last, we got food. The session by Kushal Das, Cpython developer and Fedora mentor had already started. The hall was full and we had to ascend to balcony for the session.

Kushal was funny and unfolded his journey through the open source sea. Starting from a small village at Bengal to the Python Software Foundation.

We saw Jayaram, our project manager, Tinu and Faris, directors, who flew from Cochin on previous day. We had a small discussion on last day’s sessions.

I went  to auditorium 2 afterwards for a session on BigData analysis using PySpark, a library for Apache Spark in memory Map Reduce system.

Later We attended Django design patterns by Arun Ravindran. He explained about his experiments and briefed why some of the most common design patterns like abstract factory pattern are ‘Unnecessary Complications’ in python’s case.

Anand Chittipothu’s speech on ‘Messing with Govt data’, was his experience with ‘Electronic election campaign organization’. He covered how he could create an effective election campaign using the available Govt data. Gave short intro on how he created beautiful reports with Report lab library.

We had a fantastic list of items for our lunch. Awesome food, met Oommen, friend of Jayaram, who do research on Biotechnology. He hinted how Biopython is used extensively on biotechnology researches.

The tasty lunch was enough for a good sleep. But the session was so interesting that I had to dispose my sleepy mood. Some talented college guys were trying to implement a faster VM for python. ‘Medusa’ which converts python keywords to equivalent Dart code, and ran on Dart VM. Resulting a much faster python execution. Especially in the case of recursive functions.

Dreamworks guys who coded their workflow with python, was next on stage. They were using twisted matrix, a highly customizable asynchronous framework, helping you to write network programs in any layer. I had never met anyone in person who used Twisted Matrix after my project with a Japanese firm, where we built HTTP Sticky Load balancer. Dreamworks guys explained how twisted helps them transfer large files across the sea, via dedicated line connections in between, by using client server architecture.

The documentary about “Aaron Swartz: The internet’s own boy” was inspirational. He fought for freeing knowledge. Indeed his early death was a great loss to the humanity.

There were lightning talks, which people came out with their ideas/talks and presented for 5 minutes. Was a brilliant idea which covered many new topics in a flash.

Some one took a session on ExpEYES, a cheap CRO, with a USB connector and UI software created on Python. It will definitely help young entrepreneur with Internet of Things device ideas.

A 12 year old and 9 year old kid took sessions on PyGame and how they created games in the simple framework. Python is so simple even kids could program :D

The day went really well. Visited Forum Mall while returning back to hotel. Done a quick shopping and ‘roaming’ though the mall with Sreekanth’s friends. We could try Chicken 65 and tandoor roti, Banglore version from the hotel at Madivala and had a peaceful sleep.

Day 3

Freshened up early, We started our journey for the third day. Seems early morning journey on Saturday and Sunday is not much affected by traffic as on week days. We reached the venue and queued for breakfast. Breakfast was delicious and appetizing. The big queue drawn me to session hall early without fighting much.

The Keynote speaker, Michael Foord, who is an active developer of Cpython and Ubuntu Juju. Started his career at IronPython, he later became active developer in Cpython. He gave introduction to Ubuntu Juju, an orchestration management for various cloud service providers and services. While normal cloud management systems like Ansible, Puppet and Chef provides provisioning capabilities, Juju understands the relationship between those services.

The next session was by  Aditya Manthramurthy @Plivo. Covered how Asynchronous IO systems like Gevent help to scale servers to handle heavy amount of traffic. While traditional codes to fetch data from db, calling thirdparty apis from servers etc block the operation of ‘request to response’, async operations help to run these operations in parallel and speed up response generation time and  handle more requests per second. He also explained how WSGI server handles a request and generate the response. If number of WSGI servers are increased, with the expense of more RAM, handle more number of requests per second.

Faster data processing with python by Anand S, was a mind blowing session. Explained how he could handle the ‘slow’ python for a faster data processing. Done a walk through, pros and cons of data serialization options like csv, json, pickle. His approach to speedup code via eliminate redundant operation, optimize time taking operations via reducing number of hits and reducing number of time per hit was awesome. Described how line profiling is useful for optimizations. He showed how caching some of the recurring functions gives  speedup to the code execution. Briefed Cython, numba with static typing to speedup execution if we need much faster calculations. He showed how some of the functions at numpy and pandas are faster than built in python equivalents.

There was a panel discussion after Anand’s session. Django, Flask or web.py which is better framework for web development. While Arun Narayanan represented Django, Kiran Jonnalagadda of hasgeek represented Flask, and Anand Chitipothu represented web.py.

The discussion included community response, maintenance, optimizations, performance and future of these frameworks. One thing that was new to me, at PyCon they introduced a miscall voting system to vote for the frameworks, and Django was winner in voting, as most of the people use Django for their development.

Next session I went, Development to Production by Anubhav Sinha. He briefed about Vagrant and Docker and explained why docker containers help to ‘Write somewhere and run anywhere’ applications. Docker helps to run applications and environments work across operating systems.

The last session I attended was Narahari Allamraju’s ‘Which messaging layer should you use if you want to build a loosely coupled distributed Python app?’. How to identify the patterns to make application loosely coupled. Briefed about advantages, disadvantages of Zeromq, RabbitMQ, Redis and some other MQ systems.

Most of the people who used iPython Notebook in their presentation. It is an easy web interface for iPython to try codes and save them like a notebook.

We went back to hotel and freshened up, packed things for our return journey. Our train was scheduled @9.30 evening from Banaswadi station, Had to travel 2 hours, roam around a little to find a restaurant near railway station. After 12 hours of train journey we reached Ernakulam Town Monday morning.

And we still miss the PyCon Days :(

 

* Kushal’s Session Original photo link

Using Hstore in Rails 4 with PostgreSQL

Hstore basically gives you a schema-less data store in your PostgreSQL DB. This allows you to store the Hash in a Database column.

If you want to query Model records, it is very difficult if you use Serialize to store dynamic attributes. Hstore acts same as Serialize but we can additionally query the model records using Hstore.

Please follow below steps to enable Hstore in a Ruby on Rails 4 application.

rails generate migration enable_hstore_extension
class EnableHstoreExtension < ActiveRecord::Migration
  def change
    enable_extension 'hstore'
  end
end
&#91;/ruby&#93;

<pre>rake db:migrate</pre>

<pre>rails g migration AddPropertiesToChocolate</pre>

[ruby]
class AddPropertiesToChocolate < ActiveRecord::Migration
  def change
    add_column :chocolates, :properties, :hstore
  end
end
&#91;/ruby&#93;

<pre>rake db:migrate</pre>

<strong>Rails console:</strong>

[ruby]
p = Chocolate.last
p.properties = {'color' =&gt; 'orange'}
p.properties['price'] = '5'
p.save
Chocolate.where("properties -&gt; 'color' = 'orange' ")
Chocolate.where("properties -&gt; 'price' ='5' ")

Finally, you can define accessors for your Hstore keys in your model. Validations work just like they would for any other column in your model.

class Chocolate < ActiveRecord::Base
  # setup hstore
  store_accessor :properties, :color

  # can even run typical validations on hstore fields
  validates :color,
  inclusion: { in: %w{orange gold red} }

end

Vim Bootstrap – generate .vimrc for your favorite programming language

Programmers in the current era like to work using IDEs because it is more user friendly. But there are reasonable number of programmers who still use command line for programming. Their favourite editor might be Vim. Vim is easy to use, light-weight and comes with almost every Unix distribution. Unlike IDEs, it does not hang easily. The only problem with Vim editor is that it does not have inbuilt syntax highlighters. Checkout Vim Bootsrap , problem solved. Using the site you can generate .vimrc file for your favourite programming language. Copy the .vimrc file in your home directory. Now, you are ready to start programming using your favourite language. Vim Bootstrap comes with support of c, python, php, javascript, perl, go and lot more.

An Introduction to Web Crawling using Ruby and Nokogiri

Web Crawling

A web crawler is a program automated script that browses world wide web in methodical and automated manner.Key motivation for designing web crawlers has been retrieve web pages and add their representations to local repository.   Other less frequently used names of a web crawler are

  • Bot
  • ants
  • automatic indexers
  • worm

Difference between web-crawling and web-scraping

Web scraping,  is the process of processing a web document and extracting information out of it.

web scraping will focus on two things:

  1. Examining what the webpage expects from the user and what it shows the user.
  2. Processing the data being sent or received by the browser

Web crawling, is the process of iteratively finding and fetching web links starting from a list of seed URL’s. Strictly speaking, to do web crawling, we to do some degree of web scraping (to extract the URL’s.)

Next we discus  the theory, technique, and programming needed to write web-scrapers.

Use of web inspector in crawling

All of the major browsers have a web inspector built-in or available to them.This highlights selected elements.Data-seekers will get even more utility out of the network panel, which provides a way to directly examine the data and logic underneath the webpage displaying.

The network panel is used to  examine the source of dynamically loaded data requests like Javascript or Flash.

Nokogiri (Rubygem)

RubyGems is a package manager for the Ruby programming language that provides a standard format for distributing Ruby programs and libraries.

Nokogiri  is an HTML, XML, SAX, and Reader parser. Among Nokogiri’s many features is the ability to search documents via XPath or CSS3 selectors.

Features of Nokogiri

  •    XPath support for document searching
  •  CSS3 selector support for document searching
  • XML/HTML builder

Parsing HTML with Nokogiri

Step -1 require rubygems and nokogiri pakaege

All web crawling script is having  these two lines in the beginning

require “rubygems”

require “nokogiri”

Step – 2  Opening page with open-uri pakage.

If the webpage is stored as a file on  hard drive, pass it in like so:
page = Nokogiri::HTML(open(“index.html”))

If the webpage is live on a remote site, like  http://en.wikipedia.org/

page = Nokogiri::HTML(open(“http://en.wikipedia.org/”))

If the webpage is live on a remote site, like http://en.wikipedia.org/, then include the open-uri module, which is part of the standard Ruby distribution but must be explicitly required’

ie.  require “open-uri”

Open-uri  encapsulate all the work of making a HTTP request into the open method, making the operation as simple as as opening a file on our own hard drive.

Step – 3  Selecting elements

Nokogiri’s css method allow  to target individual or groups of HTML methods using CSS selectors.
Eg.
page = Nokogiri::HTML(open(“index.html”))
puts page.class   # => Nokogiri::HTML::Document
page.css(“title”).text #=>title of the web page

The css method does not return the text of the target element,
It returns an array – more specifically, a Nokogiri data object that is a collectino of Nokogiri::XML::Element objects. These Element objects have a variety of methods.
Eg
text
name
attr
value etc..

Page.css(“csspath”)[:atrname]   #=>atrvalue
Page.css(“a.link”)[:href]        #=>”http://anyvalue.come”

Parsing XML using Nokogiri

There is small difference in xml parsing with html parsing . In xml parsing use XML class for parsing .

Page = Nokogiri::XML(open(“file.xml or url”))
retuns an Nokogiri::XML::Document
Use object method “xpath” like “css” method for
to target elements
Page.xpath(“copy xpath from browser inspector”)

we can use all other object method described above for xml parsing

 

 

 

 

 

 

 

 

 

 

 

 

 

Pelican with github pages

Pelican is a static site generator written in python which allows you to write your content directly using reStructuredText or Markdown. In this blog post, we will discuss how to create and host a static site using pelican and github pages.

Installation

Lets wrap all our installations inside a separate virtual environment using python virtual environment wrapper.

Install python virtualenvwrapper

After installing virtual environment wrapper, create a new environment for our project:

$ mkvirtualenv pelican-blog
$ workon pelican-blog

Run pelican installation:

$ pip install pelican

Checkout more installation options for pelican

Run markdown installation for writing the site contents:

$ pip install Markdown

You can also use reStructuredText for writing your content instead of markdown.

Quickstart your blog

Now we have finished all our installations and let’s create a skeleton for our site using the pelican-quickstart command. This will ask you few questions and will pre-populate the settings data as per your answers. These settings can be changed at any point of time.

$ pelican-quickstart

Please see how I have answered the quickstart questions below:

Welcome to pelican-quickstart v3.4.0.

This script will help you create a new Pelican-based website.

Please answer the following questions so this script can generate the files needed by Pelican.

> Where do you want to create your new web site? [.]
> What will be the title of this web site? Sreekanth's Blog
> Who will be the author of this web site? Sreekanth
> What will be the default language of this web site? [en]
> Do you want to specify a URL prefix? e.g., http://example.com (Y/n)
> What is your URL prefix? (see above example; no trailing slash) http://sreekanthkaralmanna.github.io
> Do you want to enable article pagination? (Y/n) How many articles per page do you want? [10]
> Do you want to generate a Fabfile/Makefile to automate generation and publishing? (Y/n)
> Do you want an auto-reload & simpleHTTP script to assist with theme and site development? (Y/n)
> Do you want to upload your website using FTP? (y/N) Do you want to upload your website using SSH? (y/N)
> Do you want to upload your website using Dropbox? (y/N)
> Do you want to upload your website using S3? (y/N)
> Do you want to upload your website using Rackspace Cloud Files? (y/N)
> Do you want to upload your website using GitHub Pages? (y/N)

Done. Your new project is available at /home/sreekanth/Documents

Once you finish with all those questions, you will be having a directory structure as follows:

yourproject/
 ├── content
 │ └── (pages)
 ├── output
 ├── develop_server.sh
 ├── fabfile.py
 ├── Makefile
 ├── pelicanconf.py # Main settings file
 └── publishconf.py # Settings to use when ready to publish

Customise your theme

Pelican comes with a default theme for every site generated. But you can use a variety of other themes to beautify your site.

In order to include your desired theme, clone your preferred theme and save the theme to a theme directory inside your project folder. Now tell pelican that it has to use this particular theme to generate html for your site. In pelicanconfig.py, add the following:

THEME = "themes/theme_name"

Also make sure to change your pelican settings as per the settings given in the theme documentations(if any)

Writing your blog content

We are done with configuring our pelican site, now let’s start writing our blog contents  inside the content folder. Below given is a sample markdown file.

Title: Pelican Test Blog
Date: 2014-05-01 10:00
Category: Python
Tags: python
Author: Sreekanth
Summary: Pelican blog for testing.

A Pelican blog for testing

Generate html files and run your site

We are all done to test our site locally.

The following command will create the output folder for your site and serves your site locally at http://localhost:8000.

$ make devserver

Run the following command to stop the localhost server:

$ ./devserver stop

Publish your blog using Github pages

For hosting your blog using github pages, create a repository named username.github.io and this will be the remote repository for your site. Contents of your output directory has to be stored in this repository.

After creating the github repository, push your output files to the remote repository. Follow the steps given below for doing the same.

$ cd output
$ git init
$ git remote add origin https://github.com/username/username.github.io.git
$ git add --all
$ git commit -m "initial commit"
$ git push origin master

We are all done with hosting our pelican site using github pages. Checkout username.github.com to see your site on live.

Also checkout this slideshow explaining hosting pelican sites using github pages

Happy Blogging :)

JSFiddle : Write and share JS easily

Javascript is the backbone of frontend developers. In fact, knowledge in javascript is an added advantage for every web developer. Need some tool/website for trying out javascript?  Need a site which can be used for sharing your js code?  A site that can be used to edit js code by multiple persons simultaneously? All in one, check out jsfiddle.net :)

You can edit your js code and can share the code by a unique url using jsfiddle. On the left side of the site, you can select the library you want to use and there are separate boxes for editing html, css and js. Here is an example fiddle using jQuery.

http://jsfiddle.net/fxoc1a20/

Using collaboration,  you can invite multiple persons to edit your code. Moreover, the site has support for almost all front-end libraries/frameworks. It supports jQuery,  Dojo, ember.js, angular js, underscore.js, Extjs,  prototype.js  and a lot more. Give it a try, I’m sure, jsfiddle won’t disappoint you.

Become a successful software developer

Success is what everyone wants. It can only be achieved through sheer hard work. How can you become a successful software developer?  Well, it is not that hard. Practicing a few small things can do wonders.

Solve problems:

Try to solve maximum problems. You can find a lot of resources in internet. For example, you can find python practice book here. Remember, practice makes man perfect.

Simple Hello,world!:

When you start to study/implement something, first you have to make sure  simple things work properly. Always go for ‘Hello,world!’ first.

Write simple, readable code:

Writing bunches of code does not make you a good programmer, write code as simple as possible. It should be readable and self explanatory.

Personal projects:

Do some personal projects. Implementing a project will increase your confidence level upto a great extent. You may come across some difficulties, but in the end you will be a happy person. It helps you to identify your strengths and weaknesses. It would be nice if you can reverse engineer some of the projects you like. Push your work on  github. So that, you can show others what you have done.

Googling:

Want to become the best in the industry? The only shortcut is, to become a good googler. Googling is an art. You might have noticed that an experienced developer gets solutions easily while googling than a less experienced developer. It will also be more accurate. That is, googling skill improves through experience. If you are a newbie, don’t worry there are some tips and tricks to improve your googling skill. Here is an article which can help you to be a good googler.

Communication:

Communication plays a key role in becoming a successful professional. Efficient communication increases productivity. When you are starting to do a task, make sure that you are clear on it. Discuss with your seniors and team lead to get a more clearer picture. When you discuss with others, you will get more points on the topic and get feedback of your approach.

Blogging:

Blogging is another way to improve your knowledge. By blogging, you can share your ideas and knowledge. Writing a blog in a topic which you are comfortable, will make you thorough with it. It also improves your language.

Read Tech news:

You should be technically updated. You can achieve this trait by  reading some of these sites.

SlashdotArstechnicaMashableGizmodoTechcrunch

Active in forums:

Be active in forums and discussions. It will improve your knowledge and make you sharper. Stack Overflow is a good site to start with.

Executing bash commands via python

In python, executing bash commands can be done using subprocess module. It’s pretty easy to use and it’s a powerful module. For simple commands,  we can use subprocess.call

Usage:

import subprocess

subprocess.call("command1")

subprocess.call(["command1", "arg1", "arg2"])

Eg:

import subprocess

subprocess.call(["ls", "-l"])
total 4

-rw-rw-r-- 1 tevin tevin 15 Sep 3 15:29 test.txt

You can also use subprocess.check_call  and subprocess.check_output

Popen:

For more flexibility, you can use Popen . Using this you can store the output of command as well as any error occurred during command execution.

Eg:

process = subprocess.Popen(["ls", "-l"])
(output, err) = process.communicate()

communicate  method interacts with process and waits for the process to complete. It returns a tuple consisting of stdout and stderr.

Executing commands in background:

subprocess.Popen() only runs a process in the background if nothing in the python script depends on the output of the command being run. For example, the following code won’t be executed in background.

import subprocess

process = subprocess.Popen(["ls", "-l"], stdout=subprocess.PIPE)

Thinking about what is subprocess.PIPE?

subprocess.PIPE: Special value that can be used as the stdin, stdout or stderr argument to Popen and indicates that a pipe to the standard stream should be opened.

Changing directory(cd command):

You might be thinking that why ‘cd’? Why it can’t be executed using subprocess?

If you use subprocess.call(“cd ..”), it will throw an error ‘No such file or directory’. It is because cd is a shell internal. So you can only call it as

subprocess.call('cd ..', shell=True)

But it is pointless to do so.  As no process can change another process’s working directory (again, at least on a UNIX-like OS, but as well on Windows), this call will have the subshell change its dir and exit immediately. Don’t worry you can change directory using os.chdir(path).

Calm.com – An answer to meditate at workplace

All are stressed at your workplace for one reason or other. Listening to music or seeing beautiful places will release your pressure upto an extent. Calm.com is an answer to get relieved at your workplace. It comes with calming music and beautiful nature scenes.  In fact, it helps you to meditate.

You can choose either guided calm or setting a timer. In guided calm, a person(recorded voice) will guide you to be calm. The person will give you proper instructions. You can set timers ranging from 2 minutes to 20 minutes. Also, you can change music as well as nature scenes as you wish.

Luckily for mobile phone users,  there are iPhone and android apps for the same. I assure you, it will be a nice experience and should make you calm.