Bytes for lunch

Visions of a web developer about software creations

How to Plot Simple Charts in R: A Step by Step Introduction

leave a comment »

Adventures in R

A couple of weeks ago I subscribed to a Coursera class on Data Science (if you don’t know what Coursera is, I really recommend to give it a look: it’s a great opportunity to get free university-quality education).

One of the tools used in the class was R, a powerful, object-oriented statistical programming language focusing on productivity and  relying on a huge ecosystem of packages, that actually allows you to do almost everything in data manipulation and statistics. And last but not least, it’s open source.

R standard installation includes around 30 packages that cover most common statistical and miscellaneous tasks as networking, input/ouput, etc.

Now that I’ve collected a very minimal set of skills to get started in plotting charts, I’d like to write down a quick note on my own experience.

 

Installing the tools

This step is really trivial: just surf to http://www.r-project.org/ Once there, you’ll grab all the things to get the tool installed.
Another tool I like is R-Studio, an IDE that gives R extra-powers (highly recommended).

 

First, let’s create a small dataset

For our example, let’s create a text file and name  it mydataset.csv. Comma Separated Values is a common format for exchanging data: it’s reasonably easy to understand, even if but there’s a price to pay in terms of performance and filtering respect to a database.

Now, paste this data to the file:

Year,Computer Sales
2010,1000
2011,1240
2012,1490

and save it.

In this simple dataset, we collected some data about Computer Sales in three years (a mere product of imagination!)

 

Plot an histogram in R

Now, launch R Studio  (or the R console).

 

Step 1: Loading the dataset into R

Type this command in the console:

mydata <- read.table("C:/mydataset.csv", header=T, sep=",")

 

Step 2: Draw a Bar Chart with this dataset

Now let’s draw the chart

barplot(mydata$Computer.Sales, main=”Computer.Sales”, xlab=”Years”, ylab=”Sales”,
names.arg=c(“2010″,”2011″,”2012″), border=”blue”,density=c(10,20,30))

 

What We Get

 

Simple bar chart in R

Computer Sales – R Barplot Tutorial

 

References

R is widely used among Data Scientist and Statisticians. With the increasing interest for all the topics about Data like Analytics, Big Data,I expect R to become a popular choice for a growing number of programmers and technicians.

R has a smooth learning curve and a vibrant ecosystem, and tons of documentation is nowadays available online.
Let me list a couple of useful links to get you started in the R ecosystem.

http://www.r-project.org/

http://www.rstudio.com/

http://www.r-bloggers.com/r-tutorial-series-r-beginners-guide-and-r-bloggers-updates/

 

Written by bytesforlunch

June 16, 2014 at 11:52 pm

Simple jQuery Dropdown button (open source code available)

leave a comment »

A couple days ago I faced a common user interface problem to solve. The design approach involved using a drop down button in a web form.
The idea was pretty simple, but I didn’t find any jquery plugin to accomplish my needs.

So… I decided to build my own. Simple and useful.

Here’s a picture of my drop down button in action:

jQuery Dropdown button in action

Source code available under the MIT license at Github, download here.

Written by bytesforlunch

June 13, 2013 at 6:37 pm

Open Data: my doubts on today’s most used ways for sharing data

leave a comment »

While Open Data is promising, I have doubts on how data is shared

Open Data is one of the best opportunity for people to really know facts about their lifes and how our world works. Open Data is a natural result from what Open Source means for software.

Let me shortly give you the idea at the heart of Open Data:

Open data is the idea that certain data should be freely available to everyone to use and republish as they wish, without restrictions from copyrightpatents or other mechanisms of control.

source: Auer, S. R.; Bizer, C.; Kobilarov, G.; Lehmann, J.; Cyganiak, R.; Ives, Z. (2007). “DBpedia: A Nucleus for a Web of Open Data”. The Semantic Web. Lecture Notes in Computer Science 4825. p. 722.doi:10.1007/978-3-540-76298-0_52ISBN 978-3-540-76297-3, Wikipedia

A lot of great guys in Open Data are facing issues about organizations, licensing and laws. This is a really important effort.
But, on the other hand, I don’t see an organic effort on the technical side. I admit my vision could be limited to what my eyes can see, but it seems there’s a lack of technology in how open data should be deployed.

Maybe not really a “lack of technology”, but it looks like the political arm runs faster than the technology one.
A practical example of what I mean? Yes: it’s unbelievable that a huge part of open data repositories are made of Excel files. It should be strictly avoided. Excel is a closed tool, at least use Open Office. Preferably, use CSV. JSON is even better.

I would like to start a discussion with people in Open Data focusing on which technologies are suitable for open data, offering my skills as a developer to find out pros and cons of each technology.

