BBC News: Indonesia traffic jam: 12 die in Java gridlock during Ramadan

Indonesia traffic jam: 12 die in Java gridlock during Ramadan –

R: Installing Packages with Dependencies

Usually installing packages in R is as simple as

install.packages("package name")

However sometimes you will run into errors. This could be due to the fact that the package you are trying to install has what is known as a dependency. What this means is that in order for the package to properly install and run, it requires another package to  already be installed.

You can think of this like trying to install an add-on for Excel like PowerQuery without having Excel installed in the first place. Clearly it would not work.

Now if you are lucky enough to know exactly what package(s) needs to be installed first, then you can simply install it and be on your way. However, most of the time we are not that lucky. And in the case of some packages, you may need to install up to a dozen packages up front to get it to work.

The easier way, just add the following syntax to your command

install.packages("package name", dependencies = TRUE)

Remember in R, Boolean (TRUE and FALSE) must be all capital letters or R will not recognize them as Boolean.

If you are using RStudio, you can install the package using the GUI

At the top, got to Tools and select Install Packages from the drop down.


Start typing the package you want in the box, it will pop up in the window


Finally, make sure install dependencies and checked and click install.


R: Manually entering data

You can use the data frame edit() function to manually enter / edit data in R.

Start by creating a data frame.

Note I am initializing each of the columns to datatype(0). This tells R that I while I want the name column to be a character and the age column to be numeric, I am leaving the size dynamic. You can set size limits during the initialization phase if you so choose.

 dfe <- data.frame(name=character(0), age = numeric(0), jobTitle = character(0))

Now, let’s use the edit() function to add some data to our data frame

dfe<- edit(dfe)

When the new window pops up, fill in the data and simply click the X when you are done


You may get warning messages when you close out your edit window. These particular messages I got simply informed me that name and jobTitle were set as factors by R. Remember in R, warnings just want you to be aware of something, they are not errors.

Now if you run dfe, you can see your data frame


By running the edit() function again, you can edit the values that currently exist in the data frame.  In this example I am going to change Philip’s age from 28 to 29

If you want to add a column to the data frame, just add data to the next empty column


You can just close out now and rename the column in R, or just click on the column header and you will be able to rename it there.


Now we have a new column listing pets

  name   age jobTitle pet
1 Ben    42  Data Sc  cat
2 Philip 29  Data Ana dog
3 Julia  36  Manager  frog

You can use the edit() function to manually edit existing data sets or data imported from other sources.

Below, I am editing the ChickWeight data set


R: Connecting to SQL Server Database

You can query data from a SQL Server database directly from R using the RODBC package.


First you need to form a connection

##connection string
cn <- odbcDriverConnect(connection="Driver={SQL Server Native Client 11.0};server=localhost; database=SSRSTraining;trusted_connection=yes;")

We use the odbcDriverConnect() function. Inside we pass a connection = value

Driver = {SQL Server Native Client 11.0};  — this is based on the version of SQL Server you have

server=localhost;  — I used localhost because the SQL Server was on the same computer I was working with. Otherwise, pass the server name

database=SSRSTraining; — name of database I want to work with

trusted_connection=yes; — this means I am able to pass my Windows credentials.

If you don’t have a trusted connect pass the user Id and password like this

uid = userName; pwd = Password;

Note each parameter is separated by a semicolon

Query the database

> ##passes query to SQL Server
> df <- sqlQuery(cn, "select * FROM [SSRSTraining].[dbo].[JobDataSet]")
> head(df)

    Name              Job Hours Complete
1  Sally Predictive Model     1        n
2 Philip      Maintanence    10        n
3    Tom    Ad-hoc Report    12        y
4    Bob             SSRS     3        y
5 Philip         Tableau      7        n
6    Tom         Tableau      9        n

using sqlQuery() – pass through the connection string (cn) and enclose your query in ” ”




R: Importing Excel Files

To work with Excel files in R, you can use the readxl library


Use the read_excel() function to read and Excel workbook

> library(readxl)
> ## read excel file
> df1 <- read_excel("r_excel.xlsx")
> head(df1)
# A tibble: 6 x 4
  Name   Job              Hours Complete
  <chr>  <chr>            <dbl> <chr>  
1 Sally  Predictive Model    1. n      
2 Philip Maintanence        10. n      
3 Tom    Ad-hoc Report      12. y      
4 Bob    SSRS                3. y      
5 Philip Tableau             7. n      
6 Tom    Tableau             9. n

By default, read_excel() reads only the first sheet in the Excel file. To read other sheets using the sheet key word.

> ## read  sheet 2
> df2 <- read_excel("r_excel.xlsx", sheet =2)
> head(df2)

# A tibble: 6 x 2
  Animal Num_Legs
  <chr>     <dbl>
1 Dog          4.
2 Duck         2.
3 Snake        0.
4 Horse        4.
5 Spider       8.
6 Human        2.

The next example, we are reading range B2 – C6 on sheet 1 (same as Excel’s range function)

> ## read sheet 1, range B2 - C6
> df3 <- read_excel("r_excel.xlsx", sheet =1, range = "B2:C6")
> df3
# A tibble: 4 x 2
  `Predictive Model`   `1`
  <chr>              <dbl>
1 Maintanence          10.
2 Ad-hoc Report        12.
3 SSRS                  3.
4 Tableau               7.

In this last example, we are importing only the first 4 rows on sheet 2

> ## read sheet 2, first 4 rows only
> df4 <- read_excel("r_excel.xlsx", sheet = 2, n_max = 4)
> df4
# A tibble: 4 x 2
  Animal Num_Legs
  <chr>     <dbl>
1 Dog          4.
2 Duck         2.
3 Snake        0.
4 Horse        4.

Python: Simulate Blockchain Mining

In my earlier tutorial, I demonstrated how to use the Python library hashlib to create a sha256 hash function. Now, using Python, I am going to demonstrate the principle of blockchain mining. Again using BitCoin as my model, I will be trying to find a nonce value that will result in a hash value below a predetermined target.

We will start by simply enumerating an integer through our sha 256 hash function until we find a hash with 4 leading zeros.

I used a while loop, passing the variable “y” through my hashing function each time the loop runs. I then inspect the first 4 digits [:4] of my hash value. If the first four digits equal 0000 then I exit the loop by setting the found variable to 1

(*note, a hash value is a string – hence the need for quotes around ‘0000’)


As you can see in the version above, it took 88445 iterations to find an acceptable hash value

Now, using the basic example of a blockchain I gave in an earlier lesson, let’s simulate mining a block


You’ll see, I am now combining the block number, nonce, data, and previous hash of my simulated block and passing it through my encryption function.  Just like in BitCoin, the only value I change per iteration is the Nonce. I keep passing my block through the hashing function until I find the Nonce that gives me a hash below the target.


Now, let’s lower the target value to 6 leading zeros. This should result in a longer runtime to get your hash


To measure the run time difference, let’s add some time stamps to our code


So, I am using the timestamp function twice. D1 will be our start time, d2 will be our end time, and I am subtracting d1 from d2 to get our elapsed time. In the example below, my elapsed time was 5 secs


Now, let’s bump the target down to 7 leading zeros. Now this brings my elapsed computing time to 20 minutes. That is a considerable commitment of resources. You can see why they call it a “proof of work” now.



Blockchain: Mining

This was, without a question, the most confusing aspect of blockchain to me when I first tried to learn it. Maybe it was because all the buzz around BitCoin mining. I usually find that when a topic becomes popular, misinformation spreads just as fast, if not faster, than actual information.

In an attempt to explain this topic I am going to be using BitCoin as my primary example. I am doing this mainly because I am sure that is where most of you first heard of the term blockchain mining. I will however, begin with a more generic explanation.

First off, let us separate blockchain mining from the idea of financial reward. Yes, in BitCoin, the miner who successfully mines a block is rewarded with BitCoin, but that is not a required part of a blockchain environment.

Mining, at its simplest form, just means successfully adding a new block to the blockchain.

