Showing posts with label Coding. Show all posts
Showing posts with label Coding. Show all posts

Saturday, June 20, 2009

Setting up a mySQL DataBase on uBuntu

http://www.debuntu.org/how-to-create-a-mysql-database-and-set-privileges-to-a-user

'import MySQLdb' failed

http://davidmichaelthompson.com/?p=12

duh, need to install package 'python-mysqldb', 'A Python interface to mySQL'.

Monday, June 15, 2009

Import & Display CSV Scatter with Python & MatPlotLib

  

class dataObject:

pointCount = 0

colCount = 0
columns = []
colLabels = []

# ===========================================

import re

def loadDataObjectFromFile():

filePath = "/home/david/Desktop/"
fileName = "ptpdrh.csv"
filePathAndName = filePath + fileName

firstLineIsLabels = True

try:
f = open(filePathAndName, 'r')

one = []
two = []

eof = False

retDataObj = dataObject()

isFirstLine = True

while (eof == False):

line = f.readline()
eof = (line == "")

if (line != ""):

elements = re.split(',', line)

elements[len(elements) - 1] = elements[len(elements) - 1].rstrip("\n")

if (isFirstLine == False):
if (len(elements) != retDataObj.colCount):
raise inconsistentColumnCountError, ('column count inconsistent at data line ' + (retDataOb.pointCount + 1))

if (isFirstLine == True):

isFirstLine = False

retDataObj.colCount = len(elements)

for num in range(retDataObj.colCount):
retDataObj.columns.append([])

if (firstLineIsLabels == True):

for label in elements:
retDataObj.colLabels.append(label)

else:

string = ""

for zidx in range(retDataObj.colCount):

string = elements[zidx]

if (len(string) == 0):
retDataObj.columns[zidx].append(None)
else:
retDataObj.columns[zidx].append(float(string))

retDataObj.pointCount = retDataObj.pointCount + 1

f.close()

except IOError:
print "io exception while attempting to load raw data"
print "from file:"
print filePathAndName


return retDataObj

# ===========================================

from pylab import *

dataObj = loadDataObjectFromFile()

titleText = "title"

for y in range(dataObj.colCount - 1):
plot(dataObj.columns[0], dataObj.columns[y + 1], label=str(dataObj.colLabels[y + 1]))

legend(numpoints=1)
xlabel(dataObj.colLabels[0])
ylabel("")
title(titleText)
show()

Wednesday, June 10, 2009

Member Field Serialisation for Config Storage

using System;

using System.Reflection;
using System.IO;
using System.Collections;

