Quick Tip #2: Disable tab-bar auto-hide feature in FF Fullscreen Mode

I’m a big fan of having my applications run in fullscreen mode, especially firefox. But I always hated how the tab-bar is always in auto-hide mode. And after Googling a little I found out how to disable the auto-hide feature! It’s super simple.payday loans All you have to do is:

Type about:config on Firefox address bar.
Search for browser.fullscreen.autohide
Set it to false

Source: superuser.com

Quick Tip #9: Identify Macbook Pro Retina Display Manufacturer

To know the manufacturer of your Macbook Pro Retina all you have to do is pop the following command in the terminal.

ioreg -lw0 | grep \"EDID\" | sed "/[^<]*</s///" | xxd -p -r | strings -6

If the code on the 2nd line starts with LP it’s and LG. If it starts with LSN it’s a Samsung

Test Driven Development Using Django Unit Testing

Before we start get on with test driven development using django unit testing, it is essential to understand what test driven development (TDD) is. The basic idea is to write tests before the implementation. The following diagram better describes the process.For more in depth information about TTD visit this website: http://www.agiledata.org/essays/tdd.html.

On with the Django stuff!!

If you haven’t already installed django and played around a little on a sample application, then consider reading these tutorials before continuing on with this: installation, sample app.

In this tutorial we will continue with the guestbook application. Let us build this tutorial on this user story: As a user, I can rate a guestbook comment.

The First Step:

Think of all the failure and success scenarios for “As a user, I can rate a guestbook comment.” This means, to think of all the features that we want to test for this user story, below are just a couple of them:

  1. Each user can rate only once.
  2. A user must be logged in to rate.
  3. A user cannot rate their own comments.

In this tutorial, I will only show number 2. ‘A user must be logged in to rate.’

The Second Step:

  1. Use the following models in models.py:
    from django.db import models
    from django.contrib.auth.models import User
    
    class Guestbook(models.Model):
        owner = models.OneToOneField(User)
    
    class Comment(models.Model):
        content = models.CharField(null = False, blank = False, max_length = 140)
        owner = models.ForeignKey(User)
        posted = models.DateTimeField('date Posted')
        guestbook = models.ForeignKey(Guestbook)
    
    class Rating(models.Model):
        RATING_CHOICES = (
            ('1', 'Pure Crap'),
            ('2', 'Meh'),
            ('3', 'Okay'),
            ('4', 'Good!'),
            ('5', 'AWESOME')
        )
        value = models.IntegerField(max_length=1, choices=RATING_CHOICES)
        comment = models.ForeignKey(Comment)
        user = models.ForeignKey(User)
  2. Use the following urls in urls.py
    from django.conf.urls import patterns, include, url
    
    # Uncomment the next two lines to enable the admin:
    from django.contrib import admin
    admin.autodiscover()
    
    urlpatterns = patterns('',
        url(r'^rate/$', 'rating.views.rate', name='rate_comment'),
        url(r'^$', 'rating.views.home', name = 'home'),
    )
  3. Create the empty method rate in views.py:
    from django.http import HttpResponse
    
    def rate(request):
        return HttpResponse('Hello World')

TheThird Step:

Write the corresponding test in tests.py:

from datetime import datetime
from django.test import Client
from django.test import TestCase
from django.core.urlresolvers import reverse
from models import *
from django.contrib.auth.models import User
from django.utils.timezone import utc

class CommentTest(TestCase):

    def setUp(self):
        self.hadeer = User.objects.create_user(username = 'Hadeer', password = '123456')
        self.john = User.objects.create_user(username = 'John', password = '123456')
        content = 'Nice guestbook!'
        self.guestbook = Guestbook.objects.create(owner = self.hadeer)
        self.comment = Comment.objects.create(guestbook = self.guestbook, posted = datetime.utcnow().replace(tzinfo = utc), content = content, owner = self.john)

    def test_models(self):
        self.assertEqual(self.guestbook.comment_set.all().count(), 1)

    def test_not_logged_in(self):
        c = Client()
        # Perform a rating action on the comment, by mocking a POST request
        response = c.post(reverse('rate_comment'), { 'cid' : self.comment.id, 'rating' : 4})
        # Should get an unauthorized message, as the user must be logged in
        self.assertEqual(response.status_code, 403)

    def test_logged_in(self):
        c = Client()
        c.login(username='Hadeer', password='123456')
        # Perform a rating action on the comment, by mocking a POST request
        response = c.post(reverse('rate_comment'), { 'cid' : self.comment.id,  'rating' : 4})
        # Should get a 302 redirect
        self.assertEqual(response.status_code, 302)
        rating = Rating.objects.get(id = 1)
        # The value should be 4
        self.assertEqual(rating.value, 4)

Note: I prefer using reverse() instead of hardcoding urls, you can read about this more here. Also set_up is called before every test is run.

Step four:

  1. Now from command line run all the tests in the application guestbook as follows:
    $ python manage.py test guestbook
  2. You should get the following output:
    Creating test database for alias 'default'...
    F.F
    ======================================================================
    FAIL: test_logged_in (rating.tests.CommentTest)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "/home/elleestcrimi/workspace/guestbook/rating/tests.py", line 34, in test_logged_in
        self.assertEqual(response.status_code, 304)
    AssertionError: 200 != 302
    
    ======================================================================
    FAIL: test_not_logged_in (rating.tests.CommentTest)
    ----------------------------------------------------------------------
    Traceback (most recent call last):
      File "/home/elleestcrimi/workspace/guestbook/rating/tests.py", line 26, in test_not_logged_in
        self.assertEqual(response.status_code, 403)
    AssertionError: 200 != 403
    
    ----------------------------------------------------------------------
    Ran 3 tests in 0.061s
    
    FAILED (failures=2)
    Destroying test database for alias 'default'...

Step Five

Now that we have seen all of our tests fail, we can start writing the rating view:

from django.core.exceptions import PermissionDenied
from django.http import HttpResponse
from models import *
from django.shortcuts import redirect

def rate(request):
    if not request.user.is_authenticated():
        raise PermissionDenied

    comment = Comment.objects.get(id = request.POST['cid'])
    Rating.objects.create(comment = comment , user = request.user, value = request.POST['rating'])

    return redirect('/')

The updated should make all the tests succeed and it does:

Creating test database for alias 'default'...
...
----------------------------------------------------------------------
Ran 3 tests in 0.051s

OK
Destroying test database for alias 'default'...

For more information take a look at the following links:
https://docs.djangoproject.com/en/dev/topics/testing/
http://toastdriven.com/blog/2011/apr/10/guide-to-testing-in-django/
http://od-eon.com/blogs/alumni/tudor/test-driven-development-django-way/
http://tdd-django-tutorial.com/

How to: Filter Commit Messages by Committer on code.google.com

I didn’t really find a tool that filtered the code.google commits by committer so I wrote a small script that does just that!

[UPDATE] This code doesn’t just filter all commits on the current page by a specific username, but instead it filters all commits. Thanks to the awesome TjWallas for suggesting this update.

In order to filter all commits by username all you have to do is:

  1. Navigate to the commits log page
  2. Open up the javascript console
  3. Load jQuey, by pasting in the jQuery loading code from below.
  4. After jQuery has loaded. Paste in the rest of the code below.
  5. Update the username variable, with the actual username you want.
  6. Enjoy!

 

[gist id=2562797 ttl=10 bump=1]

Sublime Text Latex Build System (Ubuntu)

I’m a huge fan of Sublime Text it’s a very neat editor. I use to develop nearly everything, but for some reason I couldn’t find any latex plugins that work (maybe I’m the only facing this?). After Googling around a little I decided what the heck, I’ll write my own Sublime Text Latex Build System.

This works on Ubuntu with pdfLatex 2011, it should also work with the 2009 version. Of course the cmd attribute can be changed to work with anything else besides pdflatex.


{
	"cmd": ["pdflatex $file && gnome-open $file_base_name.pdf"],
	"file_regex": "^(...*?):([0-9]*):?([0-9]*)",
    "selector": "source.latex.tex",
    "shell": true
}

In order to create a new build system with the previous code all you have to do is this:

  1. Click ‘Tools’
  2. Click ‘Build System’
  3. Click ‘New Build System’
  4. Copy and paste the previous code in the new file
  5. You must save the file anywhere within the ‘Packages’ folder

And that’s it!

How to make newspaper columns using CSS3

This is a  quick tutorial on how to get a text columns effect, without using floats and separate divs. So usually to get a “columns” effect in HTML we usually do the following: For each column create a div Then we give these divs a min-height, padding, margins, borders and make them float left or right. But now with CSS3 columns we don’t need to do all of that, it can be done simply as follows:

The HTML

<div class="holder">
    <h1>Lorem</h1>
    ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum aliquam malesuada libero, sed iaculis eros pharetra sed. Donec sollicitudin placerat fringilla. Etiam vel fermentum urna. Vivamus porttitor, felis vitae scelerisque venenatis, turpis ante vestibulum nisi, eu dignissim turpis est tristique ante. 
    <h1>Quisqu</h1> 
    lectus non facilisis suscipit, dolor justo bibendum lacus, vitae semper sapien felis id neque. Vestibulum sed risus sagittis eros placerat viverra non non felis. Aliquam scelerisque, risus ac mattis laoreet, lorem sem blandit turpis, ac euismod turpis velit et massa. 
    <h1>Nunc</h1> 
    vulputate dui ac diam suscipit semper. Vestibulum ac felis sit amet justo porttitor placerat at fermentum magna. Pellentesque id felis mauris. Cras tincidunt sollicitudin risus, consequat mattis nulla consequat vitae. Pellentesque at odio nec augue adipiscing congue ac quis lectus. In molestie rutrum urna.
</div>

The CSS

div.holder
{
  -webkit-column-count: 3;
  -webkit-column-rule: 1px dotted rgba(0, 0, 0, 0.5);
  -webkit-column-gap: 2em;
  -moz-column-count: 3;
  -moz-column-rule: 1px dotted rgba(0, 0, 0, 0.5);
  -moz-column-gap: 2em;
  column-count: 3;
  column-rule: 1px dotted rgba(0, 0, 0, 0.5);
  column-gap: 2em;
}

div.holder>h1:not(:first-of-type)
{
  -moz-column-break-before : always;
  -webkit-column-break-before : always;
}

h1 {
    margin: 0 0 20px 0
}

Demo

Introduction to Django: Guestbook application

This tutorial is intended to be a straight to the point and forward introduction to the python web framework Django.

If you do not have Django and Python already setup on your system, please follow this tutorial. Even though it is intended for windows, basically the same steps apply to linux and mac (Excluding the Python Installation section)

Creating a new django project

To create a new Django project simply:

  1. Open the CMD/Terminal
  2. CD to the place where you want your project to live
  3. Type in the following command:
    django-admin.py startproject testProject
  4. A folder called testProject will be created with the following structure:
    testProject/
        manage.py
        testProject/
            __init__.py
            settings.py
            urls.py
            wsgi.py
  5. Run the server by executing the following:
    cd testProject
    python manage.py runserver

    You should then see the following in the console:

    Validating models...
    0 errors found.
    
    Django version 1.4, using settings 'mysite.settings'
    Development server is running at http://127.0.0.1:8000/
    Quit the server with CONTROL-C.
  6. Open your browser and navigate to: http://127.0.0.1:8000/ you should see the following:

Setting up the database

To setup the database you must open settings.py and modify the databases section. Django supports MYSQL, SQLite, Oracale and PostgreSQL. In this tutorial we will setup a SQLite database.

  1. Modify your database settings as such:
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.sqlite3',
            'NAME': 'database.db', # path to database file if using sqlite3.
            'USER': '',
            'PASSWORD': '',
            'HOST': '',
            'PORT': '',
        }
    }

    Please note the NAME specified above, is the path to the database file with respect to settings.py

  2. To actually create the database and populate it with the corresponding tables, run this command:
    python manage.py syncdb

    What it does is create all nessascry databases and tables for all the applications specified in INSTALLED_APPS. This is found in settings.py

Creating the guestbook application

Now we have created a project called testProject and connected it to a database. We will now create an application within that project called guestbook.

  1. To create a new application type in the following command:
    python manage.py startapp guestbook

    This will create an application inside testProject with the following structure:

    guestbook/
        __init__.py
        models.py
        tests.py
        views.py
  2. Now open settings.py and add guestbook to the list INSTALLED_APPS:
    INSTALLED_APPS = (
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
        'django.contrib.messages',
        'django.contrib.staticfiles',
        'guestbook'
    )

Creating the models

For our guestbook application, we will create to models: Guestbook and Comment. Each guestbook belongs to one user and has many comments. While each comment belongs to one and only one guestbook, it has the fields: Name, time posted and content.

  1. This is what models.py should look like:
    from django.db import models
    from django.contrib.auth.models import User
    
    class Guestbook(models.Model):
        owner_name = models.CharField(null = False, blank =  False, max_length = 20)
    
    class Comment(models.Model):
        content = models.CharField(null = False, blank = False, max_length = 140)
        owner_name = models.CharField(null = False, blank = False, max_length = 20)
        posted = models.DateTimeField('date Posted')
        guestbook = models.ForeignKey(Guestbook)
  2. In order to see the SQL that model.py conforms to type in:
    python manage.py sql guestbook

    The output should be:

    BEGIN;
    CREATE TABLE "rating_guestbook" (
        "id" integer NOT NULL PRIMARY KEY,
        "owner_name" varchar(20) NOT NULL)
    )
    ;
    CREATE TABLE "rating_comment" (
        "id" integer NOT NULL PRIMARY KEY,
        "content" varchar(140) NOT NULL,
        "owner_name" varchar(20) NOT NULL,
        "posted" datetime NOT NULL,
        "guestbook_id" integer NOT NULL REFERENCES "rating_guestbook" ("id")
    )
    ;
  3. Now we need to re-sync the databases so that the new SQL is executed:
    python manage.py syncdb

Creating your first view

Now before we starting writing code for the views. Let us first understand how views, urls and templates work.
So first a user types in a url in the address bar. The system then tries to pattern match this url against all the urls defined in urls.py. When it finds one that it conforms to it then executes the corresponding view function which is defined in urls.py. The view function then does some backend processing and renders a template. The template is the HTML that you see in your browser.

Now we know how everything works, let’s create a view that shows “Hello World”.

  1. Open views.py
  2. Add the following code:
    from django.template import RequestContext
    from django.shortcuts import render_to_response
    
    def home(request):
            return render_to_response('index.html', RequestContext(request))

    This is just a view method that renders the template file index.html

  3. In order to use templates we must define the template directory inside settings.py. To do so we must first import the os module. Which is added at the top of settings.py.
    import os

    Now we must update the TEMPLATE_DIR as follows:

    TEMPLATE_DIRS = (
        os.path.join( os.path.dirname( __file__ ), 'templates' )
    )

    This basically states that the templates folder is in the same folder as settings.py

  4. Create a folder called templates in the same folder as settings.py
  5. Inside templatescreate an HTML file that says ‘Hello World!’
    <!DOCTYPE html>
    <html>
    <body>
        <h1>Hello World!</h1>
    </body>
  6. Final step is to create the url that goes to this view, so open urls.py. And update it as such:
    from django.conf.urls import patterns, include, url
    
    urlpatterns = patterns('',
        url(r'^home/$', 'guestbook.views.home', name='home'),
    )

    This means that if the user types in http://127.0.0.1:8000/home/, they should see “Hello World!”

  7. Restart the server and in your browser navigate to http://127.0.0.1:8000/home/ to see the effect.

GuestBook Creation View

In this view we want the user to be able to create a new guestbook by clicking a button. In order to do this, redo the steps in the previous section and change the following:

  1. Change the URL to be
    url(r'^create/guestbook/$', 'guestbook.views.create_guestbook', name='create guestbook'),
  2. Rename the view function name and HTML file name to something appropriate.
  3. The HTML file will be updated to contain a form that takes a user’s name as input.
    <form action="/create/guestbook/" method="POST">
        {% csrf_token %}
        <label for="name">What is your name?</label>
        <input type="text" name="owner_name" />
        <input type="submit" value="create" />
    </form>

    To understand what CSRF is, and what is {% csrf_token%} please read the following links:
    https://docs.djangoproject.com/en/dev/ref/contrib/csrf/
    http://en.wikipedia.org/wiki/Cross-site_request_forgery

  4. We will now write a view function called create_guestbook. If you noticed we are using the same url for viewing the form and submitting the form. This is because we can execute different code depending on the TYPE of the request. See Below:
    form models import Guestbook
    
    def create_guestbook(request):
        if request.POST:
            guestbook = Guestbook.objects.create(owner_name = request.POST['name'])
            return render_to_response('index.html', RequestContext(request))
        else:
            return render_to_response('create_guestbook.html', RequestContext(request))
  5. Now try out your new code. You should see something like this:

Guestbook Read view

Now that we can successfully create new guestbooks. We want to be able to view all the guestbooks we have. Again we will do the same steps as the section titled “Creating your first view”. Now rename everything accordingly like the last section. And change the following:

  1. In the HTML file we need to loop over all the guestbooks that appear in our database, to do this we use the {% for item in lits %} HTML here {% endfor %}template tags. This loop over a list of items, so the HTML within is re-written for each item. See code below:
    <!DOCTYPE html>
    <html>
    <body>
    <h1>Avaliable Guestbooks</h1>
    {% if guestbooks %}
        <ul>
        {% for guestbook in guestbooks %}
    	<li>{{ guestbook.owner_name }}'s Guestbook<li>
         {% endfor %}
    </ul>   
        {% else %}
            Sorry no one has created any guestbooks yet :( 
        {% endif %}
    </body>
    </html>
  2. Make the view function fetch all the guestbook objects and render them to the template. See code below:
    def guestbooks(request):
        guestbooks = Guestbook.objects.all()
        return render_to_response('guestbooks.html', { 'guestbooks' : guestbooks },RequestContext(request))
  3. Now try out your new code. You should see something like this:

    or

Single Guestbook Read/Delete View

Now that we can view all the guestbooks available on the system. We want the users to start posting some content! This part I think you can do on your own, all you need to do is show all the comments that belong to a certain guestbook, and add a create comment form.

Hints:

  1. In order to access all the comments that belong to the guestbook with id = 3, simple do as follows:
    • Method 1 in views:
          guestbook = Guestbook.objects.get(id = 3)
          comments = guestbook.comment_set.all()
    • Method 2 in views:
          comments = Comment.objects.fetch(guestbook = 3)
    • In HTML:
          {{ guestbook.comment_set.all }}
  2. To capture the id from a url pattern write it as follows:
    url(r'^guestbook/(\d+)/$', 'guestbook.views.guestbook', name='guestbook'),

    When you put anything between () in a url pattern, it acts as a view function input. Example:

        def guestbooks(request,id):
            pass

    Moreover url patterns are done using regular expressions. So in this case \d+ means a number of at least 1 digit.

  3. To delete an object you just call the .delete()method on it. Example:
        comment = Comment.objects.get(id = 1)
        comment.delete()

Quick Tip #7: Detect onDomChange Events

If you want to detect automatically everytime the contents of a dom element changes. All you have to do is attach the ‘DOMNodeInserted’ and ‘DOMNodeRemoved’ event handlers.

$('#main').bind('DOMNodeInserted', function(event) {
    alert('inserted node');
});

$('#main').bind('DOMNodeRemoved',function(event) {
    alert('removed node');
});

So basically the above code detects every time a dom element is removed or inserted into ‘#main’.

How To: Make AJAX calls in Django that pass CSRF validation

Today I was playing a little with jQuery on a django project, Then I came upon this error “Forbidden (403) CSRF verification failed. Request aborted”. I kept getting this error every time the application made an ajax call. And after Googling around a little I found that the solution is quiet simple. But before we get into that there are a few important points we need to know…

What the hell is CSRF?

CSRF stands for Cross-site request forgery

it is a type of malicious exploit of a website whereby unauthorized commands are transmitted from a user that the website trusts. Unlike cross-site scripting (XSS), which exploits the trust a user has for a particular site, CSRF exploits the trust that a site has in a user’s browser.

from wikipedia

You can read more on this here and
here.

What do I have to do in my django project, to not get this error?

To solve this we need to pass the CSRF token with every request. All you have to do is add the following code in your main template file & before the script containing the AJAX calls.

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    if(!options.crossDomain) {
        if(options.data) {
            options.data += "&";
        } else {
            options.data = "";
        }
        options.data += "csrfmiddlewaretoken={{csrf_token}}";
    }
});

Thanks to grep from stackoverflow for answering this question.

And that’s it!

jQuery Multiple Draggables

When I first used Google Plus, the first thing that impressed me the most was the circles feature. And more importantly the way you can select friends and drag them all to a certain circle. So I made a very basic jQuey plugin that mimics the dragging multiple contacts part.

How to use:

You must include this in the head part of your html page. Where “.draggable” is the class given to all the elements that will be dragged together.

<script src="jquery.js"></script>
<script src="jqueryui.js"></script>
<script src="jquery.multipleDraggable.js"></script>
<script>
$(function(){
        $('.draggable').multipleDraggable();
});
</script>
</head>

You can extend the functionality by adding start, drag & stop functions just like in jQuery’s draggable.

$('.draggable').multipleDraggable({
        start: function(){ console.log('Starting Multiple Drag');},
        drag: function(){ console.log('dragging!');},
        stop: function(){ console.log('Stopped Multiple Drag');}
});

In the body part of your html page all you need to add is the following:

<body>
<div class="draggable" ></div>
<div class="draggable" ></div>
<div class="draggable" ></div>
<div class="draggable" ></div>
</body>

In the demo I used these styles

 
*{
    padding:0;
    margin:0
}       

html{
    background:#efefef;
}

div.draggable
{
    display:inline-block;
    background: #ff6699;
    width:40px;
    height:40px;
    cursor:move
}

And that’s it!

Demo

You can see the demo here

Get The Code!

You can get the code from github

Download

[download id="1" format="1"]

Quick Tip #4: No refs in common and none specified

Today while I was playing around with git, I found my self unable to push anything to my newly created repository. This is the error that I got:

$ git push
No refs in common and none specified; doing nothing.
Perhaps you should specify a branch such as 'master'.
error: failed to push some refs to 'git@github.com:elleestcrimi/coffee.git'

After Googling around for a few minutes I found the solution! Which is dreadfully simple! All you have to do is this:

$ git push origin master

Quick Tip #3 : Fix Screen Brightness Issue on Samsung Netbooks Running Ubuntu

As all Samsung netbook owners may have noticed, the brightness goes crazy (alternates the brightness randomly) on Ubuntu 11.10, when you remove the plug or try to adjust the brightness. Also on older Ubuntu versions the brightness keyboard shortcuts don’t work. All of this can be solved using Samsung-tools.

All you have to do, is open open the terminal and type in the following:

sudo add-apt-repository ppa:voria/ppa
sudo apt-get update
sudo apt-get install samsung-tools samsung-backlight

Just restart your netbook, and everything is then magically fixed!

Revia

How To: Overcome “Cannot modify resource set without a write transaction” in Eclipse GMF

While developing with the Eclipse Graphical Modeling Framework, I’ve come across this one error that made zero sense to me:

java.lang.IllegalStateException: Cannot modify resource set without a write transaction

This error means that you’re not allowed to execute a write transaction in a read-only domain, in other words you can’t edit your models from here. There is apparently two solutions for this, if you don’t want the command to have undo and redo options then take a look @ this. I myself was never able to get this to work. So there is an alternate solution through specifying your own command. The custom command class would look something like this:

    public static class MyCommand extends AbstractTransactionalCommand
    {
	public MyCommand(TransactionalEditingDomain editingDomain)
	{
	    super(editingDomain, "a message", null);
	}

	@Override
	protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info) throws ExecutionException
	{
            // You can add here the line of code that is giving you the error! 
            // Below is an example line.
	    getEditingDomain().getCommandStack().execute(SetCommand.create(getEditingDomain(), myElement, XXXPackage.eINSTANCE.getElemenet_name(), 'New name'));
	    return CommandResult.newOKCommandResult();
	}
    }

So after defining your new class in order to execute that command in your read-only domain, you must wrap it in an ICommandProxy and then execute/return.

ICommandProxy a = new ICommandProxy(new MyCommand(getEditingDomain()));
a.execute();

And now you can execute write transactions in read-only domains!

Quick Tip #1 : Click-through Web Elements

Don’t you ever wonder how to click on an element which is behind another element?? Well apparently this is very easy and is done with the CSS property “pointer-events”

For example if you have element A which is on top of element B then we apply the CSS property to A as such:

#element-A
{
    pointer-events: none;
}

Now you can click element B with element A on top of it! It’s that simple.

Kannel: Configuring Delivery Reports

I guess I can say that I have worked with kannel enough to know my way around it (I’m no expert mind you :] ). And after a lot of googling & experimenting I finally found out how to get delivery reports for all the SMSs you send via kannel. All you have to pass the dlr-mask and dlr-url as parameters in the send-sms link. Below is a code snippet that shows the final send_sms URL which I wrote in JS.

// This is an imaginary phone number
var number  = "+222222222222222222"   

// This is the SMS content
var text    = encodeURIComponent("Hello World!")          

// This is the URL that is called when the deliver report is received
var dlr_url = encodeURIComponent("http://localhost/my_app/recieve_delivery_report?status=%d")

// This is the default send_sms url defined by kannel
var send_url = "http://localhost:13001/cgi-bin/sendsms?username=tester&password=foobar"

// This is the final send_sms link 
var link    = send_url + "&to=" + number + "&text=" + text + "&dlr-mask=31&dlr-url=" +dlr_url

window.location = link

Why do we use encodeURIComponent() ??

We use the encodeURIComponent() method to be able to pass the msg text and url as GET parameters.

What is the dlr-mask??

The dlr-mask specifies which type of reports kannel should keep track of. Here are all the available delivery report types:

1  : delivery success
2  : delivery failure
4  : message buffered
8  : smsc submit
16 : smsc reject

The value of the dlr-mask is the addition of the delivery report numbers that you want to keep track of.
Example: 31 = 1+2+4+8+16

Note:

In Egypt (where I have been testing kannel) I have noticed that the mobile providers only return delivery reports with number 8 and 16. Which in our (el masreeyen’s) case is equivalent to 1 and 2.

Further Reading:

Kannel 1.4.3 Documentation

How To: Setup Python & Django on Eclipse & Windows 7

UPDATE: Removed the use of cygwin, and used instead the normal windows command prompt.

Step 1: Install Python

  1. Go to http://www.python.org/getit/releases/2.7.2/ and download the windows installer version.
  2. Install it.
  3. Add the following to your path via system environment:
    ;C:\Python27;
  4. To make sure it works, open the command prompt and type in python

Step 2: Install Django

  1. Download Django from https://www.djangoproject.com/download/.
  2. Extract it where ever you want.
  3. Open the command prompt and navigate to where you extracted Django
  4. Run the following command:
    python setup.py install
  5. To make sure Django was installed correctly, first type in the python command in the command prompt which will open the python interpreter. Then write the following:
    import django
    print django.get_version()

Step 3: Installing PYDEV on eclipse

  1. Click Help > Install New Software
  2. In the work with field paste the following URL: use the url http://update-production-pydev.s3.amazonaws.com/pydev/updates/site.xml
  3. Only select Pydev.

  4. Select all certificates and accept them, otherwise the installation will fail.
  5. After the installation has finished, go to Window > Preferences, expand the Pydev tab and select Interperter-Python
  6. Click the “auto config” button
  7. You will then see the following screen, make sure you unselect PySrc and python32.zip and click Ok.

And that’s it! Your ready to start creating Python and Django projects on Eclipse!

An Introduction: Eclipse GMF

I thought I would start writing a series of tutorials about Eclipse GMF, mostly because I didn’t find MANY online tutorials for it that treated you as a beginner, or maybe I didn’t Google hard enough… Either ways I thought I would share what I learned.

What is Eclipse GMF?

GMF stands for Graphical Modeling Framework, it is uses a MDD approach to build graphical editors in Eclipse, using Eclipse EMF and Eclipse GEF.

So what are Eclipse EMF and GEF?

EMF stands for Eclipse Modeling Framework. What it does is generate code (Java Classes) form a structured data model, which can be a UML Model, Ecore Model or XSD Model. GEF stands for Graphical Editing Framework which makes creating graphical editors a breeze.

What Software do I need to start?

Just download the Eclipse Modeling Tools.

What do I need to know before starting?

When I first opened the GMF dashboard I was dumbstruck! They had a lot of things that i didn’t quiet understand such as Graphical Definition/Tooling Definition/Mapping Definition and so on… Like anyone can guess what they are, but when setting them up it’s get kind of confusing when picking what should go where. So here is a little insight about what everything means:

Domain Model

This is where you create your data model. The EMF provides you 3 ways to do this: UML,ECORE,XSD. It also provides you with a visual editor to build your data model, so that you can just draw what you need without writing code!

Domain Generator Model

From your Ecore/UML/XSD file you generate a generator model. This model generates the model code for you! It generates model code, edit code, editor code & test code… I think it’s easy to assume which each generated code does?

Graphical Definition Model

The main components of a graphical definition is the Nodes, Links and Attributes. Basically a Node is like an object that you want to be drawn on the canvas. A Link represents a relation between two Nodes, also a class can be graphically represented as a Link. Attributes are like the instance variables of your class.
So what does a graphical definition do?? It defines all the graphical elements to be shown on your canvas from your ecore file. (The Ecore file contains your data model). If something isn’t in the graphical definition tha’ts okay! Not everything must be graphically represented.

Tooling Definition Model

If you are building a graphical editor you will need a toolbox or a palette which all controls in it. So this is where the tooling definition comes it. You specify which tools you want to have a in your toolbox for your graphical elements.

Mapping Definition Model

From the name we can deduce that it MAPS something. What it does is detect Nodes and their Links form the Ecore file. It then maps each Node/Link to it’s corresponding tool and graphical representation. Sometimes it doesn’t always map everything correctly so it’s always best to check what the wizard does.

Diagram Editor Generator Model

This is generated from the Mapping definition. You can choose to either generate an Eclipse RCP version or a normal Eclipse plugin version. You won’t need to customize this part except for advanced applications. But what it does is it edits how the Diagram Editor (The thing you are building) behaves. For example enabling drag/drop, enabling project navigation and so on.
Hopefully sometime next week I will write a tutorial on how to create a hello world project using Eclipse GMF.
Userful Links:
GMF BPMN Tutorial
GMF Tutorials
EMF/RCP Vogella Tutorials
GMF Jevon Tutorials

An Introduction: OpenGl 2D Textures

So this is brief introduction about how to use 2D textures in openGL. This tutorial uses .raw files which do not have any transparency (can they have that aslan??), which you can easily create with photoshop; or use an online extension conversion tool (google??).

I’m not sure if the texture must be a square (most probably not) and I’m not sure if it’s dimensions must be in the form of 2^n; but these are the settings that worked for me. So experiment a bit???

Setting up the texture
void setUpTextures()
{	
        //This is the array that will contain the image color information.
        // 3 represents red, green and blue color info.
        // 512 is the height and width of texture.
	unsigned char grass[512 * 512 * 3];
        
        // This opens your image file.
	FILE* f = fopen("grass.raw", "r");
	fread(grass, 512 * 512 * 3, 1, f);
	fclose(f);

	glEnable(GL_TEXTURE_2D);
	
	//Here 1 is the texture id
        //The texture id is different for each texture (duh?)
	glBindTexture(GL_TEXTURE_2D, 1);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
        //In this line you only supply the last argument which is your color info array,
        //and the dimensions of the texture (512) 
	glTexImage2D(GL_TEXTURE_2D, 0, 3, 512, 512, 0, GL_RGB, GL_UNSIGNED_BYTE,grass);
	
	glDisable(GL_TEXTURE_2D);
}
Using the texture
void grass()
{
	glEnable(GL_TEXTURE_2D);
        // Here you specify WHICH texture you will bind to your coordinates.
	glBindTexture(GL_TEXTURE_2D,1);
	glBegin(GL_QUADS);
        // If you do not set a color, the textured area will appear black.
	glColor3f(1,1,1);

        /*
         * In order to apply a texture to a square, you must map
         * every vertex of the texture to the corresponding vertex
         * in the square.
         *
         * As you can see here we used 0 and 1 for the texture
         * coordinates, this means that the texture will be drawn only once
         * if you shift the values (ex: 0.5 and 1.5) the texture image will shift
         * if you increase the range (ex: 0 and 100) then the texture will be
         * tiled 100 times.
         *
         * Depending on the size of the square the texture will scale to fit it.
         */
	glTexCoord2d(0,0);	glVertex3f(2, 1, 2);
	glTexCoord2d(1,0);	glVertex3f(-2, 1, 2);
	glTexCoord2d(1,1);	glVertex3f(-2, 1, -2);
	glTexCoord2d(0,1);	glVertex3f(2, 1, -2);
	glEnd();
        // Do not forget this line, as then the rest of the colors in your 
        // Program will get messed up!!!
	glDisable(GL_TEXTURE_2D);
}


How to: Rotate a 3D object about it’s center in openGL

Theoretically If I have a square centered at [x, y, z] and I want to rotate it around itself, then we must apply 3 transformations:

M1 Translate to origin by [-x, -y, -z]
M2 Rotate around origin by 45deg
M3 Translate back by [x, y, z]

So the final matrix is: M3xM2xM1, So you may assume that it is written as follows in openGL:

glPushMatrix();
glTranslatef(-x, -y, -z);
glRotatef(45, 0, 1, 0);       //Rotate about the y-axis
glTranslatef(x, y, z);
draw();
glPopMatrix();

BUT this is actually wrong, it is in fact the opposite (el 3aks)!!!!!!!!!!!! So the CORRECT way to rotate an object about it’s center is as follows:

glPushMatrix();
glTranslatef(x, y, z);
glRotatef(45, 0, 1, 0);       //Rotate about the y-axis
glTranslatef(-x, -y, -z);
draw();
glPopMatrix();

FB Phonebook Exporter

So after getting my new HTC, I just loved how everything was synced together, My Google contacts with my cell contacts and how those could be linked to their facebook profiles. BUT what sucked thou is that I couldn’t save my facebook phonebook to my cell contacts or download them on my phone. (If you know how to do it please tell me =D)

So I wrote a little script that exports my FB phonebook in a Google contacts compatible CSV.
Currently it doesn’t support multiple mobile and multiple land-line numbers (none of my contacts had those, so I couldn’t test it out).

I wrote because I couldn’t get the other FB phonebook scripts to work, maybe I’m dumb XD,

You can download it off here: http://userscripts.org/scripts/show/92383

So try it out and tell me what you guys think.

3 Steps to Set Up a 3D scene in OpenGL C++

Here I will describe how to setup a basic 3D scene using glViewPort and not glOrtho. There is basically 1 main thing to do: Setup the reshape function. WHY? Because this is the first thing that is called when the window is created, then the display function is called after-wards. BUT If you put the reshape function contents into the display function, it will work AS LONG AS you don’t resize the window.

  1. Initialize the variables that will be used.
    //This is the height of your scene and window
    int height = 700;
    //This is the width of your scene and window
    int width  = 700;
    //This is the ratio of width/height
    float aspect_ratio = 1;
    /*
     *This specifies the position of the eye point, which is used in the camera
     *(gluLookAt). Here it is 30.0f pixels in the -z direction. So that you can
     *so that you can see the 3D object in-front of you, instead of seeing it
     *from the center.
     */
    float eye[3] = {0.0f, 0.0f, -30.0f};
    /*
     *This specifies the position of the reference point, which is used in the
     *camera (gluLookAt). Here the reference point is the same as the origin.
     */
    float center[3] = {0.0f, 0.0f, 0.0f};
    /*
     *This specifies the direction of the up vector, which is used in the camera
     *(gluLookAt). Here the up vector is the y-axis.
     */
    float up[3] =  {0.0f, 1.0f, 0.0f};
  2. You must set up the reshape function. It updates the scene to match the new height and width, it also takes care of the mouse XY not being correct as stated in THISpost.
    void resize(int w, int h)
    {
        //To update the width
    	width = w;
        //To update the height
    	height = h;
        //To update the aspect ratio
    	aspect_ratio = (float) width / (float) height;
        //Specifies the area in which openGl draws
    	glViewport(0, 0, width, height);
    	glMatrixMode(GL_PROJECTION);
    	glLoadIdentity();
        //Sets up the perspective projection
    	gluPerspective(45.0f, aspect_ratio, 1.0f, 600.0f);
    	glMatrixMode(GL_MODELVIEW);
    	glLoadIdentity();
        //Specifies the backgroundColor
        glClearColor(1.0f, 1.0f, 1.0f, 0.5f);
        /*
         *The depth value used when the depth buffer is cleared.
         *This is like the glClearColor() command but for the depth buffer.
         */
    	glClearDepth(1.0f);
        /*
         *This enables depth testing, OpenGL draws surfaces from back to front.
         *So if a primitive is behind the other, it doesn't mean it is really being drawn
         *behind the primitive. The depth test fixes this problem.
         */
    	glEnable(GL_DEPTH_TEST);
        /*
         *GL_LEQUAL means "less or equal", so everything that is less or
         *equal the actual value gets drawn.
         */
    	glDepthFunc(GL_LEQUAL);
    	glLineWidth(4);
    }
  3. The display function will be like any other display function, here We will draw a 3DCube
    void display()
    {
        /*
         *gluLookAt sets up the camera, so you are telling it from WHERE
         *you want to look at the 3D scene.
         */
    	gluLookAt(eye[0], eye[1], eye[2], center[0], center[1], center[2], up[0], up[1], up[2]);
    	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
        //Rotates -45degs around the x-axis, So that you can have a better view
    	glRotatef(-45, 1, 0, 0);
        //Rotates 45degs around the y-axis, So that you can have a better view
    	glRotatef(45, 0, 1, 0);
    	glColor3f(0.0f, 0.0f, 0.0f);
        //draws the outline of a 3Dcube with width 10.
    	glutWireCube(10);
        //Make sure changes appear onscreen
        glutSwapBuffers();
    }

Source: Google ImagesDescription: This is an example of what the gluPerspective is.




Source: Google ImagesDescription: This is an example of what the gluLookAt is. The cuboid is your 3D object and the 3D Pyramid is your perspective.

Further Reading:
glViewport
gluPerspective
gluLookAt
glClearDepth
glDepthFunc

How To: Detect MouseEvents in OpenGL C++

There is 3 types of “Mouse Listeners” for OpenGL

This detects mouse clicks:

glutMouseFunc();

This detects mouse movement while the left button is held down thus “active motion”:

glutMotionFunc();

This detects mouse movement while the no button is held down thus “passive motion”:

glutPassiveMotionFunc();
The Code: Mouse Clicks
  1. To tell the window to listen to “Mouse Clicks” then you have to add “glutMouseFunc(processMouse)” before the “glutMainLoop();” as below:
    int main(int argc, char** argv)
    {
    	...
    	glutMouseFunc(processMouse);
    	glutMainLoop();
    }
    
  2. “processMouse” is the method processes the mouse inputs.
    void processMouse(int button, int state, int x, int y)
    {
    	//Your code goes here!
    }
    
    • “x” and “y” are the mouse coordinates, they are sometimes incorrect when the window is scaled. (This can be fixed by updating the gluOrtho2D to match the window size.)
    • “state” indicates wether the mouse button is up or down. So in order to check this you would check it against “GLUT_UP” or “GLUT_DOWN” as follows:
      void processMouse(int button, int state, int x, int y)
      {
      	if(state == GLUT_DOWN)
      	{
      		//your code
      	}
      	else
      	{
      		//alternate code
      	}
      }
      
    • “button” indicates which mouse button was clicked, it can be checked against “GLUT_LEFT_BUTTON” or “GLUT_RIGHT_BUTTON” or “GLUT_MIDDLE_BUTTON”. To get accurate results on a “Left/Middle/Right Click” event you should combine the GLUT_DOWN with the GLUT_(l/m/r)_BUTTON as follows:
      void processMouse(int button, int state, int x, int y)
      {
      	if(state == GLUT_DOWN)
      	{
      		if(button == GLUT_LEFT_BUTTON)
      		{
      			//Left Button code.
      		}
      		else if(button == GLUT_MIDDLE_BUTTON)
      		{
      			//middle button code
      		}
      		else if(button == GLUT_RIGHT_BUTTON)
      		{
      			//right button code
      		}
      	}
      	else
      	{
      		//alternate code
      	}
      }
      
The Code: Mouse Active/Passive Motion
  1. To tell the window to listen to “Mouse Movement” then you have to add “glutMotionFunc(processMouseActiveMotion)” for mouse movement when the left button is held down and “glutPassiveMotionFunc(processMousePassiveMotion)” when no button is held down as below:
    int main(int argc, char** argv)
    {
    	...
    	glutMotionFunc(processMouseActiveMotion);
    	glutPassiveMotionFunc(processMousePassiveMotion)
    	glutMainLoop();
    }
    
  2. “processMouseActiveMotion” && “processMousePassiveMotion” are the methods that process the mouse coordinates. If you the same thing to happen in both cases, then “glutMotionFunc” and “glutPassiveMotionFunc” should take the same method as input.
    void processMouseActiveMotion(int x, int y)
    {
    	//Your code goes here!
    }
    
    void processMousePassiveMotion(int x, int y)
    {
    	//Your code goes here!
    }
    

    As stated before, “x” and “y” are the mouse coordinates.

And that’s all you have to do to have mouse interaction!

How To: Set Up GLUT for Eclipse on Windows 7

You must first have Eclipse c++. If you don’t then download it from the Eclipse website. I used the MinGW compiler and the FreeGLUT libraries with Eclipse 3.4 on Windows 7.

The Compiler
  1. Download the MinGW compiler from [link]
  2. Unzip MinGW.zip to C:\Program Files\MinGW or wherever it is you want.
  3. Go to Environment Variables in Windows and add the bin directory of MinGW to the PATH variable in System variables.
  4. Open the “Start Menu” and right click “My Computer”, choose properties. Click “Advanced Setting” then click “Environment Variables”
  5. Then scroll down to “Path” in the System Variables and click edit
  6. Append “;C:\Program Files\MinGW\bin” to the end of the Value
  7. To make sure that MinGW is working write the following commands in the command prompt.
    make --version
    g++ --version
FreeGlut
  1. Download freeGlut from [link]
  2. Copy the freeglut.dll to “C:\Windows\System32″
  3. Copy the contents of include\GL to “C:\MinGW\include\GL”
  4. Copy the contents of lib to “C:\MinGW\lib”
Create a new project
  1. Create a new C++ project.
  2. Uncheck the “Show project types”  checkbox if it’s already not checked

  3. Choose “Executable > Hello World c++” from “Project Type” and “MinGW GCC” from “Toolchains” and click finish.
  4. Now we have to link freeGLUT binaries to the compiler. Right click on your project and select “Properties”.
  5. Go to “C/C++ Build Settings” and select the tab “Tool Settings”.
  6. Select “Libraries” under “MinGW C++ Linker”. Add the following entries to the libraries:
    glu32
    opengl32
    freeglut

  7. You need to repeat this section for every OpenGL project you create

How To: Create JS Objects

While playing around with the canvas element, and having more than one object and each object having its specific actions, I thought the best way to manage it would be by using JS objects. At first I thought it was going to be kind of difficult but it’s not! It REAL easy. So far I found 2 approaches on how to create JS objects.

The JAVA like approach
  1. First we will call the object “myObject” and it takes one parameter called “input”
    function myObject(input)
    {
    }
    
  2. Now if you want the object to have properties or “Instance Variables” you will write as follows:
    function myObject(input)
    {
        this.x = 25;
        this.y = 25;
        this.name='max';
        this.input = input;
    }
    
  3. There is two ways to add methods to an object.

    Approach one:

    function myObject(input)
    {
        this.x = 25;
        this.y = 25;
        this.input = input;
        this.method1 = function(){ alert(this.input); }
    }
    

    Approach two:

    function alertInput()
    {
        alert(this.input);
    }
    function myObject(input)
    {
        this.x = 25;
        this.y = 25;
        this.input = input;
        this.method1 = alertInput;
    }
    
  4. Now all that’s left is to use the code.
    
    
The Array like approach
  1. In this approach you cannot create a new instance of myObject. I haven’t found a way to do so or any reference that shows how, so correct me if I am wrong.
    var input = 2;  //or whatever
    var myObject = {
        x : 25,
        y : 25,
        name: 'max',
        input : input,
        method1 : function(){alert(this.input)}
    };
    myObject.method1();
    
  2. Alternatively you can also use the second approach for the methods:
    function alertInput()
    {
        alert(this.input);
    }
    var myObject = {
        x : 25,
        y : 25,
        name: 'max',
        input : 2,
        method1 : alertInput
    };
    
    myObject.method1();
    
HINT

When using a setTimeout in a method (in an object), a little tweak must be made for it to work correctly.
We would normally write the method as such

method1 = function()
{
    alert(this.input);
    setTimeout(method1,1000);
}

So it can be safely assumed that for an object method it would be written as follows:

this.method1 = function()
{
    alert(this.input);
    setTimeout(this.method1,1000);
}

BUT when doing this firebug screams “useless setTimeout call (missing quotes around argument?)”. And if you use

setTimeout('this.method1',1000);

It won’t work. SO the solution is as follows:

var self = this;
this.method1 = function()
{
    alert(self.input);
    setTimeout(self.method1,1000);
};

And this works!! I’m not really sure why it works… I know I should, but I don’t But after a lot of googling around I found this answer If only I could remember the source =(. Why did I use self when refrencing input? Because if you don’t it will alert the correct answer only the first time, then it will alert ‘undefined’. The same is applied to the array like approach.

var myObject = {
		x : 25,
		y : 25,
		name: 'max',
		input : 2,
		method1 : alertInput
	};
self = myObject;
function alertInput()
{
    alert(self.input);
    setTimeout(self.method1,1000)
}

PS. I personally named them JAVA and Array like approaches. Seemed easier to do so XD.

[Reading Material] [link], [link].

HassanSelim.me

I know css/css3, I know HTML, I know photoshop but I’m not THAT good at actually designing websites… I haven’t actually tried to design a full fledged site/blog, I’ve always wanted to but I never had the reason to? I guess my very first proper design was my flatpress blog, which was a remake of the Hemingway theme; which as I usually do with all my work: I accidentally deleted it. So it was a first time thing to redesign someone Else’s site who had COMPLETELY different taste than I did, well… That was besides smartsoft where I wasn’t a designer, more like an automated WYSIWYG editor, for 10 or more developers to play with (I kid! It wasn’t really THAT bad…)

ANYHOW quiet a while back I had just joined twitter, started following, started getting followers mostly gucians. I started going to some of the people’s websites, and on this one dudes site (Hassan Selim), the navigation was in tabs and one of the tabs had a text-overflow and the tab was just floating in the air with the text pouring out! If only I could just fix that one tab! (assuming that’s all that I didn’t like =P) So I basically bullied offered Hassan to redesign his website.

So eventfully after a hell lot of photoshoping & a lot of horrid negative critique I ended up with the final thing! Do give feedback? You are allowed to troll and give super negative feedback, but I won’t promise you I’ll be nice afterwards =D. Also it would be helpful if you rate this post depending on how you would rate hassan’s new design, so I’ll know if I should retire or not!

So take a look at the new design >> hassanselim.me
Give him feedback >> feedback@hassanselim.me or @hassanselim0

6 steps to dynamically load pages using drag n drop

In my last post [clickie] I discussed how to implement nested dragging, in this post I’m going to extend it to dynamically loading data with the nested dragging. So you should probably read the other one first. How exactly will this work? There will be a parent node (draggable) which can have an infinite number of child nodes (draggableChild) which in turn can have an infinite number of children and so on. How is this done with nested dragging?
First: Imagine that each parent node has a header and a list of it’s children’s headers, and that each child node can either be another parent node or a child page. The child page consists of header (which appears in the parent page too) and content.


Parent Page Layout

Child Page Layout




Second: It works like this, every time you drag out a child header from it’s parent it’s content is loaded.

Step 1

The parent/child page must have a certain format, which is basically a header section and content section. Any parent page has the exact same skeletal layout, just different content (other divs instead of lorem ipsum). A very Important thing to keep in mind is that the script and styles must appear once in the very first parent. Or the page that dynamically loads the box itself (goto step 6).

I am a child page
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce quis lacus sapien, nec tincidunt purus.

Step 2

There is hundreds of ways to do the next part. So I will do the first one that comes to mind. The headers of the child pages must be added to their perspective parents. So for each child a div will be added for it with the class “draggableChild” and a title that contains the child page url (preview).

Sample Child 1

The HTML

I am a parent page
Sample Child 1
Sample Child 2
Sample Child 3
Sample Child 4

Step 3

You will now notice that there is a slight bug: The dragged box is not above the other boxes… To fix this we will add this JQuery .draggable() option “stack”

$( ".draggable" ).draggable({ stack: ".draggable" });

Step 4

The content of the child page should load when we drag out the child from it’s parent. To do this the script from the previous post must be tweaked. After the drag finishes (stop:) Two things must be added: (1) load the page using the .load(), this will be done in two steps: load the header then load the content (2) remove the draggableChild class and add the draggable class (preview)… For further reading on the .load() clickie

$(this).load($(this).attr('title')+' .header',function(){            //loads the header, after it is done it executes the rst 
	$(this).append('');    //adds a temporary Div, as the load() replaces the content
	$('#temp').load($(this).attr('title')+' .content',function(){    //loads the content
		$('#temp').replaceWith($('#temp').html());                   //replaces the temporary div with the content.   
	});
	$(this).removeClass('draggableChild');       
	$(this).addClass('draggable');
});

The script will be

$('.draggableChild').draggable({
    stack: ".draggable",
    stop:function(event,ui){
        var pos = $(this).position();
        var pos2 = $(this).closest('.draggable').position();
        $(this).css({
            position : "absolute",
            marginLeft : 0,
            marginTop : 0,
            top : pos2.top + pos.top,
            left : pos2.left + pos.left,
        });
        $('body').append($(this));
        $(this).draggable({stop:function(event, ui){[,stack: ".draggable" });
		$(this).load($(this).attr('title')+' .header',function(){
			$(this).append('');
			$('#temp').load($(this).attr('title')+' .content',function(){
				$('#temp').replaceWith($('#temp').html());
			});
				$(this).removeClass('draggableChild');
				$(this).addClass('draggable');
		});
    }
});

Step 5

This script essentially works if there is only have two levels. With more levels this happens preview. Why does this happen? Because the newly added divs are not binded to the draggable() action. So to solve this we will use the .live(), it basically binds a certain action and event to an object which is present on the page now or maybe be present on the page in the future (preview). Further reading: clickie The scripts will be further modified as follows:

$('.draggable').live('mouseover',function(){
    $(this).draggable({ stack: ".draggable" });
});
$('.draggableChild').live('mouseover',function(){
    $(this).draggable({
        stop:function(event,ui){
    	    var pos = $(this).position();
    	    var pos2 = $(this).closest('.draggable').position();
    	    $(this).css({
    	        position : "absolute",
    	        marginLeft : 0,
    	        marginTop : 0,
    	        top : pos2.top + pos.top,
    	        left : pos2.left + pos.left,
    	    });
    	    $('body').append($(this));
            $(this).draggable({stop:function(event, ui){},stack: ".draggable" });
            $(this).load($(this).attr('title')+' .header',function(){
                $(this).append('');
        	$('#temp').load($(this).attr('title')+' .content',function(){
        	    $('#temp').replaceWith($('#temp').html());
        	});
        	$(this).removeClass('draggableChild');
        	$(this).addClass('draggable');
            });
        }
    });
});

Step 6

What if you want a link on your page that opens one of these boxes?? You will first have to remove the scripts and styles from the first parent, and put it on the page you want. Second we will need a function that will open the box. We will call this function openBox(url,el) where url is the url of the box to be loaded, and el is the id of place where you want the box to appear. (preview

function openBox(url,el)
{
	$('#' + el).append('
'); var element = $('#' + el + ' #myTemp') element.load(url, function() { element.children().attr('title', url); element.children().css('z-index','4'); element.replaceWith(element.html()); }); }

The HTML of the front page


	
	

And we are done!

So far this is the basic functionality of dynamically loading content with drag and drop, but there is so many features that can be added, docking/minimizing/maximizing/closing/reverting a little sample.

10 Steps to create nested drag n drop using JQuery

For the new smarter-scrum layout we decided to simulate a semi virtual desktop, which in the end ended up being a melting pot of dragging and dropping, and ALOT of JavaScript. One of the things I had to implement was enabling a draggable element within a draggable element that when dragged out of it’s parent acted independently . Even though it’s not hard to implement using JQuery, I hadn’t come across any web source that explained how to do THAT in particular,which was strange because everything is usually on the web. So I decided to go step by step on how to implement this using JQuery.

  1. First you will need to import JQuery, and JQuery-ui
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js">
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js">
  2. We will use ‘body’ as our workspace, meaning the elements that are being dragged have body as their direct parent. You can use any other element, just make sure that it has a width and height
  3. The parent container will have a class of draggable. JQuery UI has a built in function called draggable, which enables dragging(duh?). So you will need to paste the code below in the head of your document.
    $(function(){
        $('.draggable').draggable();
    });
  4. Now add between the body tag.
    I am a draggable element!
  5. To see draggable options,events & methods goto http://jqueryui.com/demos/draggable/
  6. Any child container will have a class of draggableChild, so that we can diffrentiate between it and it’s parent.
  7. So now we will update our script to:
    $(function(){
        $('.draggable').draggable();
         $('.draggableChild').draggable();
    });

    And change the HTML to:

    I am a draggable element!
    I am a draggableChild element!

    And add a little bit of CSS so it’s easy on the eyes.

    .draggable
    {
        background-color:red;
        padding:10px;
        width:200px;
        height:200px;
        color:white;
    }
    .draggableChild
    {
        background-color:blue;
        padding:10px;
        color:white;
    }
  8. So far if you test this, you will get something that looks like this: clickie. As you can see, after moving the draggableChild out of draggable, then dragging draggable draggableChild moves with it. To fix this, what we will do is after the draggableChild is dragged out of the parent, it will be removed from the parent and added to the ‘body’. So the script will be modified as follows:
    $(function(){
        $('.draggable').draggable();
        $('.draggableChild').draggable({
            stop:function(event,ui){
                $('body').append($(this));
            }
        });
    });
  9. It’s fixed! But after it’s added to the body it’s always added to the bottom. clicke. To fix this we will for the last time modify the script.
    $(function(){
        $('.draggable').draggable();
        $('.draggableChild').draggable({
            stop:function(event,ui){
                var pos = $(this).position();
                var pos2 = $(this).closest('.draggable').position();
                $(this).css({
                    position : "absolute",
                    marginLeft : 0,
                    marginTop : 0,
                    top : pos2.top + pos.top,
                    left : pos2.left + pos.left,
                    width: $(this).css('width'),
                    height: $(this).css('height')
                });
                $('body').append($(this));
                $(this).draggable({stop:function(event, ui){}});
            }
        });
    });
  10. In the previous step, a position fix wand size fix were added; meaning that when you stop dragging the element’s position will be set to the dragged offset + parent offset (since the child’s offset is relative to the parents), it’s css updated and the stop function is removed. clickie here for final outcome.

How To: Connect to a MySQL DB throught Java

In my Databases 1 course I implemented a movie database management system using Java and SQL. And I’ve had many friends ask me how exactly I established the link between Java and SQL. The code is all from my project which I wrote with my friend Pierre. I will be showing code on how to connect to a database, manipulate the results and adding the results to a JTable . So in this guide I am assuming that the database is located on your computer, if it is a remote database you simply adjust the URL and driver; but I am no expert on that so google it?? Also for this to work you must create an ODBC thingie. Also google it as it differs from OS to OS. SO LETS GET ON WITH IT!

Libraries needed

First you will need to import the java.sql library.

import java.sql.*;

Establishing The Connection With the Database

The code below connects to a database “mySampleDB”

String dataSourceName = "mySampleDB";
String username="admin";
String password ="1234";
try
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String dbURL = "jdbc:odbc:" + dataSourceName;
Connection connection = DriverManager.getConnection(dbURL, username, password);
System.out.println("User connected using driver: " + connection.getMetaData().getDriverName());
}
catch (Exception e)
{
System.err.println(e.getMessage()); 
} 

Executing a Query

Assuming music is a table in your database.

String myQuery = "SELECT * FROM music";
Statement statement = connection.createStatement();
statement.executeQuery(myQuery);

Manipulating the Query Results

To access the result data we will use:

String myQuery = "SELECT * FROM music";
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(myQuery);

To access the column names we will use:

ResultSetMetaData rsm = resultSet.getMetaData();

Adding the result set to a JTable

This method returns a TableModel. You then use the JTable.setDefaultTableModel() method. Not all JDBC drivers offer the .getRow() function, so instead we will execute an extra query that fetches the row count. (It changed depending on your query). The result must be split into an array for the column headers and a 2D array for the data. Below is the full code.

public static javax.swing.table.DefaultTableModel executeStatement(String a) {
	String dataSourceName = "mySampleDB";
	String username = "admin";
	String password = "1234";
	String myQuery = "SELECT * FROM music";
	String rowQuery = "SELECT COUNT(*) AS rowcount FROM music";

	// output is a 2D array of the results
	Object[][] output = new Object[1][1];

	// cols is an array of the column headers
	Object[] cols = new Object[1];

	// The number of columns in the result set
	int numOfColumns;

	try {
		Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
		String dbURL = "jdbc:odbc:" + dataSourceName;
		Connection connection = DriverManager.getConnection(dbURL,
				username, password);
		System.out.println("User connected using driver: "
				+ connection.getMetaData().getDriverName());
		Statement statement = connection.createStatement();

		// This is used to get the row count
		ResultSet rowCount = statement.executeQuery(rowQuery);
		rowCount.next();
		int rows = rowCount.getInt("rowcount");
		rowCount.close();

		ResultSet resultSet = statement.executeQuery(myQuery);
		ResultSetMetaData rsm = resultSet.getMetaData();
		numOfColumns = rsm.getColumnCount();
		output = new Object[rsm.getColumnCount()][rows];
		cols = new Object[rsm.getColumnCount()];

		while (resultSet.next()) {
			int j = 0;
			for (int i = 0; i < = numOfColumns; i++) {
				if (i == 0) {
					cols[i] = rsm.getColumnName(i + 1);
				}
				output[j][i] = resultSet.getObject(i + 1);
			}
			j++;
		}
		resultSet.close();
	} catch (Exception e) {
		System.err.println(e.getMessage());
	}
	javax.swing.table.DefaultTableModel finalO = new javax.swing.table.DefaultTableModel(
			output, cols);

	return finalO;
}