So why can’t you just add a new block like you add a new element to a list or array in any other programming language? This has to do with the decentralized nature of blockchain. Since there is no centralized authority, blockchains rely on group consensus to verify that a new block added to the chain is valid. Keep in mind, this group is made up of anonymous nodes all over the world who do not know each other, and have no good reason to trust one another.

So, if you were to add a new block to the chain, the rest of the chain would need a mechanism in place that gives them time to update their copy of the chain and verify the block you added is good. So effectively we need a pause button.

How do we do that fairly and in a random manner that doesn’t allow for gaming of the system? We force anyone wishing to add a new block to show what is known as proof of work. Proof of work is proof that the person wishing to add the new block has completed a complex mathematical puzzle that required some level of resource allocation on their end. This effectively means they have skin in the game. There is a “cost” associated on their end. This “cost” deters the typical denial of service or blasting type attachk.

In BitCoin the mining process goes like this:

  1. Bob wants to buy a guitar from Philip. They agree on a price of .2 BitCoin and through what is known as their BitCoin wallet a transaction is sent out to the BitCoin universe. A BitCoin wallet is a software client that the person trading with BitCoin uses. From the end user’s point of view, it is a lot like a Paypal type interaction.
  2. Once the transaction is out in the ether, nodes (computers) known as BitCoin miners verify the transaction using a set of established rules built into the BitCoin software they are all running. These rules verify sender and receiver public keys, timestamps, etc. Once verified, the transaction is put into a queue.
  3. Next the bitcoin miners build a new block. The goal is to make their new block the next block in the chain. This block with contain the following items:
    1. Block number – just the next number in the line
    2. Previous Hash – this the hash value of the current last block in the chain
    3. Transactions – they will fill the block with verified transactions from the queue
    4. A timestamp
    5. The Nonce

On a side note – BitCoin only releases a block every 10 minutes. This is a design decision made by the makers of BitCoin, this is not a requirement of Blockchain

Once they have all of that information, they pass their block into a hashing algorithm and get a hash for their new block – This is where mining gets interesting

You see, not any old hash will do. In order for the block to be added to the chain, the hash must be less than the target hash.

The target hash is established by the initial creator of the blockchain. It can be whatever they chose. In the case of BitCoin, the target hash is actually programmed to drop lower and lower every couple thousand blocks.

Okay, so what is the big deal about trying to get below the hash?

Let’s consider this problem using a 6 digit number. (keep in mind that sha256 uses a 64 digit hexadecimal number – much bigger).

So we all agree that a hash is nothing more than creating a random number. Sure it looks funny in hexadecimal, but it can be converted to a base 10 number we all understand.

So, when I pass anything into my imaginary 6 digit hashing function, I can expect 1 million results, (if I only consider positive numbers) – 000,000 to 999,999

Now, let’s set a target for our hash. Let’s say that in order for a hash to be under the target, it must have a first digit of 0. I know what you are thinking – big deal!  Well, actually, it kind of is. We have just gone from 1 million possible hashes to 100,000.  We have effectively made 9 out of 10 available hashes invalid. We can now only accept 000,000 – 099,999. Now, let’s make the first 3 digits of our target 0.  So now we have gone from 1 million possible hashes to 1000. 1000/1,000,000 = .001. So every time you run a hashing function, you now have a 0.1% chance of getting a valid hash.

Now think about our 64 digit hexadecimal number. It has a maximum value of 18,446,744,073,709,551,615 when converted to base 10. So If I made a requirement for the first 6 digits to be 0, we are now looking at: 99,999,999,999,999/18,446,744,073,709,551,615


Every time you run your hashing function, you have a 0.00054% chance of getting one below the target. So as you can see, in order to get a hash below the target, you will most likely have to use a brute force approach.

And that is what miners do. In fact the current difficultly related to finding a hash below the target in BitCoin has led to hundreds of thousands of nodes teaming up together to find a good hash in a brute force manner.

