Saturday, March 19, 2011

Copying Array's Content to Another

Several methods used to copy the contents of an array to another.

Random r = new Random();
int[] pins = new int[4]{ r.Next() % 10, r.Next() % 10,
                         r.Next() % 10, r.Next() % 10 };

// 1st method
int[] copy = new int[pins.Length];
for (int i = 0; i < pins.Length; i++ )
{
 copy[i] = pins[i];
}

// 2nd method
int[] copy2 = new int[pins.Length];
pins.CopyTo(copy2, 0); //starting from index 0 of copy2

// 3rd method
int[] copy3 = new int[pins.Length];
Array.Copy(pins,copy3,copy3.Length);

// 4th method
int[] copy4 = new int[pins.Length];
copy4 = (int[])pins.Clone();

All of them are copying the reference of the original array, not the value.

Friday, March 11, 2011

Step Through Codes during Debugging Process

  • Right-click at the starting line of the code which you want to analyze
  • Select "Run to cursor"
  • Your program will be run. Enter some values to test the code
  • In the lower-left side, choose 'Local' tab. Here, you can monitor the local variables assignment. 
  • Debug -> Step into (shortcut: F11), to run the next code
  • Do the last step for several time while monitoring the 'Local' tab, until you figure out how your code works.

Wednesday, March 9, 2011

Browse and Display Text File (C#)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;          //namespace buat OpenFileDialog 
using System.IO;

namespace BrowseAndDisplay
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {

        public MainWindow()
        {
            InitializeComponent();
        }

        private void buttonClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void buttonBrowse_Click(object sender, RoutedEventArgs e)
        {
            //create an instance of the open file dialog box
            OpenFileDialog openFileDialog = new OpenFileDialog();

            openFileDialog.InitialDirectory = "C:";
            openFileDialog.Title = "Choose one of the text file";
            openFileDialog.FileName = "";
            openFileDialog.Filter = "Text file|*.txt";

            openFileDialog.ShowDialog();

            //isi textBox FileLocation dengan path file yang akan dibuka
            textBoxFileLocation.Text = openFileDialog.FileName;

            //tampilkan isi file text ke textBox DisplayTextFile
            FileInfo src = new FileInfo(openFileDialog.FileName);

            textBoxDisplayTextFile.Text = "";
            TextReader reader = src.OpenText();
            string line = reader.ReadLine();

            while (line != null)
            {
                textBoxDisplayTextFile.Text += line + '\n';
                line = reader.ReadLine();
            }
            reader.Close();
        }
    }
}



    
        
            
            
        
        

Saturday, September 11, 2010

Retrieve MP3 Metadata

I know, there are many modules can be used: eyeD3, mutagen, etc. But I think it is a good idea to understand first what is the concept of MP3 metadata.

Based on this Wikipedia article, the ID3v1 metadata container (which I used for this script) occupies 128 bytes beginning with the string TAG. The tag is placed at the end of the file to maintain compatibility with older media players.

ID3v1 consists of the following informations, including the bytes position:


for deeper information about ID3, including the extended tags, visit Wikipedia link above.

Just in case you haven't got this information yet, in Windows, you must read MP3 file as binary file, therefore you should use 'rb' for open function.

Here is my script:
import sys

filename = sys.argv[1]

fsock = open(filename, "rb", 0)
fsock.seek(-128,2) # get the last 128 bytes
tagdata = fsock.read(128)

fsock.close()

if tagdata[:3] == "TAG":
print "title\t: ", tagdata[3:33]
print "artist\t: ", tagdata[33:63]
print "album\t: ", tagdata[63:93]
print "year\t: ", tagdata[93:97]
print "comment\t: ", tagdata[97:126]
print "genre\t: ", tagdata[127:128]

Sunday, August 29, 2010

HTML Parsing using HTMLParser

Simple script to get the video download link from here, which are hosted at archive.org
This script is adapted from here.

HTMLParser usage
from Python documentation:

Usage:
    p = HTMLParser()
    p.feed(data)
    ...
    p.close()

Start tags are handled by calling handle_starttag() or
handle_startendtag(); end tags by handle_endtag().  The
data between tags is passed from the parser to the derived class
by calling handle_data() with the data as argument (the data
may be split up in arbitrary chunks).  Entity references are
passed by calling handle_entityref() with the entity
reference as the argument.  Numeric character references are
passed to handle_charref() with the string containing the
reference as the argument.

import sys
import urllib
import HTMLParser
import re

class GetLinks(HTMLParser.HTMLParser):
    def handle_starttag(self,tag,attrs):
        if tag == 'a':
            for name,value in attrs:
                if name == 'href':
                    if re.search('ArabicLanguageCourseVideos',value):
                        print(value)
                    
gl = GetLinks()
url = 'http://www.lqtoronto.com/videodl.html'

urlconn = urllib.urlopen(url)

# read and put the downloaded html code into url content
urlcontents = urlconn.read()

# input the downloaded material into HTMLParser's member function 
# for parsing
gl.feed(urlcontents)

Friday, August 27, 2010

Socket Exception Handlers

Based on book 'Foundations of Python Network Programming' chapter 2.

Based on Python documentation, there are four socket exceptions (error, herror, gaierror, timeout). Here, I only use the socket.error only. It is used for general I/O and communication problems.

For an illustration, try the following from command line:
> python.exe socket.py google.com 80 index.html

import socket,sys

# standard input
host = sys.argv[1]
port = sys.argv[2]
filename = sys.argv[3]

# error handler 
def errorHandler(message,e):
    print('{0} {1}' .format(message,e))
    sys.exit(1)
    
# create socket 
try:
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
except socket.error, e:
    errorHandler('Socket creation error: ',e)

# input port manipulation
try:
    port = int(port)
except ValueError,e:
    errorHandler('Error port number: ',e)

# connection initiation
try:
    s.connect((host,port))
except socket.error, e:
    errorHandler('error socket initiation: ',e)
    
# sending HTTP request
try:
    s.sendall("GET %s HTTP/1.0\r\n\r\n" % filename)
except socket.error, e:
    errorHandler('Error sending HTTP request: ',e)
    
# receiving data from server
while 1:
    try:
        buf = s.recv(2048)
    except socket.error, e:
        errorHandler('Error receiving data: ',e)
    if not len(buf):
        break
    sys.stdout.write(buf)

Monday, August 23, 2010

Install zope.interface for Twisted

Twisted uses Zope Interface to define and document APIs.
  1. Download it from here. It's in egg format. Choose the appropriate Python version with ours.
  2. To install .egg, we need 'Easy Install' that is part of setuptools. So, we have to install setuptools first. Download it from here. Choose the appropriate Python version with ours. Because our aim is to be able to install .egg, choose setuptools in .exe format.
  3. Run the installer. 
  4. It will install a new executable file called 'easy_install.exe' under Python's 'Scripts' folder.
  5. To install the zope.interface in .egg format, I did the following in Command Line:
c:\Python26\Scripts\easy_install.exe c:\zope.interface-3.6.1-py2.6-win32.egg
Now we can use the zope.interface for our twisted.

---
Further readings: