Showing posts with label how-to. Show all posts
Showing posts with label how-to. Show all posts

Wednesday, 19 March 2014

Customizing django-registration


Whatz up?!

The integration of django-register is awesome! But if you want to customize it with additional models it can be confusing.

Here in example I will show how to create your custom backend, form to handle it (custom validator and model choice field).

Note, the django I use is version v1.5.4 django-registration v1.0. Some line breaks are imposed due to layout of this page.

Thus, bellow you will find everything you need to:
  • Create custom backend
  • Add custom form 
  • Create custom validation
  • Badabung! :D

Below is and example extending
from registration.backends.default.views.RegistrationView
First of all, inherit RegistrationView, then override register() and get_form_class() functions. In the examples to follow it is assumed that the class is saved to regbackend.py.
#regbackend.py
from registration.backends.default.views import RegistrationView

#create custom registration backend
class StudentBackend(RegistrationView): 
    '''
    we just want to override register and fix profile creation
    ''' 
    def register(self,request, **kwargs):
        from usermanager.models import Profile
        user=super(StudentBackend,self).register(request, **kwargs)
        user.first_name = kwargs['first_name']
        user.last_name = kwargs['last_name']
        user.save()
        profile = Profile.objects.create(
                                user=user, course=kwargs['course'])
        profile.save()
        
    def get_form_class(self, request):
        """
        Return the default form class used for user registration.

        """
        from usermanager.form import UserRegistrationForm
        return UserRegistrationForm    
Below is the code from urls.py. Nothing fancy, just import your registration backend, and form, and redirect accounts/register/ to your backend.
#urls.py
from regbackend import StudentBackend
from form import UserRegistrationForm

urlpatterns = patterns('',
    url(r'^accounts/register/$',
        StudentBackend.as_view(form_class = UserRegistrationForm),
        name='registration_register'),
    (r'^accounts/', include('registration.backends.default.urls')),
    #more url configs
)
Following code is from form.py:
#form.py
from django import forms
from django.contrib.auth.models import User
from usermanager.models import Course, Profile
from registration.forms import RegistrationForm
from django.utils.translation import ugettext_lazy as _



attrs_dict = { 'class': 'required' }

#this function checks for the allowed domain:
def affiliation_valid_email(value):
    allowed_domain=['domain.se','domain.se']
    #not the prettiest soliution 
    v_error=_("Email does not match allowed domains (%s, %s)"
                           %(allowed_domain[0],allowed_domain[1])
    if value.split('@')[1] not in allowed_domain:
        raise forms.ValidationError(v_error)
    else:
        return value


#the registration form is inherited from django-registration   
class UserRegistrationForm(RegistrationForm):  
    
    class Meta:
        model = User
        fields = ("first_name",
                  "last_name",
                  "username", 
                  "email", 
                  "password1", 
                  "password2")
    #username is enforced to some particular rules 
    u_error = _("User name needs to match domain convention.")   
    username = forms.RegexField(regex=r'^\w',
                                max_length=9,
                                widget=forms.TextInput(attrs=attrs_dict),
                                label=_("Username - same as in domain!"),
                                error_messages={ 
                                'invalid': u_error })
    first_name = forms.CharField(max_length=30)
    last_name = forms.CharField(max_length=30)
    course = forms.ModelChoiceField(queryset=Course.objects,required=True)
    email = forms.EmailField(validators=[affiliation_valid_email],
                             widget=forms.TextInput(
                                     attrs=dict(attrs_dict,maxlength=75)
                                     ),
                                     label=_("domain - Email address"))
    

    
    def clean(self):
        #clean with super
        ue_error = _("Email and user name do not match.")
        super(UserRegistrationForm, self).clean()
        #this is just checking that username is the same as in email
        if self.cleaned_data['email'].split('@')[0] == 
                                        self.cleaned_data.get("username"):
            return self.cleaned_data
        else:
            raise forms.ValidationError(ue_error)
         
    def save(self, commit=True):
        user = super(UserRegistrationForm, self).save(commit=True)    
        user.email = self.cleaned_data["email"]
        user.first_name =  self.cleaned_data["first_name"]
        user.last_name =self.cleaned_data["last_name"]
        profile = Profile(
                   systemuser=user, course = self.cleaned_data["course"])

    if self.commit:
        user.save()
        profile.save()
    return user

Models used in this example:
#models.py

class Course(models.Model):
    code = models.CharField(max_length=6)
    teacher = models.CharField(max_length=30)
    
    class Meta:
        app_label = "usermanager"
        verbose_name = "Course"
        verbose_name_plural = "Courses"
    
    def __unicode__(self):
        return "%s" % self.code
    
class Profile(models.Model):
    user=models.ForeignKey(User, unique=True)
    course=models.ForeignKey('usermanager.Course')
    created = models.DateTimeField(auto_now_add=True)
    updated_local = models.DateTimeField(blank=True, null=True)
    

    def getCourse(self):
        return "%s" %self.course
    
    def save(self,*args,**kwargs):
        self.updated_local = datetime.now()
        super(Profile, self).save(*args,**kwargs)
    
    def __unicode__(self):
        return "Profile: %s" %self.user

Finally, remember to enable registration in installed apps before running
python manage.py syncdb
INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'django.contrib.admindocs',
    'registration',
)
That's it foks, happy coding! L

Tuesday, 7 August 2012

Install and run NS3 on Amazons EC2

This is simple step-by step on how to run NS3 on Amazon cloud. If you skip to 3 you can use same script on any other machine using Ubuntu.

This script will install needed packages, download ns3, make standard configuration, build ns-3-dev, and will run test.

Assuming you have Amazon account.

  1. Create Ubuntu 12.04 image
  2. Log in to it
  3. Create file installns3.sh
  4. vi installns3.sh
    i
    
  5. Copy following code into it:
  6. #!/bin/bash
    #original timer was published in
    #http://www.linuxjournal.com/
    #http://tiny.cc/en2niw 
    #by Mitch Frazier
    function timer()
    {
     if [[ $# -eq 0 ]]; then
      echo $(date '+%s')
     else
      local  stime=$1
      etime=$(date '+%s')
             if [[ -z "$stime" ]]; then stime=$etime; fi
             dt=$((etime - stime))
             ds=$((dt % 60))
             dm=$(((dt / 60) % 60))
      dh=$((dt / 3600))
      printf '%d:%02d:%02d' $dh $dm $ds
     fi
    }
    tmr=$(timer)
    INSTALL_DIR="/home/ubuntu/dev/ns3"
    #files to install 
    APPS="gcc g++ python python-dev mercurial bzr gdb valgrind gsl-bin \
     libgsl0-dev libgsl0ldbl flex bison libfl-dev tcpdump sqlite sqlite3 \
     libsqlite3-dev libxml2 libxml2-dev libgtk2.0-0 libgtk2.0-dev vtun \
     lxc uncrustify doxygen graphviz imagemagick texlive texlive-extra-utils \ 
     texlive-latex-extra python-sphinx dia python-pygraphviz python-kiwi \
     python-pygoocanvas libgoocanvas-dev libboost-signals-dev \ 
     libboost-filesystem-dev openmpi-bin libopenmpi-dev openmpi-doc"
    # update repos
    RETVAL=$(sudo apt-get update)
    if [ $? -ne 0 ]; then
     echo "Unable to update, reason: $?"
     echo $RETVAL
     exit 1
    else
     echo "Successfully updated app repostitory"
    fi
    #function to handle instaliation 
    function make_install(){
     if [ $# == 0 ]; then
             echo "must give at least one argument"
      exit 1
     fi
     for app in $*
     do
      #we do not care is packet is installed it is success
      RETVAL=$(sudo apt-get install -y $app 2>&1 >/dev/null)
      if [ $? -ne 0 ]; then
       echo "Failure: can't install $app reson: $?"
              echo $RETVAL
              echo "Skipping package $app" 
      else
       echo "Succesfully installed $app"
      fi
    
     done
    }
    
    #create directory
    if [ ! -d "$INSTALL_DIR" ]; then
     echo "Creating $INSTALL_DIR"
     RET=$(mkdir -p $INSTALL_DIR 2>&1 >/dev/null)
     if [ $? -ne 0 ]; then
      echo "Can not create directory $INSTALL_DIR. Reason: $?"
      echo $RET
      exit 1
     else
      echo "Succesfully created directory $INSTALL_DIR"
     fi
    fi
    #check if port is open
    
    #install apps
    make_install $APPS
    
    cd $INSTALL_DIR
    echo "Cloning repo"
    RET=$(hg clone http://code.nsnam.org/ns-3-allinone)
    if [ $? -ne 0 ]; then
     echo "Could not clone ns-3-allinone. REASON: $?"
     echo $RET
     exit 1
    else
     echo "Cloning was successfull"
    fi
    cd "ns-3-allinone"
    echo "Downloading ns3-dev"
    chmod +x download.py
    ./download.py -n ns-3-dev
    cd "ns-3-dev"
    echo "Building standart ns3"
    ./waf configure --enable-tests
    ./waf build
    echo "Running test"
    chmod +x test.py
    ./test.py
    printf 'Elapsed time: %s\n' $(timer $tmr) 
    echo "Thank you! Enjoy NS3"
    
  7. Save file and execute it.
  8. #hit esc
    :wq
    chmod +x installns3.sh
    ./installns3.sh
    #go grab coffee
    
  9. It will take a while, I was using medium instance which took: ~34 min.
If you are to lazy to copy paste and bother, find "ubuntu-12.04-ns-3-dev" AMI in community AMI's I have published pre-installed and pre-build version of the image. It will save you time and buck too!

Cheers :)

Monday, 6 August 2012

TOSSIM simulations on Amazon AWS

There can be many reasons why you want to run your TOSSIM simulations on cloud.
  • Share same apps and environment with your coworkers.
  • Give access to students.
  • Run gi-norm-ous  simulation.
  • etc
Edit: if you for some reason do not want to create your own installation, search publics for ubuntu-12.04-tinyos-tossim, I have published an AMI with preinstalled TinyOS 2.1.1 and svn version ready to use!
 
What ever reason is here is how-to guide for running both release and svn version of TinyOS simulator TOSSIM, one assumption is that you have AWS account.
  1. Create  EBS volume.
  2. Create EC2 instance and start it (it is enough to have ssh port open), type does not matter since you can change it later. The only assumption that you run Ubuntu 12.04 64 bit version.
  3. Log in to the instance
  4. Create and edit source file
  5. sudo vi /etc/apt/sources.list.d/tinyos.list
    #in vi paste
    deb http://tinyos.stanford.edu/tinyos/dists/ubuntu natty main
    #hit esc and 
    :wq
    
  6. Install main release of TinyOS
  7. sudo apt-get update && sudo apt-get install -y --force-yes tinyos-2.1.1
    #fix ownership 
    sudo chown -R ubuntu:ubuntu /opt/tinyos-2.1.1
    
    With the -y --force-yes following packages will be installed:
    Setting up libasound2 (1.0.25-1ubuntu10.1) ...
    Setting up libasyncns0 (0.8-4) ...
    Setting up libatk1.0-data (2.4.0-0ubuntu1) ...
    Setting up libatk1.0-0 (2.4.0-0ubuntu1) ...
    Setting up libgtk2.0-common (2.24.10-0ubuntu6) ...
    Setting up ttf-dejavu-core (2.33-2ubuntu1) ...
    Setting up fontconfig-config (2.8.0-3ubuntu9) ...
    Setting up libfontconfig1 (2.8.0-3ubuntu9) ...
    Setting up libpixman-1-0 (0.24.4-1) ...
    Setting up libxcb-render0 (1.8.1-1) ...
    Setting up libxcb-shm0 (1.8.1-1) ...
    Setting up libxrender1 (1:0.9.6-2build1) ...
    Setting up libcairo2 (1.10.2-6.1ubuntu3) ...
    Setting up libavahi-common-data (0.6.30-5ubuntu2) ...
    Setting up libavahi-common3 (0.6.30-5ubuntu2) ...
    Setting up libavahi-client3 (0.6.30-5ubuntu2) ...
    Setting up libcups2 (1.5.3-0ubuntu2) ...
    Setting up libjpeg-turbo8 (1.1.90+svn733-0ubuntu4.1) ...
    Setting up libjpeg8 (8c-2ubuntu7) ...
    Setting up libjasper1 (1.900.1-13) ...
    Setting up libtiff4 (3.9.5-2ubuntu1.2) ...
    Setting up libgdk-pixbuf2.0-common (2.26.1-1) ...
    Setting up libgdk-pixbuf2.0-0 (2.26.1-1) ...
    Setting up libthai-data (0.1.16-3) ...
    Setting up libdatrie1 (0.2.5-3) ...
    Setting up libthai0 (0.1.16-3) ...
    Setting up libxft2 (2.2.0-3ubuntu2) ...
    Setting up fontconfig (2.8.0-3ubuntu9) ...
    Cleaning up old fontconfig caches... done.
    Regenerating fonts cache... done.
    Setting up libpango1.0-0 (1.30.0-0ubuntu3.1) ...
    Setting up libxcomposite1 (1:0.4.3-2build1) ...
    Setting up libxfixes3 (1:5.0-4ubuntu4) ...
    Setting up libxcursor1 (1:1.1.12-1) ...
    Setting up libxdamage1 (1:1.1.3-2build1) ...
    Setting up libxi6 (2:1.6.0-0ubuntu2) ...
    Setting up libxinerama1 (2:1.1.1-3build1) ...
    Setting up libxrandr2 (2:1.3.2-2) ...
    Setting up shared-mime-info (1.0-0ubuntu4.1) ...
    Setting up libgtk2.0-0 (2.24.10-0ubuntu6) ...
    Setting up libnspr4 (4.8.9-1ubuntu2) ...
    Setting up libnss3 (3.13.1.with.ckbi.1.88-1ubuntu6) ...
    Setting up libnss3-1d (3.13.1.with.ckbi.1.88-1ubuntu6) ...
    Setting up tzdata-java (2012b-1) ...
    Setting up java-common (0.43ubuntu2) ...
    Setting up libgif4 (4.1.6-9ubuntu1) ...
    Setting up libjson0 (0.9-1ubuntu1) ...
    Setting up libogg0 (1.2.2~dfsg-1ubuntu1) ...
    Setting up libflac8 (1.2.1-6) ...
    Setting up libvorbis0a (1.3.2-1ubuntu3) ...
    Setting up libvorbisenc2 (1.3.2-1ubuntu3) ...
    Setting up libsndfile1 (1.0.25-4) ...
    Setting up libpulse0 (1:1.1-0ubuntu15.1) ...
    Setting up x11-common (1:7.6+12ubuntu1) ...
    Setting up libxtst6 (2:1.2.0-4) ...
    Setting up libgomp1 (4.6.3-1ubuntu5) ...
    Setting up libice6 (2:1.0.7-2build1) ...
    Setting up libmpfr4 (3.1.0-3ubuntu2) ...
    Setting up libquadmath0 (4.6.3-1ubuntu5) ...
    Setting up libsm6 (2:1.2.0-2build1) ...
    Setting up libxt6 (1:1.1.1-2build1) ...
    Setting up libxmu6 (2:1.1.0-3) ...
    Setting up libxpm4 (1:3.5.9-4) ...
    Setting up libxaw7 (2:1.0.9-3ubuntu1) ...
    Setting up libgd2-noxpm (2.0.36~rc1~dfsg-6ubuntu2) ...
    Setting up libmpc2 (0.9-4) ...
    Setting up tinyos-base (2.1-20080806) ...
    Setting up avr-tinyos-base (2.1-20080806) ...
    Setting up avr-binutils-tinyos (2.17-20080812) ...
    Setting up avr-gcc-tinyos (4.1.2-20080812) ...
    Setting up avr-libc-tinyos (1.4.7-20080812) ...
    Setting up avrdude-tinyos (5.4-20080812) ...
    Setting up avr-tinyos (2.1-20080806) ...
    Setting up avr-optional-tinyos (2.1-20090326) ...
    Setting up binutils (2.22-6ubuntu1) ...
    Setting up cpp-4.6 (4.6.3-1ubuntu5) ...
    Setting up cpp (4:4.6.3-1ubuntu5) ...
    Setting up libc-dev-bin (2.15-0ubuntu10) ...
    Setting up linux-libc-dev (3.2.0-27.43) ...
    Setting up libc6-dev (2.15-0ubuntu10) ...
    Setting up nesc (1.3.3-20110821) ...
    Setting up tinyos-tools (1.4.0-20100326) ...
    Setting up deputy-tinyos (1.1-20080807) ...
    Setting up fonts-liberation (1.07.0-2ubuntu0.1) ...
    Setting up gcc-4.6 (4.6.3-1ubuntu5) ...
    Setting up gcc (4:4.6.3-1ubuntu5) ...
    Setting up libcdt4 (2.26.3-10ubuntu1) ...
    Setting up libcgraph5 (2.26.3-10ubuntu1) ...
    Setting up libgraph4 (2.26.3-10ubuntu1) ...
    Setting up libpathplan4 (2.26.3-10ubuntu1) ...
    Setting up libgvc5 (2.26.3-10ubuntu1) ...
    Setting up libgvpr1 (2.26.3-10ubuntu1) ...
    Setting up graphviz (2.26.3-10ubuntu1) ...
    Setting up hicolor-icon-theme (0.12-1ubuntu2) ...
    Setting up libgtk2.0-bin (2.24.10-0ubuntu6) ...
    Setting up xorg-sgml-doctools (1:1.10-1) ...
    Setting up x11proto-core-dev (7.0.22-1) ...
    Setting up libice-dev (2:1.0.7-2build1) ...
    Setting up libpthread-stubs0 (0.3-3) ...
    Setting up libpthread-stubs0-dev (0.3-3) ...
    Setting up libsm-dev (2:1.2.0-2build1) ...
    Setting up libxau-dev (1:1.0.6-4) ...
    Setting up libxdmcp-dev (1:1.1.0-4) ...
    Setting up x11proto-input-dev (2.1.99.6-1) ...
    Setting up x11proto-kb-dev (1.0.5-2) ...
    Setting up xtrans-dev (1.2.6-2) ...
    Setting up libxcb1-dev (1.8.1-1) ...
    Setting up libx11-dev (2:1.4.99.1-0ubuntu2) ...
    Setting up libx11-doc (2:1.4.99.1-0ubuntu2) ...
    Setting up libxt-dev (1:1.1.1-2build1) ...
    Setting up manpages-dev (3.35-0.1ubuntu1) ...
    Setting up msp430-binutils-tinyos (2.21.1-20110821) ...
    Setting up msp430-gcc-tinyos (4.5.3-20110821) ...
    Setting up msp430-libc-tinyos (20110612-20110821) ...
    Setting up msp430mcu-tinyos (20110613-20110821) ...
    Setting up msp430-tinyos (20110821) ...
    Setting up tinyos-required-msp430 (2.1-20090326) ...
    Setting up tinyos-required-avr (2.1-20090326) ...
    Setting up tinyos-required-all (2.1-20090326) ...
    Setting up tinyos-2.1.1 (2.1.1-20100401) ...
    Setting up ttf-dejavu-extra (2.33-2ubuntu1) ...
    Setting up ttf-liberation (1.07.0-2ubuntu0.1) ...
    Setting up icedtea-netx-common (1.2-2ubuntu1.1) ...
    Setting up openjdk-6-jre-headless (6b24-1.11.3-1ubuntu0.12.04.1) ...
    
  8. Install svn release of TinyOS, the directory root is of your chois, I just like keep things organised
  9. sudo apt-get install subversion
    mkdir /home/your_user/dev
    cd dev
    mkdir tiny-os-svn
    #checkout the trunk version
    svn checkout http://tinyos-main.googlecode.com/svn/trunk/ tinyos-main-read-only
    
    
    
  10. Fix .bashrc
  11. vi .bashrc
    i
    #paste
    TOSROOT_BASE="/opt/tinyos-2.1.1"
    TOSROOT_SVN="/home/ubuntu/dev/tiny-os-svn/trunk"
    #TOSROOT=$TOSROOT_SVN #swap TOSROOT to change to different version of TinyOS
    TOSROOT=$TOSROOT_BASE 
    TOSDIR="$TOSROOT/tos"
    CLASSPATH=.:$TOSROOT/support/sdk/java:$TOSROOT/support/sdk/java/tinyos.jar:$CLASSPATH
    MAKERULES="$TOSROOT/support/make/Makerules"
    PYTHONPATH=$PYTHONPATH:$TOSROOT/support/sdk/python
    export TOSROOT
    export TOSDIR
    export CLASSPATH
    export MAKERULES
    export PYTHONPATH
    
    #reload bash
    source /home/ubuntu/.bashrc
    
  12. Fix JNI
  13. sudo tos-install-jni
    
  14. Install build tools
  15. sudo apt-get install build-essential python python-dev gdb
    
  16. Fix python version
  17. vi /opt/tinyos-2.1.1/support/make/sim.extra
    i
    #change PYTHON_VERSION=2.5 to
    PYTHON_VERSION ?= $(shell python --version 2>&1 | sed 's/Python 2\.\([0-9]\)\.[0-9]+\{0,1\}/2.\1/')
    
  18. Test installiation
  19. cd dev/tiny-os-svn/trunk/apps/Blink
    make micaz sim
    #should end with 
    *** Successfully built micaz TOSSIM library.
    
  20. Create and run simulation
  21. cd /opt/tinyos-2.1.1/apps/RadioCountToLeds
    make micaz sim
    
    Create topo.txt
    0  2 -66.0
     2  0 -67.0
     1  2 -54.0
     2  1 -55.0
     1  3 -60.0
     3  1 -60.0
     2  3 -64.0
     3  2 -64.0
    
    Create python packet.py (this is edited and fixed version of original packet.py)
    import sys
    from TOSSIM import *
    from RadioCountMsg import *
    
    t = Tossim([])
    m = t.mac();
    r = t.radio();
    
    t.addChannel("RadioCountToLedsC", sys.stdout)
    t.addChannel("LedsC", sys.stdout)
    
    for i in range(0, 2):
      m = t.getNode(i);
      m.bootAtTime((31 + t.ticksPerSecond() / 10) * i + 1)
    
    f = open("topo.txt", "r")
    lines = f.readlines()
    for line in lines:
      s = line.split()
      if (len(s) > 0):
        if (s[0] == "gain"):
          r.add(int(s[1]), int(s[2]), float(s[3]))
    
    noise = open("/opt/tinyos-2.1.1/tos/lib/tossim/noise/meyer-heavy.txt", "r")
    lines = noise.readlines()
    for line in lines:
      st = line.strip()
      if (st != ""):
        val = int(st)
        for i in range(0, 2):
          t.getNode(i).addNoiseTraceReading(val)
    
    for i in range(0, 60):
      t.runNextEvent()
    
    msg = RadioCountMsg()
    msg.set_counter(7)
    pkt = t.newPacket()
    pkt.setData(msg.data)
    pkt.setType(msg.get_amType())
    pkt.setDestination(0)
    
    print "Delivering %s to 0 at %s" %(str(msg),str(t.time() + 3))
    pkt.deliver(0, t.time() + 3)
    
    
    for i in range(0, 20):
      t.runNextEvent()
    
    
    Run in sequence
    python packet.py
    
     
    Lots of pretty output. Done! 
    For more info on simulations see http://docs.tinyos.net/tinywiki/index.php/TOSSIM. 
    Remember to stop your instance when you done!
    Happy WSN simulations!