Create Graph using Highcharts from a CSV File

1. Add these JavaScript inclusions in the head of your page

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script><script type="text/javascript" src="http://code.highcharts.com/highcharts.js"></script>

2. Add the JavaScript to initialize the chart on document ready

$(document).ready(function () {
    var options = {
        chart: {
            renderTo: 'container',
            type: 'line',
            width: 800,
            height: 450
        },
        title: {
            text: 'Cabadbaran, Agusan del Norte'
        },
        subtitle: {
            text: 'Source:CSU Phil-LiDAR 1',
            x: -20
        },
        xAxis: {
            categories: [],
            minTickInterval: 15,
            TickInterval: 15,
            tickmarkPlacement: "on",
            labels: {
                padding: 10,
                align: "center",
                style: {
                    fontSize: "10px"
                }
            }
        },
        yAxis: [{ //primary y axis 
            min: 0,
            max: 50,
            title: {
                text: "Rainfall Intensity, mm/hr."
            },
            reversed: !0,
            plotLines: [{
                value: 0,
                width: 1,
                color: "#808080"
            }],
            plotBands: [{
                color: '#86e3e7',
                from: 0,
                to: 2.5,
                label: {
                    text: 'Light',
                    align: 'left',
                    x: 10
                }
            }, {
                color: '#8aa7fd',
                from: 2.5,
                to: 7.5,
                label: {
                    text: 'Moderate',
                    align: 'left',
                    x: 10
                }
            }, {
                color: '#8686dc',
                from: 7.5,
                to: 15,
                label: {
                    text: 'Heavy',
                    align: 'left',
                    x: 10
                }
            }, {
                color: '#fed88d',
                from: 15,
                to: 30,
                label: {
                    text: 'Intense',
                    align: 'left',
                    x: 10
                }
            }, {
                color: '#fe9686',
                from: 30,
                to: 100,
                label: {
                    text: 'Torrential',
                    align: 'left',
                    x: 10
                }
            }]
        }, { //secondary y axis 
            max: 10,
            min: 0,
            title: {
                text: "Accumulated Rainfall, mm"
            },
            plotLines: [{
                value: 0,
                width: 1,
                color: "#808080"
            }],
            opposite: !0,
            reversed: !1
        }],
        gridLineDashStyle: 'solid',
        series: []
    };
    $.get('https://dl.dropboxusercontent.com/u/75734877/AGUSAN_DEL_NORTE-CABADBARAN-RAIN2-.csv', function (data) {
        var lines = data.split('\n');
        options.series.push({
            name: "Rainfall Intensity",
            data: [],
            tooltip: {
                valueSuffix: "  mm/hr."
            },
            color: "#0000ff"
        }, {
            name: "Accumulated Rainfall",
            data: [],
            tooltip: {
                valueSuffix: " mm"
            },
            yAxis: 1,
            color: "#ff0000"
        });
        $.each(lines, function (lineNo, line) {
            var items = line.split(',');
            if (lineNo > 0) {
                $.each(items, function (itemNo, item) {
                    if (itemNo === 0) {
                        options.xAxis.categories.push(item);
                    } else if (itemNo === 2) {
                        options.series[0].data.push(parseFloat(item));
                    } else if (itemNo === 3) {
                        options.series[1].data.push(parseFloat(item));
                    }
                });
            }
        });
        var chart = new Highcharts.Chart(options);
    });
});

3. Add the container

<div id="container" style="width: 800px; height: 450px; margin: 0 auto; border: 2px solid #343434;border-radius:5px"></div> 

I also made some quite styling before the chart is loaded.

#container {
    background-image: url('hex-loader.gif');
    background-repeat:no-repeat;
    background-position:center center;
}

Demo

The code is based on this JSFiddle with a little modification to suit what I want.

Schedule Loading of Shapefile into a PostgreSQL Database

The code below automatically loads the shapefile found in a certain directory into a PostgreSQL database within a given interval(in this example 2 minutes).