The way they find the hash is through the Nonce. You see, if you pass the word “dog” through my imaginary hash, you will get 123456. If you pass it to my hash 1 million times, you will get 123456 1 million times. So how it working in Blockchain, is we add the nonce to the hash, so dog+1 will give us 879602 and dog+2 will give us 258665. We will repeat this, enumerating the nonce until we get a good hash: dog+28549 gives us 000587. The nonce that gave us that hash 28549 – is called the golden nonce.

And in the world of BitCoin, once you have a golden nonce, you have your proof of work. You can now place your block on the chain.

It is called a proof of work, because other nodes on the blockchain  can very quickly verify your work. They just pass your block with your golden nonce and they will get a hash of 000587, which is below the target. When enough nodes have verified your proof of work ( a consensus), your block becomes locked into the chain, it can no longer be changed or removed.

Okay, so what about the reward BitCoin miners get? Well, built into the BitCoin algorithm, each block mined with worth an ever decreasing number of BitCoin. At the time of this writing, I believe a mined block is worth 12.5 BitCoins. On top of that, the miners also get transaction fees from the people wishing to buy something with BitCoin. In the example above, Bob might offer up .1 BitCoin as a transaction fee as encouragement for some miner to put their transaction into the Blockchain. Keep in mind, there is no bank here, no centralized entity. So the transaction fee is the fee you pay help encourage total strangers to use their time and electricity to verify and move your transaction into the blockchain.

I promise to create another lesson diving deeper into transaction fees, until then, I hope this offers up at basic understanding of how mining works.

Python: Create a Blockchain Hash Function

If you are at all like me, reading about a concept is one thing. Actually practicing it though, that helps me to actually understand it. If you have been reading my blockchain tutorial, or if you came from an outside tutorial, then you have undoubtedly read enough about cryptographic hashes.

Enough reading, let’s make one:

( if you are unfamiliar with crytographic hashes, you can reference my tutorial on them here: Blockchain: Cryptographic Hash )

For this example, I am using the Anaconda Python 3 distribution.

Like most things in Python, creating a hash is as simple as importing a library someone has already created for us. In this case, that library is: hashlib

So our first step is to import hashlib

import hashlib

Now let us take a moment to learn the syntax require to create a cryptographic hash with hashlib. In this example, I am using the SHA 256 hashing algorithm. I am using this because it is the same algorithm used by BitCoin.

Here is the syntax used


To understand the syntax, we are calling the hashlib method sha256(): hashlib.sha256()

Inside the brackets, we are entering the string we want to encode in the hash. Yes it must be a string for this function to work.

Still inside the brackets we use the method .encode() to (surprise, surprise) ENCODE the string as a hash

Finally, I added the method .hexdigest() to have the algorithm return our hash in hexadecimal format. This format will help in understanding future lessons on blockchain mining.

So in the example below, you can see that I assigned the variable x the string ‘doggy’. I then passed x to our hash function. The output can be seen below.


Now a hash can hold much more than just a simple word. Below, I have passed the Gettysburg Address to the hashing function.

(**note the ”’ ”’ triple quotes. Those are used in Python if your string takes up more than one line **)


Now I try passing a number. You will notice I get an error.


To avoid the error, I turn the integer 8 into a string with the str() function


Below I concatenation a string and an integer.


Last I want to show the avalanche effect of the hash function.


By simply changing the first letter from an uppercase T to a lowercase t the hash changes completely. This is a requirement for hashing functions. If the hash did not change dramatically from a small change to the string, it would be easy to reverse engineer the hash. This is known as the avalanche effect.



SSRS: Drill down

Let’s make the report at little more readable and interactive.

We are going to do a drill down on the names in our report. This mean when the report first opens, you will only see one row for each name. If you want to see the details of that person, you can click on a + by their name and the details for that person will pop down like an accordion.

Below your report design window, you should see another window called Row Groups

Go to the area marked Details (green arrow) and right click – Group Properties…


Click Visibility > Hide > Display can be toggled.

(Note I am selecting Name1 not Name. If you remember Name was the column we hid. Name1 is the column created when we created the Parent Group)


Now when you open your report, you will see it is in drill down format.