namespace ConfigTester
{


public class CFG
{
public int pi = 3;
public string word = "tetragrammatron";
public TimeSpan time = new TimeSpan(1,6,6,6);

public string homeDir = @"/home/david/Desktop/";
public string configFName = "config.cfg";

public CFG()
{
}

// ===== ----- ===== ----- =====

public string FieldToSerial(string fieldName, int fieldValue)
{
return string.Format("{0},{1}", fieldName, fieldValue.ToString());
}

public string FieldToSerial(string fieldName, string fieldValue)
{
return string.Format("{0},{1}", fieldName, fieldValue);
}

public string FieldToSerial(string fieldName, TimeSpan fieldValue)
{
return string.Format("{0},{1},{2},{3},{4}", fieldName, fieldValue.Days, fieldValue.Hours, fieldValue.Minutes, fieldValue.Seconds);
}

// ===== ----- ===== ----- =====

public string[] FieldsToSerial()
{
ArrayList lines = new ArrayList();

Type cfgType = typeof(CFG);
FieldInfo[] fieldInfos = cfgType.GetFields();

foreach (FieldInfo fieldInfo in fieldInfos)
{
string name = fieldInfo.Name;
Type fieldType = fieldInfo.FieldType;

if (fieldInfo.FieldType == typeof(string))
{
string val = (string)(fieldInfo.GetValue(this));
lines.Add(this.FieldToSerial(name, val));
}

if (fieldInfo.FieldType == typeof(int))
{
int val = (int)(fieldInfo.GetValue(this));
lines.Add(this.FieldToSerial(name, val));
}

if (fieldInfo.FieldType == typeof(TimeSpan))
{
TimeSpan val = (TimeSpan)(fieldInfo.GetValue(this));
lines.Add(this.FieldToSerial(name, val));
}
}

int fieldCount = lines.Count;

string[] fields = new string[fieldCount];

for (int fieldNum = 1; fieldNum <= fieldCount; fieldNum++)
fields[fieldNum - 1] = (string)(lines[fieldNum - 1]);

return fields;
}

// ===== ----- ===== ----- =====

public void ListFieldInfo()
{

Console.WriteLine();
Console.WriteLine("FIELD INFO");
Console.WriteLine();

Type cfgType = typeof(CFG);
FieldInfo[] fieldInfos = cfgType.GetFields();

foreach (FieldInfo fieldInfo in fieldInfos)
{
string name = fieldInfo.Name;
Console.WriteLine("name: {0}", name);

Type fieldType = fieldInfo.FieldType;
Console.WriteLine("type: {0}", fieldType);

object obj = fieldInfo.GetValue(this);
Console.WriteLine("value: {0}", obj.ToString());

Console.WriteLine();
}

Console.WriteLine("{0} fields", fieldInfos.Length);
}

// ===== ----- ===== ----- =====

public void SerializeFields()
{
string fullFName = this.homeDir + this.configFName;

try
{
FileStream fileStream = new FileStream(fullFName, FileMode.Create);
StreamWriter streamWriter = new StreamWriter(fileStream);

this.SerializeFields(streamWriter);

streamWriter.Close();
}
catch (Exception exc)
{
throw new Exception("ConfigSaveException");
}
}

// ===== ----- ===== ----- =====

public void SerializeFields(TextWriter tw)
{
string[] lines = this.FieldsToSerial();

foreach (string line in lines)
tw.WriteLine(line);
}

// ===== ----- ===== ----- =====
// ===== ----- ===== ----- =====
// ===== ----- ===== ----- =====

// ===== ----- ===== ----- =====

public void LoadSerialised()
{
string fullFName = this.homeDir + this.configFName;

ArrayList lines = new ArrayList();

try
{
FileStream fileStream = new FileStream(fullFName, FileMode.Open);
StreamReader streamReader = new StreamReader(fileStream);

string line;
while ((line = streamReader.ReadLine()) != null)
lines.Add(line);

streamReader.Close();

int fieldCount = lines.Count;

string[] serials = new string[fieldCount];
for (int fieldNum = 1; fieldNum <= fieldCount; fieldNum++)
serials[fieldNum - 1] = (string)(lines[fieldNum - 1]);

this.FieldsFromSerials(serials);
}
catch (Exception exc)
{
throw new Exception("ConfigLoadException");
}
}

// ===== ----- ===== ----- =====

public string StringFromSerial(string serial)
{
return serial;
}

// ===== ----- ===== ----- =====

public int IntFromSerial(string serial)
{
return Convert.ToInt32(serial);
}

// ===== ----- ===== ----- =====

public TimeSpan TimeSpanFromSerial(string serial)
{
string[] vals = serial.Split(',');

if (vals.Length != 4)
throw new Exception("timespan serial has incorrect number of variables");

int days = Convert.ToInt32(vals[0]);
int hrs = Convert.ToInt32(vals[1]);
int mins = Convert.ToInt32(vals[2]);
int secs = Convert.ToInt32(vals[3]);

return new TimeSpan(days, hrs, mins, secs);
}

// ===== ----- ===== ----- =====

public string MatchKey(string key, string[] keys, string[] values)
{
if (keys.Length != values.Length)
throw new Exception("key count must match value count, but does not");

for (int num = 1; num <= keys.Length; num++)
if (key == keys[num - 1])
return values[num - 1];

return null;
}

// ===== ----- ===== ----- =====

public void FieldsFromSerials(string[] serials)
{
// separate names & serialised form of fields retrieved from storage

int fieldCount = serials.Length;

string[] names = new string[fieldCount];
string[] forms = new string[fieldCount];

for (int fieldNum = 1; fieldNum <= fieldCount; fieldNum++)
{
int splitMarker = serials[fieldNum - 1].IndexOf(',');

string name = serials[fieldNum - 1].Substring(0, splitMarker);
string form = serials[fieldNum - 1].Substring(splitMarker + 1);

names[fieldNum - 1] = name;
forms[fieldNum - 1] = form;
}

// scan through this instantiated object

Type cfgType = typeof(CFG);
FieldInfo[] fieldInfos = cfgType.GetFields();

foreach (FieldInfo fieldInfo in fieldInfos)
{
string name = fieldInfo.Name;
Type fieldType = fieldInfo.FieldType;

string serialString = this.MatchKey(name, names, forms);

if (fieldInfo.FieldType == typeof(string))
{
string val = this.StringFromSerial(serialString);
fieldInfo.SetValue(this, val);
}

if (fieldInfo.FieldType == typeof(int))
{
int val = this.IntFromSerial(serialString);
fieldInfo.SetValue(this, val);
}

if (fieldInfo.FieldType == typeof(TimeSpan))
{
TimeSpan val = this.TimeSpanFromSerial(serialString);
fieldInfo.SetValue(this, val);
}
}

}

// ===== ----- ===== ----- =====

} // class
} // namespace

Monday, May 25, 2009

GTK-Sharp: Scrollable (Window) Table Example



using System;
using Gtk;

namespace gtkTest
{

public class WinTable
{

private Gtk.ScrolledWindow sWinRef;
private Table table;

private uint rowCount, colCount, rowSpacing, colSpacing;

// ==========================================================

public WinTable(uint pRowCount, uint pColCount, uint pRowSpacing, uint pColSpacing, Gtk.ScrolledWindow pSWinRef)
{
sWinRef = pSWinRef;

rowCount = pRowCount;
colCount = pColCount;

rowSpacing = pRowSpacing;
colSpacing = pColSpacing;

bool homogeneous = true;
table = new Table (rowCount, colCount, homogeneous);

for (uint rowNum = 1; rowNum <= rowCount; rowNum++)
table.SetRowSpacing(rowNum - 1, rowSpacing);

for (uint colNum = 1; colNum <= colCount; colNum++)
table.SetColSpacing(colNum - 1, colSpacing);

sWinRef.AddWithViewport(table);
}

// ==========================================================

/* for e.g. = 2 x 2 table, say (horiz,vert), then

(0,0) (1,0) (2,0)

(0,1) (1,1) (2,1)

(0,2) (1,2) (2,2)

*/

public void PackWidgetAtXY(Widget widget, uint x, uint y)
{
uint leftAttach = x - 1;
uint rightAttach = x;
uint topAttach = y - 1;
uint bottomAttach = y;

//Gtk.AttachOptions xOptions = new Gtk.AttachOptions(); // fill, shrink, expand

table.Attach(widget, leftAttach, rightAttach, topAttach, bottomAttach);
widget.Show();
}

// ==========================================================

public void Demo()
{

for (uint rowNum = 1; rowNum <= rowCount; rowNum++)
for (uint colNum = 1; colNum <= colCount; colNum++)
{
string text = "one\ntwo\nthree\nfour";
Label label = new Label(text);
this.PackWidgetAtXY(label, rowNum, colNum);
}

this.table.Show();
}


// ==========================================================
}


//####################################################

public partial class MainWindow: Gtk.Window
{
public MainWindow (): base (Gtk.WindowType.Toplevel)
{
Build ();
}

protected void OnDeleteEvent (object sender, DeleteEventArgs a)
{
Application.Quit ();
a.RetVal = true;
}
}

//####################################################

class MainClass
{
public static void Main (string[] args)
{
Application.Init ();
MainWindow mainWin = new MainWindow ();

uint rowCount = 8, colCount = 7;
uint rowSpacing = 80, colSpacing = 200;

mainWin.ShowAll();

Window priWin = new Window("Primary Window");
priWin.SetDefaultSize(250, 200);
priWin.SetPosition(WindowPosition.Center);

Gtk.ScrolledWindow sWin = new Gtk.ScrolledWindow();
sWin.SetPolicy(Gtk.PolicyType.Always, Gtk.PolicyType.Always);

priWin.Add(sWin);
sWin.Show();

WinTable winTable = new WinTable(rowCount, colCount, rowSpacing, colSpacing, sWin);
winTable.Demo();

priWin.Show();

Application.Run ();
}
}

}