And you, what do you think about it? Am I missing something?

Written by bytesforlunch

May 21, 2013 at 11:47 pm

Posted in Open Data

JSAutoCaption: a simple JQuery plugin to automatically show alt and title image attributes

leave a comment »

Some days ago, I’ve been talking to a friend of mine when he gave me a nice idea. He was looking for a jQuery plugin to automatically extract alt and title attributes from an IMG tag and display them under the image.

Wow, such a funny task!

So I did it. It’s simple, and it plays right!

Here’s a couple of screenshots

JSAutoCaption-in-action

The text under the image has been automatically extracted from alt and title attributes of your image.

JSAutoCaption-in-action-html

HTML code

Like it? You can get it!

I’m so happy when I give even a little contribute to the open source community.

I release this plugin under the terms of the MIT License. So have fun.

Source code and live example available here, at the great JSFiddle.

Written by bytesforlunch

February 21, 2013 at 6:29 pm

Finest Tools: introducing AppleScript

leave a comment »

I bought my first Apple computer ten months ago, and a day doesn’t pass without discovering new exciting features of my Macintosh.

A few weeks ago I wrote a post about HyperCard, a great piece of software born from Bill Atkinson, Dan Winkler and Apple.
A few days after, I happily discovered that something similar already existed in my Mac, under a different name: AppleScript. In this post I’m gonna show you how to accomplish basic tasks with it.

Introducing AppleScript

ApplesScript is used to automate actions of the Macintosh operating system. You can script commands to run applications, open documents, browse the web, copy files, store informations, etc. Furthermore, AppleScript is perfectly suitable for database applications, searching and organizing data. One of the coolest things in AppleScript is it can be programmed in plain english, and best of all, it’s a built-in software that comes with your Macintosh.

How it works

A set of instructions is called “Script”. An interpreter executes the commands to interact with the applications and the system. These commands are written in AppleScript, an english-like computer language that contains verbs, nouns, adjectives, articles and other English elements we use everyday.

A script is created in AppleScript Editor, a free tool included wih the platform. It’s extremely simple to use, with a clear toolbar.

An important point to remember is that AppleScript considers everything an object, with properties that can be changed to model the behavior of your script.

Make your computer talk

Let’s try to create our first script. First, launch the AppleScript editor. A window like that one shown in figure will appear.

Now, write this command

SAY “Hello”

and press Run. Nice! Your computer talks.

Now let’s do something useful. Write this:

tell application “Finder” to open home

and press Run.

A window displaying your Home folder content will appear.

Now let’s see how to play with Google Chrome. We’re gonna open it and load a website.

tell application “Google Chrome”
    activate
    set theUrl to “http://www.pixcone.com&#8221;
end tell

Pushing a tool to the max

Even if we just scratched  the surface of AppleScript, I hope to stimulate users to be serious about pushing their expensive computer to the max.

As a practical example, I use AppleScript to automate the process of starting tools for coding. It’s a great accomplishment to automate the tedious process of opening your IDE, your browser with some preferred urls, a couple of Finder windows and a MAMP server.

Here my very simple script for starting coding tools:

tell application “TextMate”

   activate

   open “/Applications/MAMP/htdocs”

end tell

tell application “Cyberduck”

   activate

end tell

tell application “MAMP”

   activate

end tell

tell application “Google Chrome”

   make new window

   set URL of active tab of window 1 tohttp://localhost:8888/pixcone/&#8221;

   set myTab to make new tab at end of tabs of window 1

   set URL of myTab tohttp://www.pixcone.com&#8221;

   set musTab to make new tab at end of tabs of window 1

   set URL of musTab tohttp://www.stereomood.com&#8221;

end tell

say “Happy coding”

Enjoy Applescript!

Written by bytesforlunch

December 5, 2012 at 12:07 am

Posted in AppleScript

Parsing JSON string in javascript

leave a comment »

All we know how JSON is good at describing objects. It is compact and clear, and brings a lot of benefits when used as a transport vehicle for informations between applications. When I say JSON my mind immediately think about REST. Yes, such a great DUO: REST+JSON.

That being said, using JSON requires for an application to parse JSON strings.
In this post I’m gonna talk about parsing strings to JSON objects.

Option 1: Eval() (is not always the evil)

When parsing json strings, a common choice is using the javascript function Eval().

A lot of programmers consider using the  function eval a bad practice. All around the Internet, it seems there’s a psychosis about it.
I argue that this is not always the truth. Actually, it depends on the context. As everything in software, you must know it before use it.