Downside (in which I'm trying to figure out):
What if the filename of the shapefile changes?

Anyway, this suits of what I need right now.

__author__ = 'Matt'
import os
from django.db import connection
from django.contrib.gis.utils import LayerMapping
from .models import FloodHazard
import datetime
import time
import logging
from apscheduler.scheduler import Scheduler

logging.basicConfig()
# Start the scheduler
sched = Scheduler()
sched.daemonic = False
sched.start()

#ogrinspect evidensapp/data/flood_hazard/FloodHazard.shp FloodHazard --srid=32651 --mapping --multi
# Auto-generated `LayerMapping` dictionary for FloodHazard model
floodhazard_mapping = {
    'hazard': 'Hazard',
    'date_field': 'Date_',
    'geom': 'MULTIPOLYGON'
}

bound_shape = os.path.abspath(os.path.join(os.path.dirname(__file__),
                                           'data/flood_hazard/FloodHazard.shp'))
exist = os.path.isfile(bound_shape)

if exist:
    def run(verbose=True):
        try:
            cursor = connection.cursor()
            cursor.execute("TRUNCATE TABLE evidensapp_floodhazard RESTART IDENTITY")
            lm = LayerMapping(FloodHazard, bound_shape, floodhazard_mapping,
                              transform=False, encoding='iso-8859-1')
            lm.save(strict=True, verbose=verbose)
            print(datetime.datetime.now())
            print(exist)
            time.sleep(60)

        except FloodHazard.DoesNotExist:
            lm = LayerMapping(FloodHazard, bound_shape, floodhazard_mapping,
                              transform=False, encoding='iso-8859-1')
            lm.save(strict=True, verbose=verbose)
            print(datetime.datetime.now())
            time.sleep(60)

    # Schedules job_function to be run every 2 minutes
    sched.add_interval_job(run, minutes=2)

else:
    print(exist)
    sched.shutdown()

Change the model name and path/directory. As you noticed that if the table has an existing rows, it performed a TRUNCATE query to save memory and the system that I'm developing need the latest Flood Hazard Map. And also, it gives an error if you load a shapefile on the table with existing rows (Why?).

Next task to do is, check if the file has been modified otherwise stop the schedule.

This is based on this question and using Advanced Python Scheduler and LayerMapping utility of Django.

I want to grow up my child like me...

...but minus the immaturity!
Well, of course let's have girlfriend first. HAHA

We had a short trip today to Carmen, Agusan del Norte to celebrate Father's Day. My father is gone but will always be remembered. Anyway, it was fun.

Here are our photos below:










Pantsu on EOS!!!


So, this game is GOOD!!! Why?

  1. PANTSU
  2. Characters can jump
  3. Anime-like characters
  4. Skill has cooldown
  5. Transportation
  6. Pets
  7. Lots of Quest (with hints and location indicator)
  8. Has 5 Classes and Subclasses
  9. Soul System(After each encounter with a monster or an evil spirit, you can receive a Chaos Soul from the fallen creature.)
  10. Dungeon (Solo, Party, Infinite)
  11. PVP is FAIR(stats and gear are normalized between all participating players for a fair fight. )
  12. Lots of skill (cool animation)


Downside:

  1. Gender lock classes
  2. Burns my laptop (HAHA; 4GB RAM, 4GB Graphics, i5) reaches up to 80C
  3. Movement Controls
  4. Awkward looking Rouge Class (HAHA)


Actually, I just played Echo of Soul today and my character is an Archer -> Huntress and lvl. 15. I'll update this soon.





Off-topic: 

"Shame", "For the Watch"

Holy macaroon!!! What just happened?!! HAHA

Game of Thrones Season 5 is over!!!

To sum it up (Ep.10):

1. Body Count: 6 deaths plus Stannis' army.
Winter is coming and the Night's Watch just killed Jon Snow, my sister cries hard and it's funny. Stannis' fate is unexplainable, nonsense (I can't find the right adjective for it).


2. Walk of Atonement
I love Cersei's look after the "new" member of Kingsguard lift him.  


3. Daenerys being sorrounded by Dothraki warriors.
Is she gonna be raped again? 


4. Arya's brutality
Gruesome!!!! but good job Arya Stark! :)

5. Theon has grown some balls, finally.
Yeah! Prevent Sansa from death by pushing Myranda and then jump off the castle. They're at least alive right? :D



Next season will be WAR! Hope so. Now the countdown starts.



Something worth posting...

I'm not that religious type of person. I often go to church, in fact I've never been to church this year. Something's wrong with me. But I'm always grateful for all the blessings that God has given me, and also for all the problems and trials. I won't be this type of person today if I did not experience those things. 

I'm sharing Owl City's new song "My Everything" because it's a very good song and the lyrics is simple yet  powerful.

"My Everything"

When my hope is lost 
and my strength is gone
I run to you and you alone
When I can't get up and I can't go on
I run to you and you alone
'Cause you're my light in the dark
and I sing with all of my heart

Hallelujah
My almighty God divine
Hallelujah
I am yours and you are mine
This is all I know I will say
Hallelujah
Hallelujah
You're my everything

When I'm plagued with pain
and filled with fear
I run to you and you alone
When my days are few
and death is near
I run to you and you alone
'Cause you're my light in the dark
and I sing with all of my heart

Hallelujah
My almighty God divine
Hallelujah
I am yours and you are mine
This is all I know I will say
Hallelujah
Hallelujah

When trouble comes and goes
and when the cold wind blows
I lift my hands up, I lift my hands up
When sorrow knocks me down
and you pick me off the ground
I lift my hands up, I lift my hands up

And I sing, Hallelujah
My almighty God divine
Hallelujah
I am yours and you are mine
This is all I know I will say

Hallelujah
By the grace of God above
Hallelujah
Our shining light to shine above
This is all I know I will say
Hallelujah
Hallelujah
This is all I know I will say
Hallelujah
Hallelujah
You're My everything

Ohh Ohh, You're my everything

Styling Vector Layer Based on Attributes

/*START OF STYLING THE VECTOR LAYER*/
var o = {
    getColour: function (e) {
        var t = e.attributes.hazard;
        return "Low" == t ? "#FFFF00" : "Medium" == t ? "#FFA500" : "#ff0000"
    }
};
var c = {
    fillOpacity: .3,
    strokeColor: "${getColour}",
    strokeWidth: 0,
    strokeOpacity: 0,
    fillColor: "${getColour}"
};

var b = new OpenLayers.Style(c, {
    context: o
});

var v = new OpenLayers.StyleMap({
    "default": b
});
/*END OF STYLING THE VECTOR LAYER*/

var GeoJSONLayer = new OpenLayers.Layer.Vector("GeoJSON", {
    styleMap: v,
    strategies: [new OpenLayers.Strategy.Fixed(), filterStrategy],
    renderers: ['Canvas', 'SVG', 'VML'],
    protocol: new OpenLayers.Protocol.HTTP({
        url: "{% static "js/floodmap.txt" %}",
        format: new OpenLayers.Format.GeoJSON()
    })
});

Change the attribute name based on your layer's attribute. In my case, the styling of my layer is based on "hazard" which is "Low, Medium and High". Then add "styleMap" property in your layer.


#FFFF00, #FFA500, #ff0000 are hex colors representing the type of hazard as shown in the image above.


Divert




First, I was kinda disappointed with myself because I guess my effort is not enough. Anyway, I'll just focus on the things that I have right now which is my work and studies. Let's make ourself better after a sad event that just happen. :)

"Some things are just not meant to happen, 'cause some things need hard work and effort."


If she's not important to me, I can't possibly write this and it would end up like sh*t. HAHA

We had our moments and it ended quite fast. No hard feelings though. Again, I'll wait and be hopeful! It was nice knowing her and I don't have any regrets at all. She's a very fine lady. I can't say anything bad about her. I thank her for her honesty.

~fin




KOWTS #3


"To live with no regrets is to live happily."

Generate Random Quotes from a Text File

So to do that, you need a text file full of quotes. HAHAHA
Separated by new line.

$('#btn_modal').click(function () {
    var num = 0;
    $.ajax({
        url: "https://dl.dropboxusercontent.com/u/75734877/taglines.txt",
        type: "GET",
        dataType: "text",
        beforeSend: function () {
            $('#kowts').show().html('<img src="http://www.feelol.com/Content/images/Loading.gif" />');
        },
        success: function (t) {
            var lines = t;
            var lineArr = lines.split('\n');
            num = Math.floor(Math.random() * lineArr.length);
            $('#kowts').show().text(lineArr[num]);
        },
        error: function(){
            alert('Error')
        }
    });
});

Split the quotes from text file by "\n" (new line), then get its length and generate a random number between 0 to maximum length. Then use the generated number as index to get the quote on that particular line. Display it in your HTML element.

<button id="btn_modal">Give me a Quote</button>
<p id="kowts"></p>

#kowts {
    display:none;
    font-weight:bold
}

BTW, the text file that I used is not mine, got from somewhere else I forgot the link. (: