September 2014 THE COMPLETE MAGAZINE ON OPEN SOURCE
O PE N SOU R C E FO R YOU
VOLU ME : 02 ISSU E : 12
Email : [email protected] ContentsDevelopers 26 Improve Python Code by Using a Profiler
30 Understanding the Document Object Model (DOM) in Mozilla
40 Introducing AngularJS 45 Use Bugzilla to Manage Defects in Software
48 An Introduction to Device Drivers in the Linux Kernel 35 Experimenting with More Functions in Haskell 52 Creating Dynamic Web Portals Using Joomla and WordPress
56 Compile a GPIO Control Application and Test It On the Raspberry Pi
Admin 59 Use Pound on RHEL to Balance the Load on Web Servers 67 Boost the Performance of CloudStack with Varnish Why We Need to Handle Bounced Emails 74 Use Wireshark to 63 Detect ARP Spoofing 77 Make Your Own PBX with Asterisk REGULAR FEATURES Open Gurus 08 You Said It... 25 Editorial Calendar 80 How to Make Your USB Boot 09 Offers of the Month 100 Tips & Tricks with Multiple ISOs New Products 86 Contiki OS Connecting 10 105 FOSS Jobs Microcontrollers to the 13 FOSSBytes Internet of Things
4 | September 2014 | OPEN SOURCE For You | www.OpenSourceForU.com
YOUSAID IT
Online access to old issues helpful to them. We will surely look into your request and I want all the issues of OSFY from 2011, right up to the try to include the topic you have asked for in upcoming current issue. How can I get these online, and what would be issues. Keep reading OSFY and continue sending us your the cost? feedback! —c kiran kumar; [email protected] Annual subscription I’ve bought the July 2014 issue of OSFY and I loved ED: It feels great to know that we have such valuable readers. it. I want the latest version of the Ubuntu 14.04 LTS and the Thank you, Kiran, for bringing this request to us. You can avail programming tools (JDK and other tools for C, C+, Java and all the back issues of Open Source For You in e-zine format from Python). Also, how can I subscribe to your magazine for one www.ezines.efyindia.com year and can I get it at my village (address enclosed)? —Parveen Kumar; Request for a sample issue [email protected] I am with a company called Relia-Tech, which is a brick- and-mortar computer service company. We are interested in ED: Thank you for the compliments. We're glad to know that subscribing to your magazine. Would you be willing to send us a you enjoy reading our magazine. We will definitely look into magazine to check out before we commit to anything? your request. Also, I am forwarding your query regarding —Lindsay Steele; subscribing to the magazine to the concerned team. Please [email protected] feel free to get back to us in case of any other suggestions or questions. We're always happy to help. ED: Thanks for your mail. You can visit our website www.ezine. lfymag.com and access our sample issue. Availability of OSFY in your city I want to purchase Open Source For You for the A ‘thank-you’ and a request for more help library in my organisation but I am unable to find copies I began reading your magazine in my college library and in the city I live in (Jabalpur in Madhya Pradesh). I cannot thought of offering some feedback. go in for the subscription as well. Please give me the name I was facing a problem with Oracle Virtual Box, but after of the distributor or dealer in my city through whom I can reading an article on the topic in OSFY, the task became so easy. purchase the magazine. Thanks for the wonderful help. I am also trying to set up —Gaurav Singh; my local (LAN-based) GIT server. I have no idea how to [email protected] set it up. I have worked a little with GitHub. I do wish your magazine would feature content on this topic in upcoming ED: We have a website where you can locate the nearest store editions. in your city that supplies Open Source For You. Do log on —Abhinav Ambure; to http://ezine.lfymag.com/listwholeseller.asp. You will find [email protected] there are two dealers of the magazine in your city: Sahu News Agency (Sanjay Sahu, Ph: 09301201157) and Janta News ED: Thank you so much for your valuable feedback. We Agency (Harish, Ph: 09039675118). They can ensure regular really value our readers and are glad that our content proves supply of the magazine to your organisation.
Please send your comments Share Your or suggestions to: The Editor, Open Source For You, D-87/1, Okhla Industrial Area, Phase I, New Delhi 110020, Phone: 011-26810601/02/03, Fax: 011-26817563, Email: [email protected]
8 | September 2014 | OPEN SOURCE For You | www.OpenSourceForU.com www.OpenSourceForU.com | OPEN SOURCE For You | September 2014 | PB offerS THE monTH 2000 One Rupees month Coupon free (Free Trial Coupon) Free Dedicated Server Hosting No condition attached for trial of our for one month cloud platform Subscribe for our Annual Package of Dedicated Server Hosting & enjoy one month free service Enjoy & Please share Feedback at [email protected] Hurry! th Hurry! th For more information, call us Offer valid till 30 Offer valid till 30 on 1800-209-3006/ +91-253-6636500 September 2014! For more information, call us on September 2014! 1800-212-2022 / +91-120-666-7718
www.esds.co.in www.cloudoye.com
Get 10% 35% discount off & more “Do not wait! Be a part of Reseller package special offer ! the winning team”
Free Dedicated hosting/VPS for one Get 35% off on course fees and if you appear month. Subscribe for annual package for two Red Hat exams, the second shot is free of Dedicated hosting/VPS and get Hurry! th one month FREE th Hurry! Contact us @ 98409 82184/85 or Offer valid till 30 Contact us at 09841073179 Offer valid till 30 Write to [email protected] September 2014! or Write to [email protected] September 2014!
www.space2host.com www.vectratech.in
Get PACKWEB PACK WEB Get 25% HOSTING 12 Months P roX Free Off Time to go PRO now Pay Annually & get 12 Month Free Considering VPS or a Dedicated Services on Dedicated Server Hosting Server? Save Big !!! And go Subscribe for the Annual Packages of with our ProX Plans Dedicated Server Hosting & Enjoy Next 25% Off on ProX Plans - Ideal for running 12 Months Free Services th Hurry! th Hurry! High Traffic or E-Commerce Website Coupon Code : OSFY2014 Offer valid till 30 Offer valid till 30 September 2014! For more information, call us on September 2014! Contact us at 98769-44977 or 1800-212-2022 / +91-120-666-7777 Write to [email protected] www.goforhosting.com www.prox.packwebhosting.com
Pay the most EMBEDDED SOFTWARE DEVELOPMENT competitive COURSES AND WORKSHOPS Fee Embedded RTOS -Architecture, Internals To advertise here, contact and Programming - on ARM platform Omar on +91-995 888 1862 or Date: 20-21 Sept’ 2014 ( 2 days program) Faculty: Mr. Babu Krishnamurthy 011-26810601/02/03 or COURSE Visiting Faculty / CDAC/ ACTS with 18 years Write to [email protected] FEE: of Industry and Faculty Experience RS.5620/- (all inclusive) Contact us at +91-98453-65845 or Write to [email protected] www.opensourceforu.com
FOSSBYTES Powered by www.efytimes.com
Ubuntu 14.04.1 LTS is out VLC 2.1.5 has been The Ubuntu 14.04 LTS has released been around for quite some VideoLAN has announced the time now and most people release of the final update in the must have upgraded it. 2.1.x series of its popular open Another smaller update is source, cross-platform media player ready – 14.04.1. Canonical and streaming media has announced that this server: the VLC media Ubuntu update fixes many player. VLC 2.1.5 is bugs and includes security now available for updates. There is also a list of bugs and other updates in Ubuntu 14.04.1 that download and you might want to have a look at, in order to see the scope of this update. If you installation on haven’t upgraded to 14.04.1 yet, do so as soon as possible. It is a worthy upgrade Windows, Mac and if you use an older version of Ubuntu. Linux operating systems. Notably, the next big release for the VLC Android Device Manager makes it easier to media player will be that of the search for lost phones! 2.2.x branch. A careful look at the Google has created an update in Android Device change log reveals that although the Manager that will help the device’s users better VLC 2.1.5 update has been released security. This latest version is called 1.3.8. It will across multiple platforms, the most help add a phone number in the remote locking noticeable improvements are for OS screen, and the ‘lock screen’ password can also X users. Others could consider it as a be changed. An optional message can also be set minor update. up. If the phone number is added, then a big green For OS X users, VLC 2.1.5 button will appear on the lock screen saying ‘Call brings about additional stability owner’. If the lost phone is found by someone, to the Qtsound capture module as then the owner can be easily contacted. Earlier, well as improved support for Reti. only a message could be added by the users. The Other notable changes (for the OS call-back number can be set up through the Android X platform) include compilation Device Manager app as well as the Web interface, fixes for OS/2 operating systems. if another Android device is not present. Both Also, MP3 file conversions will no these message and call-back features are optional, longer be renamed ‘.raw’ under the though. But it’s highly recommended that these features are used so that a lost Qt interface following the update. A phone can be easily found. few decoder fixes will now benefit DxVA2 sample decoding, MAD Ubuntu’s Amazon shopping feature complies resistance in broken MP3 streams with UK Data Protection Act and PGS alignment tweaks for MKV. The independent body investigating In terms of security, the new release the implementation of Ubuntu’s Unity comes with fixes for GNU TLS and Shopping Lens feature and its compliance libpng as well. One should remember with the UK Data Protection Act (DPA) of that VLC is a portable, free and open 1998 has found no instances of Canonical source, cross-platform media player being in breach of the act. Ubuntu’s and streaming media server written by controversial ‘Amazon shopping’ feature the VideoLAN project that supports has been found to be compliant with many audio and video compression relevant data protection and privacy laws methods and file formats. It comes in the UK, something that was checked in response to a complaint filed by blogger with a large number of free decoding Luis de Sousa last year. Notably, the feature sends out queries made in the Dash to an and encoding libraries, thereby intermediary Canonical server, which sends it forward to Amazon. The e-commerce eliminating the need of finding or giant then returns product suggestions matching the query back to the Dash. The calibrating proprietary plugins. feature also sends across non-identifiable location data out in the process.
www.OpenSourceForU.com | OPEN SOURCE For You | September 2014 | 13 FOSSBYTES
Here’s what’s new in Linux 3.16 The founder of Linux, Linus Torvalds, Calendar of forthcoming events announced the release of the stable build of Name, Date and Venue Description Contact Details and Website Linux 3.16 recently. This version is known 4th Annual Datacenter The event aims to assist the community in Praveen Nair; Email: Praveen.nair@ as ‘Shuffling Zombie Juror’ for developers. Dynamics Converged. the data centre domain by exchanging ideas, datacenterdynamics.com; Ph: +91 There are a host of improvements and new September 18, 2014; accessing market knowledge and launching 9820003158; Website: Bengaluru new initiatives. http://www.datacenterdynamics.com/ features in this new stable build of Linux. CIOs and senior IT executives from across the These include new and improved drivers, Gartner Symposium IT Xpo, world will gather at this event, which offers Website: October 14-17, 2014; Grand and some complex integral improvements talks and workshops on new ideas and strate- http://www.gartner.com Hyatt, Goa like a unified control hierarchy. This new gies in the IT industry. Linux 3.16 stable version will be ideal for Open Source India, Asia’s premier open source conference that Omar Farooq; Email: omar.farooq@ the Ubuntu Linux Kernel 14.10. LTS version November 7-8, 2014; aims to nurture and promote the open source efy.in; Ph: 09958881862 users will get this update once the 14.10 NIMHANS Center, Bengaluru ecosystem across the sub-continent. http://www.osidays.com kernel is released. CeBit This is one of the world’s leading business IT Website: November 12-14, 2014; events, and offers a combination of services http://www.cebit-india.com/ Shutter 0.92 for Linux released BIEC, Bengaluru and benefits that will strengthen the Indian IT and fixes a number of bugs and ITES markets. Users have had some trouble using the 5th Annual Datacenter The event aims to assist the community in Praveen Nair; Email: Praveen.nair@ popular Shutter screenshot tool for Linux Dynamics Converged; the datacentre domain by exchanging ideas, datacenterdynamics.com; Ph: +91 December 9, 2014; Riyadh accessing market knowledge and launching 9820003158; Website: owing to the many irritating bugs and new initiatives. http://www.datacenterdynamics.com/ stability issues that came along. But they are Hostingconindia This event will be attended by Web hosting Website: in for a pleasant surprise as developers have December 12-13, 2014; companies, Web design companies, domain http://www.hostingcon.com/ now released a new bug fix for the tool that NCPA, Jamshedji Bhabha and hosting resellers, ISPs and SMBs from contact-us/ aims to address some of its more prominent Theatre, Mumbai across the world. issues. The new bug fix—Shutter 0.92—is now available for download for the Linux According to Sousa, the Shopping Lens implementation “…contravened a platform and a number of stability issues 1995 EU Directive on the protection of users’ personal data.” Sousa had provided have been dealt with for good. a number of instances to put forward his point. Initially, Sousa began by reaching out to Canonical for clarification but to no avail. He was finally forced to file a Open source community irked complaint with the Information Commissioner’s Office regarding his security by broken Linux kernel patches concerns. Finally, the ICO responded to Sousa’s need for clarification by clearly One of the many fine threads that bind the stating that the Shopping Lens feature complies with the DPA (Data Protection Act) open source community is avid participation very well and in no way breaches users’ privacy. and cooperation between developers across the globe, with the common goal of improving Oracle launches Solaris 11.2 with OpenStack support the Linux kernel. However, not everyone is Oracle Corp recently launched the latest actually trying to help out there, as recent version of its Solaris enterprise UNIX happenings suggest. Trolls exist even in the platform: Solaris 11.2. Notably, this new Linux community, and one that has managed version was in beta since April. The to make a big impression is Nick Krause. latest release comes with several key Krause’s recent antics have led to significant enhancements—the support for OpenStack bouts of frustration among Linux kernel as well as software-defined networking maintainers. Krause continuously tries to get (SDN). Additionally, there are various broken patches past the maintainers—only security, performance and compliance his goals are not very clear at the moment. enhancements introduced in Oracle’s Many developers believe that Krause aims to new release. Solaris 11.2 comes with OpenStack integration, which is perhaps its damage the Linux kernel. While that might most crucial enhancement. The latest version runs the most recent version of the be a distant dream for him (at least for now), popular toolbox for building clouds: OpenStack Havana. Meanwhile, the inclusion he has managed to irk quite a lot of people, of software-defined networking (SDN) support is seen as Oracle’s ongoing effort to slowing down the whole development process transform its Exalogic Elastic Cloud into one-stop data centres. Until now, Exalogic because of the need to keep fixing broken boxes were being increasingly used in the form of massive servers or for transaction patches introduced by him. processing. They were therefore not fulfilling their real purpose, which is to work
14 | September 2014 | OPEN SOURCE For You | www.OpenSourceForU.com
FOSSBYTES
as cloud-hosting systems. However, with SDN support added, Oracle is aiming Android-x86 4.4 R1 to change all this. Oracle plans to directly take on network equipment makers Linux distro available for like Cisco, Hewlett-Packard and Brocade with the introduction of Solaris 11.2. download and testing Enterprises using Solaris can now simply purchase a handful of Solaris boxes and The team behind Android-x86 run their mission-critical clouds. In addition, they can also use bits of OpenStack recently launched version 4.4 R1 of without acquiring additional hardware. the port of the Android OS designed specifically for the x86 platform. Canonical launches Ubuntu 12.04.5 LTS Android-x86 4.4 KitKat is now Marking its fifth point release, Canonical has announced that Ubuntu 12.04.5 LTS available for download and testing is available for download and installation. Ubuntu 12.04 on the Linux platform for your LTS was first released back in April 2012. Canonical PC. Android is actually based on a will continue supporting the LTS until 2017 with regular modified Linux kernel, with many updates from time to time. Also, this is the first major believing it to be a stand alone Linux release for Canonical since the debut of Ubuntu 14.04 distribution in its own right. With that LTS earlier this year. The most notable improvement said, developers have managed to in the new release is the inclusion of an updated kernel tweak Android to make it port to the (3.13) and X.org stack. Both of these have been traded PC for the x86 platforms; that’s what from Ubuntu 14.04 LTS. The new release is out now for Android-x86 is really all about. desktop, server, cloud and core products, as well as other flavours of Ubuntu with long-term support. In addition, the new release also comes Linux Mint Debian edition with ‘security updates and corrections for other high-impact bugs, with a focus to switch from snapshot on maintaining stability and compatibility with Ubuntu 12.04 LTS.’ Meanwhile, cycle to Debian stable Kubuntu 12.04.5 LTS, Edubuntu 12.04.5 LTS and Ubuntu Studio 12.04.5 LTS are package base also available for download and install. Storm Energy’s SunSniffer charmed by Raspberry Pi! The humble Raspberry Pi single board computer is indeed going places, receiving critical acclaim for, well, being downright awesome. The latest to be smitten by it is the German company, Storm Energy, which builds products like SunSniffer, a solar plant monitoring system. The SunSniffer system is designed to monitor photovoltaic (PV) solar power installations of varied sizes. The company has now upgraded the system to a Linux- The team behind Linux Mint has based platform running on a Raspberry Pi. In addition to this, the decided to let go of the current latest SunSniffer version also comes with a custom expansion snapshot cycle in the Debian edition board and customised Linux OS. The SunSniffer is IP65-rated, for the Linux distribution and instead and the new Connection Box’s custom Raspberry Pi expansion switch over to a Debian stable board comes with five RS-485 ports and eight analogue/digital package base. The current Linux I/O interfaces to help simultaneously monitor a wide variety Mint editions are based on Ubuntu of solar inverters (Refusol, Huawei and Kostal, among others). In short, the new system and the team is most likely to stick can remotely control solar inverters via a radio ripple control receiver, as against earlier to that for at least a couple of years. versions where users could only monitor their data. The team recently launched the The Raspberry Pi-laden SunSniffer also offers SSL-encryption and optional latest iteration of Linux Mint, a.k.a. integrated anti-theft protection. ‘Qiana’. Both the Cinnamon and Mate versions are now available for Italian city of Turin switching to open source technology download with the KDE and XFCE In a recent development, the Italian city of Turin is considering ditching all versions expected to come out soon. Microsoft products in favour of open source alternatives. The move is directly Meanwhile, it has been announced aimed at cutting government costs, while not compromising on functionality. If at that the next three Linux Mint all Turin gets rid of all proprietary software, it will go on to become one of the first releases would also, in all probability, Italian ‘open source cities’ and save itself at least a whopping six million Euros. A be based on Ubuntu 14.04 LTS. report suggests that as many as 8,300 computers of the local administration in Turin will soon have Ubuntu under the hood and will be shipped with the Mozilla Firefox
16 | September 2014 | OPEN SOURCE For You | www.OpenSourceForU.com FOSSBYTES
Web browser and OpenOffice—the two joys of the open source world. The local Khronos releases OpenGL NG government has argued that a large amount of money is spent on buying licences in The Khronos Group recently announced case of proprietary software, wasting a lot of the local tax payers’ money. Therefore, the release of the latest iteration of a decision to drop Microsoft in favour of cost-effective open source alternatives OpenGL (the oldest high-level 3D seems to be a viable option. graphics API still in popular use). Although OpenGL 4.5 is a noteworthy LibreOffice coming to Android release in its own right, the Group’s LibreOffice needs no introduction. The Document Foundation’s popular open second major release in the next source office suite is widely used by millions of people across the globe. Therefore, generation OpenGL initiative is garnering news that the suite could soon be widespread appreciation. While OpenGL launched on Android is something to 4.5 is what some might call a fairly watch out for. You heard that right! A standard annual OpenGL update, OpenGL new report by Tech Republic suggests NG is a complete rebuild of the OpenGL that the Document Foundation is API, designed with the idea of building an currently on a rigorous workout to entirely new version of OpenGL. This new make this happen. However, as things version will have a significantly reduced stand, there is still some time before that happens for real. Even as the Document overhead owing to the removal of a lot Foundation came out with the first Release Candidate (RC) version of the upcoming of abstraction. Also, it will do away with LibreOffice 4.2.5 recently (it has been quite consistent in updating its stable version the major inefficiencies of older versions on a timely basis), work is on to make LibreOffice available for Google’s much when working at a low level with the bare loved Android platform as well, the report says. The buzz is that developers back metal GPU hardware. home are currently talking about (and working at) getting the file size right, that is, Being a very high-level API, earlier something well below the Google limit. Until they are able to do that, LibreOffice versions of OpenGL made it hard to for Android is a distant dream, sadly. efficiently run code on the GPU directly. However, as and when this happens, LibreOffice would be in direct competition While this didn’t matter so much earlier, with Google Docs. Since there is a genuine need for Open Document Format (ODF) now things have changed. Fuelled by support in Android, the release might just be what the doctor ordered for many users. more mature GPUs, developers today This is more of a rumour at the moment, and things will get clearer in time. There is tend to ask for graphics APIs that allow no official word from either Google or the Document Foundation about this, but we them to get much closer to the bare will keep you posted on developments. The recent release – the LibreOffice 4.2.5 metal. The next generation OpenGL RC1—meanwhile tries to curb many key bugs that plagued the last 4.2.4 final release. initiative is directed at developers who This, in turn, has improved its usability and stability to a significant extent. are looking to improve performance and reduce overhead. RHEL 6.6 beta is released; draws major inspiration from RHEL 7 Just so RHEL 6.x users (who wish to continue with this branch of the distribution for Dropbox’s updated Android a bit longer) don’t feel left out, Red Hat has launched a beta release of its Red Hat App offers improved features Enterprise Linux 6.6 (RHEL 6.6) platform. Taking much of its inspiration from the A major update has been announced recently released RHEL 7, the move is directed towards RHEL 6.x users so that they by Dropbox in connection with its benefit from new platform features. At the same time, it comes with some real cool official Android app, and is available features that are quite independent of RHEL 7 and which make 6.6 beta stand out at Google Play. This new update on its own merits. Red Hat offers Application Binary Interface (ABI) compatibility carries version number 2.4.3 and for RHEL for a period of ten years, so technically speaking, it cannot drastically comes with a lot of improved features. change major elements of an in-production release. Quite simply put, it can’t and As the Google Play listing suggests, won’t change an in-production release in a way that could alter stability or existing this new Dropbox version supports in- compatibility. This would eventually mean that the new release on offer cannot go app previews of Word, PowerPoint and much against the tide with respect to RHEL 6. Although the feature list for RHEL PDF files. A better search experience is 6.6 beta ties in closely with the feature list of the major release (6.0), it doesn’t also offered in this new version, which mean RHEL 6.6 beta is simply old wine served in a new bottle. It does manage to enables tracking of recent queries, and introduce some key improvements for RHEL 6.x users. To begin with, RHEL 6.6 suggestions are also displayed. One beta includes some features that were first introduced with RHEL 7, the most notable can also search in specific folders from being Performance Co-Pilot (PCP). The new beta release will also offer RHEL 6.x now onwards. users more integrated Remote Direct Memory Access (RDMA) capabilities.
www.OpenSourceForU.com | OPEN SOURCE For You | September 2014 | 17 Buyers’ Guide Motherboards The Lifeline of Your Desktop If you are a gamer, or like to customise your PC and build it from scratch, the motherboard is what you require to link all the important and key components together. Let’s find out how to select the best desktop motherboards.
he central processing unit (CPU) can be considered to CPU socket be the brain of a system or a PC in layman’s language, The central processing unit is the key component of a motherboard T but it still needs a ‘nervous system’ to be connected and its performance is primarily determined by the kind of with all the other components in your PC. A motherboard processor it is designed to hold. The CPU socket can be defined plays this role, as all the components are attached to it and as an electrical component that connects or attaches to the to each other with the help of this board. It can be defined motherboard and is designed to house a microprocessor. So, as a PCB (printed circuit board) that has the capability of when you’re buying a motherboard, you should look for a CPU expanding. As the name suggests, a motherboard is believed socket that is compatible with the CPU you have planned to use. to be the ‘mother’ of all the components attached in it, Most of the time, motherboards use one of the following five including network cards, sound cards, hard drives, TV tuner sockets -- LGA1155, LGA2011, AM3, AM3+ and FM1. Some cards, slots, etc. It holds the most significant sub-systems— of the sockets are backward compatible and some of the chips the processor along with other important components. A are interchangeable. Once you opt for a motherboard, you will be motherboard is found in all electronics devices like TVs, limited to using the processors that offer similar specifications. washing machines and other embedded systems. Since it provides the electrical connections through which other Form factor components are connected and linked with each other, it needs A motherboard’s capabilities are broadly determined by its the most attention. It hosts other devices and subsystems and shape, size and how much it can be expanded – these aspects also contains the central processing unit, unlike the backplane. are known as form factors. Although there is no fixed design or There are quite a lot of companies that deal with form for motherboards, and they are available in many variations, motherboards and Simmtronics is one among the leading players. two form factors have always been the favourites -- ATX and According to Dr Inderjeet Sabbrawal, chairman, Simmtronics, microATX. The ATX motherboard measures around 305cm “Simmtronics has been one of the exclusive manufacturers of x 23cm (12 inch x 9 inch) and offers the highest number of motherboards in the hardware industry over the last 20 years. We expansion slots, RAM bays and data connectors. MicroATX strongly believe in creativity, innovation and R&D. Currently, we motherboards measure 24.38cm x 24.38cm (9.6 x 9.6 inch) and are fulfilling our commitment to provide the latest mainstream have fewer expansion slots, RAM bays and other components. motherboards. At Simmtronics, the quality of the motherboards The form factor of a motherboard can be decided according to is strictly controlled. At present, the market is not growing.… what purpose the motherboard is expected to serve. India still has a varied market for older generation models as well as the latest models of motherboards.” RAM bays Random access memory (RAM) is considered the most important Factors to consider while buying a motherboard workspace in a motherboard, where data is processed even after In a desktop, several essential units and components being removed from the hard disk drive or solid state drive. The are attached directly to the motherboard, such as the efficiency of your PC directly depends on the speed and size of your microprocessor, main memory, etc. Other components, such RAM. The more space you have on your RAM, the more efficient as the external storage controllers for sound and video display your computing will be. But it’s no use having a RAM with greater and various peripheral devices, are attached to it through efficiency than your motherboard can support, as that will be just a slots, plug-in cards or cables. There are a number of factors to waste of the extra potential. Neither can you have RAM with lesser keep in mind while buying a motherboard, and these depend efficiency than the motherboard, as then the PC will not work well on the specific requirements. Linux is slowly taking over the due to the bottlenecks caused by mismatched capabilities. Choosing PC world and, hence, people now look for Linux-supported the motherboard which supports just the right RAM is vital. motherboards. As a result, almost every motherboard now Apart from these factors, there are many others to consider before supports Linux. The many factors to keep in mind when selecting a motherboard. These include the audio system, display, buying a Linux-supported motherboard are discussed below. LAN support, expansion capabilities and peripheral interfaces.
18 | September 2014 | OPEN SOURCE For You | www.OpenSourceForU.com Buyers’ Guide A few desktop motherboards with the latest chipsets Intel: DZ87KLT-75K motherboard Supported CPU: Fourth generation Intel Core i7 processor, Intel Core i5 processor and other Intel processors in the LGA1150 package Memory supported: 32GB of system memory, dual channel DDR3 2400+ MHz, DDR3 1600/1333 MHz Form factor: ATX form factor
Asus: Z87-K motherboard Supported CPU: Fourth generation Intel Core i7 processor, Intel Core i5 processor and other Intel processors Memory supported: Dual channel memory architecture supports Intel XMP Form factor: ATX form factor
Simmtronics SIMM-INT H61 (V3) motherboard CPU supported: Intel Core2nd and Core3rd Generation i7/i5/i3/Pentium/Celeron Main memory supported: Dual channel DDR3 1333/1066 BIOS: 1×32MB Flash ROM Connectors: 1×4-pin ATX 12V power connector Chipset: Intel H61 (B3 Version)
Gigabyte Technology: GA-Z87X-OC motherboard CPU supported: Fourth generation Intel Core i7 processor, Intel Core i5 processor and other Intel processors Memory supported: Supports DDR3 3000 Form factor: MicroATX
By: Manvi Saxena The author is a part of the editorial team at EFY.
www.OpenSourceForU.com | OPEN SOURCE For You | September 2014 | 19 CODE SPORT Sandya Mannarswamy In this month’s column, we continue our discussion on natural language processing.
or the past few months, we have been discussing The software design phase also produces a number of information retrieval and natural language processing, SE artifacts such as the design document, design models Fas well as the algorithms associated with them. This in the form of UML documents, etc, which also can be month, we continue our discussion on natural language mined for information. Design documents can be analysed processing (NLP) and look at how NLP can be applied to generate automatic test cases in order to test the final in the field of software engineering. Given one or many product. During the development and maintenance phases, text documents, NLP techniques can be applied to extract a number of textual artifacts are generated. Source code information from the text documents. The software itself can be considered as a textual document. Apart from engineering (SE) lifecycle gives rise to a number of textual source code, source code control system logs such as SVN/ documents, to which NLP can be applied. GIT logs, Bugzilla defect reports, developers’ mailing lists, So what are the software artifacts that arise in SE? field reports, crash reports, etc, are the various SE artifacts to During the requirements phase, a requirements document which text mining can be applied. is an important textual artifact. This specifies the expected Various types of text analysis techniques can be applied behaviour of the software product being designed, in terms to SE artifacts. One popular method is duplicate or similar of its functionality, user interface, performance, etc. It is document detection. This technique can be applied to important that the requirements being specified are clear find out duplicate bug reports in bug tracking systems. A and unambiguous, since during product delivery, customers variation of this technique can be applied to code clones would like to confirm that the delivered product meets all and copy-and-paste snippets. their specified requirements. Automatic summarisation is another popular technique Having vague ambiguous requirements can hamper in NLP. These techniques try to generate a summary of a requirement verification. So text analysis techniques can given document by looking for the key points contained in it. be applied to the requirements document to determine There are two approaches to automatic summarisation. One whether there are any ambiguous or vague statements. is known as ‘extractive summarisation’, using which key For instance, consider a statement like, “Servicing of user phrases and sentences in the given document are extracted requests should be fast, and request waiting time should and put back together to provide a summary of the document. be low.” This statement is ambiguous since it is not clear The other is the ‘abstractive summarisation’ technique, which what exactly the customer’s expectations of ‘fast service’ is used to build an internal semantic representation of the or ‘low waiting time’ may be. NLP tools can detect such given document, from which key concepts are extracted, and ambiguous requirements. It is also important that there are a summary generated using natural language understanding. no logical inconsistencies in the requirements. For instance, The abstractive summarisation technique is close to how a requirement that “Login names should allow a maximum humans would summarise a given document. Typically, we of 16 characters,” and that “The login database will have a would proceed by building a knowledge representation of field for login names which is 8 characters wide,” conflict the document in our minds and then using our own words with each other. While the user interface allows up to a to provide a summary of the key concepts. Abstractive maximum of 16 characters, the backend login database summarisation is obviously more complex than extractive will support fewer characters, which is inconsistent with summarisation, but yields better summaries. the earlier requirement. Though currently such inconsistent Coming to SE artifacts, automatic summarisation requirements are flagged by human inspection, it is possible techniques can be applied to generate large bug reports. to design text analysis tools to detect them. They can also be applied to generate high level comments
20 | September 2014 | OPEN SOURCE For You | www.OpenSourceForU.com Guest Column CodeSport of methods contained in source code. In this case, each method intent. Hence, the code written by the developer and the comment can be treated as an independent document and the high level associated with that piece of code should be consistent with each comment associated with that method or function is nothing but a other. Consider the simple code sample shown below: short summary of the method. Another popular text analysis technique involves the use of /* linux/drivers/scsi/in2000.c: */ language models, which enables predicting what the next word /* caller must hold instance lock */ would be in a particular sentence. This technique is typically used in Static int reset_hardware(…) optical character recognition (OCR) generated documents, where due { to OCR errors, the next word is not visible or gets lost and hence the …. tool needs to make a best case estimate of the word that may appear } there. A similar need also arises in the case of speech recognition static int in2000_bus_reset(…) systems. In case of poor speech quality, when a sentence is being { transcribed by the speech recognition tool, a particular word may ….. not be clear or could get lost in transmission. In such a case, the tool reset_hardware(); needs to predict what the missing word is and add it automatically. … Language modelling techniques can also be applied in intelligent } development environments (IDE) to provide ‘auto-completion’ suggestions to the developers. Note that in this case, the source code In the above code snippet, the developer has expressed the itself is being treated as text and is analysed. intention that ‘instance_lock’ must be held before the function Classifying a set of documents into specific categories is another ‘reset_hardware’ is called as a code comment. However, in the well-known text analysis technique. Consider a large number of news actual source code, the lock is not acquired before the call to articles that need to be categorised based on topics or their genre, such ‘reset_hardware’ is made. This is a logical inconsistency, which can as politics, business, sports, etc. A number of well-known text analysis arise either due to: (a) comments being outdated with respect to the techniques are available for document classification. Document source code; or (b) incorrect code. Hence, flagging such errors is classification techniques can also be applied to defect reports in SE to useful to the developer who can fix either the comment or the code, classify the category to which the defect belongs. For instance, security depending on which is incorrect. related bug reports need to be prioritised. While people currently inspect bug reports, or search for specific key words in a bug category My ‘must-read book’ for this month field in Bugzilla reports in order to classify bug reports, more robust This month’s book suggestion comes from one of our readers, and automated techniques are needed to classify defect reports in large Sharada, and her recommendation is very appropriate to the scale open source projects. Text analysis techniques for document current column. She recommends an excellent resource for natural classification can be employed in such cases. language processing—a book called, ‘Speech and Language Another important need in the SE lifecycle is to trace source Processing: An Introduction to Natural Language Processing’ by code to its origin in the requirements document. If a feature ‘X’ Jurafsky and Martin. The book describes different algorithms for is present in the source code, what is the requirement ‘Y’ in the NLP techniques and can be used as an introduction to the subject. requirements document which necessitated the development Thank you, Sharada, for your valuable recommendation. of this feature? This is known as traceability of source code to If you have a favourite programming book or article that you requirements. As source code evolves over time, maintaining think is a must-read for every programmer, please do send me traceability links automatically through tools is essential to a note with the book’s name, and a short write-up on why you scale out large software projects. Text analysis techniques think it is useful so I can mention it in the column. This would can be employed to connect a particular requirement from the help many readers who want to improve their software skills. requirements document to a feature in the source code and hence If you have any favourite programming questions/software automatically generate the traceability links. topics that you would like to discuss on this forum, please We have now covered automatic summarisation techniques send them to me, along with your solutions and feedback, at for generating summaries of bug reports and generating header sandyasm_AT_yahoo_DOT_com. Till we meet again next level comments for methods. Another possible use for such month, happy programming! techniques in SE artifacts is to enable the automatic generation of user documentation associated with that software project. By: Sandya Mannarswamy A number of text mining techniques have been employed to mine ‘stack overflow’ mailing lists to generate automatic user The author is an expert in systems software and is currently working with Hewlett Packard India Ltd. Her interests include compilers, documentation or FAQ documents for different software projects. multi-core and storage systems. If you are preparing for systems Regarding the identification of inconsistencies in the software interviews, you may find it useful to visit Sandya's LinkedIn requirements document, inconsistency detection techniques group ‘Computer Science Interview Training India’ at http://www. can be applied to source code comments also. It is a general linkedin.com/groups?home=HYPERLINK "http://www.linkedin.com/ expectation that source code comments express the programmer’s groups?home=&gid=2339182"
www.OpenSourceForU.com | OPEN SOURCE For You | September 2014 | 21 Exploring Software Guest Column
Anil Seth Exploring Big Data on a Desktop Getting Started with Hadoop Hadoop is a large scale, open source storage and processing framework for data sets. In this article, the author sets up Hadoop on a single node, takes the reader through testing it, and later tests it on multiple nodes.
edora 20 makes it easy to install Hadoop. Version 2.2 $ sudo systemctl start hadoop-namenode hadoop-datanode \ is packaged and available in the standard repositories. hadoop-nodemanager hadoop-resourcemanager FIt will place the configuration files in /etc/hadoop, with reasonable defaults so that you can get started easily. As You can find out the hdfs directories created as you may expect, managing the various Hadoop services is follows. The command may look complex, but you are integrated with systemd. running the ‘hadoop fs’ command in a shell as Hadoop's internal user, hdfs: Setting up a single node First, start an instance, with name h-mstr, in OpenStack $ sudo runuser hdfs -s /bin/bash /bin/bash -c “hadoop fs -ls using a Fedora Cloud image (http://fedoraproject. /” org/get-fedora#clouds). You may get an IP like Found 3 items 192.168.32.2. You will need to choose at least the drwxrwxrwt - hdfs supergroup 0 2014-07-15 13:21 /tmp m1.small flavour, i.e., 2GB RAM and 20GB disk. Add drwxr-xr-x - hdfs supergroup 0 2014-07-15 14:18 /user an entry in /etc/hosts for convenience: drwxr-xr-x - hdfs supergroup 0 2014-07-15 13:22 /var
192.168.32.2 h-mstr Testing the single node Create a directory with the right permissions for the user, Now, install and test the Hadoop packages on the virtual fedora, to be able to run the test scripts: machine by following the article, http://fedoraproject.org/ wiki/Changes/Hadoop: $ sudo runuser hdfs -s /bin/bash /bin/bash -c "hadoop fs -mkdir /user/fedora" $ ssh fedora@h-mstr $ sudo runuser hdfs -s /bin/bash /bin/bash -c "hadoop fs $ sudo yum install hadoop-common hadoop-common-native hadoop- -chown fedora /user/fedora" hdfs \ hadoop-mapreduce hadoop-mapreduce-examples hadoop-yarn Disable the firewall and iptables and run a mapreduce example. You can monitor the progress at It will download over 200MB of packages and take about http://h-mstr:8088/. Figure 1 shows an example running 500MB of disk space. on three nodes. Create an entry in the /etc/hosts file for h-mstr using the The first test is to calculate pi using 10 maps and name in /etc/hostname, e.g.: 1,000,000 samples. It took about 90 seconds to estimate the value of pi to be 3.1415844. 192.168.32.2 h-mstr h-mstr.novalocal $ hadoop jar /usr/share/java/hadoop/hadoop-mapreduce- Now, you can test the installation. First, run a script to examples.jar pi 10 1000000 create the needed hdfs directories: In the next test, you create 10 million records of 100 $ sudo hdfs-create-dirs bytes each, that is, 1GB of data (~1 min). Then, sort it (~8 min) and, finally, verify it (~1 min). You may want to clean Then, start the Hadoop services using systemctl: up the directories created in the process:
22 | September 2014 | OPEN SOURCE For You | www.OpenSourceForU.com www.OpenSourceForU.com | OPEN SOURCE For You | september 2014 | 23
Exploring Software Guest Column
$ hadoop jar /usr/share/java/hadoop/hadoop-mapreduce- examples.jar teragen 10000000 gendata $ hadoop jar /usr/share/java/hadoop/hadoop-mapreduce- examples.jar terasort gendata sortdata $ hadoop jar /usr/share/java/hadoop/hadoop-mapreduce- examples.jar teravalidate sortdata reportdata $ hadoop fs -rm -r gendata sortdata reportdata
Stop the Hadoop services before creating and working with multiple data nodes, and clean up the data directories:
$ sudo systemctl stop hadoop-namenode hadoop-datanode \ hadoop-nodemanager hadoop-resourcemanager $ sudo rm -rf /var/cache/hadoop-hdfs/hdfs/dfs/* Figure 1: OpenStack-Hadoop
Testing with multiple nodes The following steps simplify creation of multiple instances: Generate ssh keys for password-less log in from any node Delete the following lines from hdfs-site.xml: to any other node. In /etc/ssh/ssh_config, add the following to ensure that
Now, modify the configuration files located in /etc/hadoop. [fedora@h-mstr hadoop]$ cat slaves Edit core-site.xml and modify the value of fs.default.name h-slv1 by replacing localhost by h-mstr: h-slv2
24 | September 2014 | OPEN SOURCE For You | www.OpenSourceForU.com www.OpenSourceForU.com | OPEN SOURCE For You | september 2014 | 25 Guest Column Exploring Software
Launch instances h-slv1 and h-slv2 serially using $ sudo runuser hdfs -s /bin/bash /bin/bash -c "hadoop fs Hadoop-Base as the instance boot source. Launching of the -mkdir /user/fedora" first instance from a snapshot is pretty slow. In case the IP $ sudo runuser hdfs -s /bin/bash /bin/bash -c "hadoop fs addresses are not the same as your guess in /etc/hosts, edit / -chown fedora /user/fedora" etc/hosts on each of the three nodes to the correct value. For your convenience, you may want to make entries for h-slv1 You can run the same tests again. Although you are using and h-slv2 on the desktop /etc/hosts file as well. three nodes, the improvement in the performance compared to The following commands should be run from Fedora on the single node is not expected to be noticeable as the nodes h-mstr. Reformat the namenode to make sure that the single are running on a single desktop. node tests are not causing any unexpected issues: The pi example took about one minute on the three nodes, compared to the 90 seconds taken earlier. Terasort took 7 $ sudo runuser hdfs -s /bin/bash /bin/bash -c "hadoop minutes instead of 8. namenode -format" Start the hadoop services on h-mstr. Note: I used an AMD Phenom II X4 965 with 16GB $ sudo systemctl start hadoop-namenode hadoop-datanode RAM to arrive at the timings. All virtual machines and their hadoop-nodemanager hadoop-resourcemanager data were on a single physical disk.
Start the datanode and yarn services on the slave nodes: Both OpenStack and Mapreduce are a collection of interrelated services working together. Diagnosing problems, $ ssh -t fedora@h-slv1 sudo systemctl start hadoop-datanode especially in the beginning, is tough as each service has its hadoop-nodemanager own log files. It takes a while to get used to realising where to $ ssh -t fedora@h-slv2 sudo systemctl start hadoop-datanode look. However, once these are working, it is incredible how hadoop-nodemanager easy they make distributed processing!
Create the hdfs directories and a directory for user fedora By: Dr Anil Seth as on a single node: The author has earned the right to do what interests him. You can find him online at http://sethanil.com, http://sethanil. blogspot.com, and reach him via email at [email protected] $ sudo hdfs-create-dirs
OSFY Magazine Attractions During 2014-15
Month Theme Featured List buyers’ guide
March 2014 Network monitoring Security ------
April 2014 Android Special Anti Virus Wifi Hotspot Devices
May 2014 Backup and Data Storage Certification External Storage
June 2014 Open Source on Windows Mobile Apps UTMs fo SMEs
July 2014 Firewall and Network security Web Hosting Solutions Providers MFD Printers for SMEs
August 2014 Kernel Development Big Data solution Providers SSDs for Servers
September 2014 Open Source for Start-ups Cloud Android Devices
October 2014 Mobile App Development Training on Programming Languages Projectors
November 2014 Cloud Special Virtualisation Solutions Providers Network Switches and Routers
December 2014 Web Development Leading Ecommerce Sites AV Conferencing
January 2015 Programming Languages IT Consultancy Service Providers Laser Printers for SMEs
February 2015 Top 10 of Everything on Open Source Storage Solutions Providers Wireless Routers
24 | September 2014 | OPEN SOURCE For You | www.OpenSourceForU.com www.OpenSourceForU.com | OPEN SOURCE For You | september 2014 | 25 Developers Insight Improve Python Code by Using a Profiler
The line_profiler gives a line-by-line analysis of the Python code and can thus identify bottlenecks that slow down the execution of a program. By making modifications to the code based on the results of this profiler, developers can improve the code and refine the program.
ave you ever wondered which module is slowing b) For Fedora systems: down your Python program and how to optimise Hit? Well, there are ‘profilers’ that can come to sudo yum install -y mercurial python python3 python-pip your rescue. Profiling, in simple terms, is the analysis of a program Note: 1. I have used the ‘–y’ argument to to measure the memory used by a certain module, automatically install the packages after being tracked by frequency and duration of function calls, and the time the yum installer. complexity of the same. Such profiling tools are termed 2. Mac users can use Homebrew to install these packages. profilers. This article will discuss the line_profiler for Python. Cython is a pre-requisite because the source releases require a C compiler. If the Cython package is not found or is Installation too old in your current Linux distribution version, install it by Installing pre-requisites: Before installing line_profiler running the following command in a terminal: make sure you install these pre-requisites: a) For Ubuntu/Debian-based systems (recent versions): sudo pip install Cython
sudo apt-get install mercurial python python3 python-pip Note: Mac OS X users can install Cython using pip. python3-pip Cython Cython3
26 | September 2014 | OPEN SOURCE For You | www.OpenSourceForU.com www.OpenSourceForU.com | OPEN SOURCE For You | September 2014 | 27
Developers Insight
Cloning line_profiler: Let us begin by cloning the line_profiler source code from bitbucket. To do so, run the following command in a terminal: hg clone https://bitbucket.org/ robertkern/line_profiler
The above repository is the official line_profiler repository, with support for python 2.4 - 2.7.x. For python 3.x support, we will need to clone a fork of the official Figure 1: line_profiler output source code that provides python 3.x compatibility for line_profiler and kernprof. Note: I have combined both the commands in a single line separated by a semicolon ‘;’ to immediately show the hg clonehttps://bitbucket.org/kmike/line_profiler profiled results. Installing line_profiler: Navigate to the cloned You can run the two commands separately or run repository by running the following command in a terminal: kernprof.py with ‘–v’ argument to view the formatted result in the terminal. cd line_profiler kernprof.py -l compiles the profiled function in example.py line by line; hence, the argument -l stores To build and install line_profiler in your system, run the the result in a binary file with a .lprof extension. (Here, following command: example.py.lprof) a) For official source (supported by python 2.4 - 2.7.x): We then run line_profiler on this binary file by using the ‘-m line_profiler’ argument. Here ‘-m’ is followed by the sudo python setup.py install module name, i.e., line_profiler. Case study: We will use the Gnome-Music source code b) For forked source (supported by python 3.x): for our case study. There is a module named _connect_view in the view.py file, which handles the different views (artists, sudo python3 setup.py install albums, playlists, etc) within the music player. This module is reportedly running slow because a variable is initialised each Using line_profiler time the view is changed. Adding profiler to your code: Since line_profiler has been By profiling the source code, we get the following result: designed to be used as a decorator, we need to decorate the specified function using a ‘@profile’ decorator. We can do so Wrote profile results to gnome-music.lprof by adding an extra line before a function, as follows: Timer unit: 1e-06 s
@profile File: ./gnomemusic/view.py def foo(bar): Function: _connect_view at line 211 ..... Total time: 0.000627 s
Running line_profiler: Once the ‘slow’ module is Line # Hits Time Per Hit % Time Line Contents profiled, the next step is to run the line_profiler, which ======will give line-by-line computation of the code within the 211 @profile profiled function. 212 def _connect_view(self): Open a terminal, navigate to the folder where the ‘.py’ file 213 4 205 51.2 32.7 vadjustment = is located and type the following command: self.view.get_vadjustment() 214 4 98 24.5 15.6 self._ kernprof.py -l example.py; python3 -m line_profilerexample. adjustmentValueId = py.lprof vadjustment.connect( 215 4 79 19.8 12.6 'value-changed',
28 | September 2014 | OPEN SOURCE For You | www.OpenSourceForU.com www.OpenSourceForU.com | OPEN SOURCE For You | September 2014 | 29 Insight Developers
216 4 245 61.2 39.1 self._on_scrolled_win_change)
In the above code, line no 213, vadjustment = self.view.get_ vadjustment(), is called too many times, which makes the process slower than expected. After caching (initialising) it in the init function, we get the following result tested under the same condition. You can see that there is a significant improvement in the results (Figure 2). Figure 2: Optimised code line_profiler output
Wrote profile results to gnome-music.lprof to the total amount of recorded time spent in the function. Timer unit: 1e-06 s Line content: It displays the actual source code.
File: ./gnomemusic/view.py Note: If you make changes in the source code you Function: _connect_view at line 211 need to run the kernprof and line_profiler again in order to Total time: 0.000466 s profile the updated code and get the latest results.
Line # Hits Time Per Hit % Time Line Contents Advantages ======Line_profiler helps us to profile our code line-by-line, 211 @profile giving the number of hits, time taken for each hit and 212 def _connect_view(self): %time. This helps us to understand which part of our code 213 4 86 21.5 18.5 self._adjustmentValueId = is running slow. It also helps in testing large projects and vadjustment.connect( the time spent by modules to execute a particular function. 214 4 161 40.2 34.5 'value-changed', Using this data, we can commit changes and improve our 215 4 219 54.8 47.0 self._on_scrolled_win_change) code to build faster and better programs. Understanding the output Here is an analysis of the output shown in the above snippet. References Function: Displays the name of the function that is [1] http://pythonhosted.org/line_profiler/ profiled and its line number. [2] http://jacksonisaac.wordpress.com/2013/09/08/using- Line#: The line number of the code in the respective file. line_profiler-with-python/ [3] https://pypi.python.org/pypi/line_profiler Hits: The number of times the code in the corresponding [4] https://bitbucket.org/robertkern/line_profiler line was executed. [5] https://bitbucket.org/kmike/line_profiler Time: Total amount of time spent in executing the line in ‘Timer unit’ (i.e., 1e-06s here). This may vary from By: Jackson Isaac system to system. The author is an active open source contributor to projects Per hit: The average amount of time spent in executing like gnome-music, Mozilla Firefox and Mozillians. Follow the line once in ‘Timer unit’. him on jacksonisaac.wordpress.com or email him at % time: The percentage of time spent on a line with respect [email protected]
28 | September 2014 | OPEN SOURCE For You | www.OpenSourceForU.com www.OpenSourceForU.com | OPEN SOURCE For You | September 2014 | 29 Developers Insight Understanding the Document Object Model (DOM) in Mozilla
This article is an introduction to the DOM programming interface and the DOM inspector, which is a tool that can be used to inspect and edit the live DOM of any Web document or XUL application.
he Document Object Model (DOM) is a programming objects. For example, the document object that represents the interface for HTML and XML documents. It provides document itself, the tableObject that implements the special Ta structured representation of a document and it HTMLTableElement DOM interface to access the HTML defines a way that the structure can be accessed from the tables, and so forth. programs so that they can change the document structure, style and content. The DOM provides a representation of the Why is DOM important? document as a structured group of nodes and objects that have ‘Dynamic HTML’ (DHTML) is a term used by some vendors properties and methods. Essentially, it connects Web pages to to describe the combination of HTML, style sheets and scripts or programming languages. scripts that allow documents to be animated. The W3C DOM A Web page is a document that can either be displayed in working group is aiming to make sure interoperable and the browser window or as an HTML source that is in the same language-neutral solutions are agreed upon. document. The DOM provides another way to represent, store As Mozilla claims the title of ‘Web Application Platform’, and manipulate that same document. In simple terms, we can support for the DOM is one of the most requested features; in say that the DOM is a fully object-oriented representation of a fact, it is a necessity if Mozilla wants to be a viable alternative Web page, which can be modified by any scripting language. to the other browsers. The user interface of Mozilla (also The W3C DOM standard forms the basis of the DOM Firefox and Thunderbird) is built using XUL and the DOM to implementation in most modern browsers. Many browsers manipulate its own user interface. offer extensions beyond the W3C standard. All the properties, methods and events available for How do I access the DOM? manipulating and creating the Web pages are organised into You don’t have to do anything special to begin using the
30 | September 2014 | OPEN SOURCE For You | www.OpenSourceForU.com www.OpenSourceForU.com | OPEN SOURCE For You | September 2014 | 31 Insight Developers
Figure 1: DOM inspector Figure 2: Inspecting content documents DOM. Different browsers have different implementations of it, which exhibit varying degrees of conformity to the actual representing the HTMLFormElement gets its name property DOM standard but every browser uses some DOM to make from the HTMLFormElement interface but its className Web pages accessible to the script. property from the HTMLElement interface. In both cases, the When you create a script, whether it’s inline in a property you want is simply in the form object. script element or included in the Web page by means of a script loading instruction, you can immediately begin Interfaces and objects using the API for the document or window elements. Many objects borrow from several different interfaces. The This is to manipulate the document itself or to get at the table object, for example, implements a specialised HTML children of that document, which are the various elements table element interface, which includes such methods as in the Web page. createCaption and insertRow. Since an HTML element is Your DOM programming may be something as simple as also, as far as the DOM is concerned, a node in the tree of the following, which displays an alert message by using the nodes that makes up the object model for a Web page or an alert( ) function from a window object or it may use more XML page, the table element also implements the more basic sophisticated DOM methods to actually create them, as in the node interface, from which the element derives. longer examples that follow: When you get a reference to a table object, as in the following example, you routinely use all three of
these interfaces interchangeably on the object, perhaps unknowingly: Aside from the script element in which JavaScript is defined, this JavaScript sets a function to run when the var table = document.getElementById (“table”); document is loaded. This function creates a new element H1, var tableAttrs = table.attributes; // Node/Element interface adds text to that element, and then adds H1 to the tree for this for (var i = 0; i < tableAttrs.length; i++) { document, as shown below: // HTMLTableElement interface: border attribute if(tableAttrs[i].nodeName.toLowerCase() == “border”) table.border = “1”; } generally used most often in DOM programming. In simple terms, the window object represents something like the browser, and the document object is the root of the document itself. The element inherits from the generic node interface and, together, these two interfaces provide many of the methods and properties you use on individual DOM interfaces elements. These elements may also have specific interfaces These interfaces just give you an idea about the actual things for dealing with the kind of data those elements hold, as in that you can use to manipulate the DOM hierarchy. The object the table object example.30 | September 2014 | OPEN SOURCE For You | www.OpenSourceForU.com www.OpenSourceForU.com | OPEN SOURCE For You | September 2014 | 31 Developers Insight
Figure 3: Inspecting Chrome documents
Figure 4: Inspecting arbitrary URLs
easily accessed from scripts. An introduction to the DOM inspector The DOM inspector is a Mozilla extension that you can access from the Tools -> Web Development menu in SeaMonkey, or by selecting the DOM inspector menu item from the Tools menu in Firefox and Thunderbird or by Figure 5: Inspecting a Web page using Ctrl/Cmd+Shift+I in either application. The DOM inspector is a ‘standalone’ extension; it supports all toolkit The following are a few common APIs in XML and Web applications, and it’s possible to embed it in your own page scripting that show the use of DOM: XULRunner app. The DOM inspector can serve as a sanity • document.getElementById (id) check to verify the state of the DOM, or it can be used to • element.getElementsByTagName (name) manipulate the DOM manually, if desired. • document.createElement (name) When you first start the DOM inspector, you are presented • parentNode.appendChild (node) with a two-pane application window that looks a little like the • element.innerHTML main Mozilla browser. Like the browser, the DOM inspector • element.style.left includes an address bar and some of the same menus. In • element.setAttribute SeaMonkey, additional global menus are available. • element.getAttribute • element.addEventListener Using the DOM inspector • window.content Once you’ve opened the document for the page you are • window.onload interested in Chrome, you’ll see that it loads the DOM nodes • window.dump viewer in the document pane and the DOM node viewer in • window.scrollTo the object pane. In the DOM nodes viewer, there should be a structured, hierarchical view of the DOM. Testing the DOM API By clicking around in the document pane, you’ll see Here, you will be provided samples for every interface that the viewers are linked; whenever you select a new node that you can use in Web development. In some cases, the from the DOM nodes viewer, the DOM node viewer is samples are complete HTML pages, with the DOM access automatically updated to reflect the information for that node. in a the onclick event of Javascript.