Eval is a javascript function that evaluates an expression. It can be used to run a piece of code, or to evaluate an expression.
Calling Eval to parse a json string invokes the compiler, and the result is a native javascript object that is naturally understood by javascript.
Yes, Eval has some points to be taken in consideration.

First, there’s a security issue. Invoking Eval on a piece of code means to execute it. So be sure that code is trusted. Consider where that json is coming from, and do the math.

var myObject = eval('(' + myJSONtext + ')');

I think  eval() is a good choice to parse json string, especially when you trust the origin of the string.

Option 2: JSON.parse

This is the most suggested way to parse json strings.
Please note that JSON.parse uses the eval() at its core, but it does some control on the input, so it’s considered better.
JSON.parse is supported by the majority of today’s browser, but if you need to provide a backward compatibility, you can download the famous Douglas Crockfors’s library.

Option 3: JQuery

JQuery has a solution for almost everything in the javascript world. Check this:

jQuery.parseJSON(json-string);

Do you wonder if JQuery uses eval() internally?

Well, we just need to see the JQuery code.


parseJSON: function( data ) {
if ( !data || typeof data !== "string") {
return null;
}

// Make sure leading/trailing whitespace is removed (IE can’t handle it)
data = jQuery.trim( data );

// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}

// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, “@” )
.replace( rvalidtokens, “]” )
.replace( rvalidbraces, “”)) ) {

return ( new Function( “return ” + data ) )();

}
jQuery.error( “Invalid JSON: ” + data );
}

(taken from JQuery.com)

Ok, as we can see, JQuery used JSON.parse except for old browsers, where it uses this construct:

return (new Function(‘return ‘ + data))();

Using new Function makes the code operating only on its local variables, giving it a more secure context.

Conclusion

JSON support is officially part of JavaScript since Decembre 2009, when ECMAScript Programming
Language Standard – Fifth Edition was adopted by the ECMA General Assembly.

Even if we would like our users to be using modern browser, sometimes we need to cope with backward compatibility. For most cases, json2.js is the best choice.

Written by bytesforlunch

November 15, 2012 at 9:12 pm

Posted in Javascript, JQuery

A taste of Semantic Web

with one comment

For sure, Semantic Web is one of the most heard word on the Internet.
But how many people can really use it? Due to its steep learning curve and its manifold nature, penetration of semantic techniques in web development is still poor.
In this post I’m gonna show you how to implement simple Semantic techniques in a web page.

Why the Semantic Web?

Everyday, the most of information we get from the web comes by algorithms that mainly look at text. This is because the majority of web pages are made up by human-readable words.

The base principle of the semantic web is to provide metadata for giving text a meaning. Several techniques are on the table, the one we’re gonna see is Microdata.

Microdata consists of annotating the DOM of a web page with  scoped key/value pairs, that give meta-informations about the thing they’re related to.

Let’s see an example.

Some days ago I’ve published a web application (PixCone) and I wanted to add information about myself using semantic definitions.

As a side note, please keep in account that on summer 2011 the big three (Google, Yahoo and Bing) launched an initiative to endorse Schemas and Microdata as key technologies for their search algorithms. You do the math…

A simple example: the author section

Before to dig into the example, we should spend a few words on defining the concept of Schema.

Annotating html tags with microdata means to add new attributes to describe the entity. Most of times these attributes already exist, and must be conformed to a particular Schema. A schema is a definition of an object. See here to read more.

In the next piece of code we’re going to add semantic data to the author section of a page. This is a relevant chunk of informations because tells the world who created what.

Let’s give a look at the code

<div>
<div itemscope itemtype=”http://schema.org/Person”&gt;
<span itemprop=”name”>Francesco Ricceri</span><br>
<span itemprop=”title”>Software Developer</span><br>
<span itemprop=”worksFor”>Pix Cone</span>
</div>
</div>

Job completed! We have defined a few properties of a “Person” schema.

The line n.2 declares the schema which the object belongs to. In this case we’re giving informations about the author, which is a Person.
Person is defined as a schema. More info here.

Lines 3-4-5 are pretty easy to understand.

With a few lines of code, we made this section to be understood by machines. Great! This is your first step in the world of semantic web.

Microdata in action

One of the Chrome plugins I find absolutely useful is Semantic Inspector. It allows to find semantic data in a web page.

Here’s what I see in the Pixcone homepage.

PixCone-Using-Semantic-Inspector-plugin

By clicking on the Semantic Inspector, we’ll see semantic informations sniffed by the plugin:

pix-cone-with-semantic-data

Linkography

Now some links I consider a good starting point.

Schema.org

Microdata

Written by bytesforlunch

November 6, 2012 at 11:46 pm

Posted in Semantic Web

Follow

Get every new post delivered to your Inbox.