Archive for the ‘Software’ Category

Random Snippets.

May 1st, 2010

Here are some random snippets of f# code I had lying around. mostly simple stuff for basic stats calculations. Not the most complex stuff but maybe its useful to somebody trying to learn f#.

// Learn more about F# at http://fsharp.net
open System
open System.Net

//basic arithmetic mean
let Mean (x:List<float>) =
    let sum = x |> Seq.sum
    let items = x |>Seq.length
    sum / (float items)

//basic variance method
let Variance x =
    let m = Mean x
    let deviation =
        x
        |> Seq.map (fun x -> Math.Pow((x-m), 2.))
        |> Seq.toList
    Mean deviation

//Calculates standard deviation using above variance method
let StandardDeviation x =
    Math.Sqrt(Variance x)

//recursively calculates the factorial of x
//will overflow long before running into recursion limits
//at larger values it will wrap back around to 0
let rec Factorial x =
    if x = 0I then
        1I
    else
        x * Factorial(x-1I)

//calculates combinations
let Combinations n r =
    (Factorial n)/ ((Factorial r)*(Factorial (n-r)))

//calculates permutations
let Permutations n r =
    (Factorial n)/ (Factorial (n-r))

//uses Euclids formula for the greatest common divisor
let rec GCD a b =
    if b = 0UL then
        a
    else
        GCD b (a%b)

//returns an array representing the binary version of x
let toBinary (x:uint64) =
    let rec con (x:uint64) r =
        if x = 0UL then
            r
        else
            con (x/2UL) ([x%2UL] @ r)
    con x []

// gets ticker price using yahoo
let GetTickerPrice (ticker:string) =
    let url =
        "http://download.finance.yahoo.com/d/quotes.csv?s="+
        ticker+
        "&f=sl1d1t1c1ohgv&e=.csv"
    let wc = new WebClient()
    let info = wc.DownloadString(url).Split([|','|])
    float info.[1] // info.[1] is the current price will return 0.0 on invalid ticker

Tags: ,
Posted in Software | Comments (0)

Amazing stress relief program. (Red Faction Guerrilla)

October 6th, 2009

Because there’s nothing like running through a town with a sledgehammer destroying anything that moves…

Definitely one of the most entertaining games, the vehicles handle well, and there is a lot of weapons to choose from when planning how your going to attack the EDF. Plus you get a rifle that eats people alive!

Posted in General, Software | Comments (0)

Get a path from a node.

August 30th, 2009

This snippet of code lets you get a TreePath from a nodeview when you only know the ending node. This seems to be a problem I run into rather often where I want to manipulate the tree by expanding a path but I only have the node I want to expand to. The is a GetPath function in the NodeStore class however it is marked as internal with no easy access, so this provides a work around for that.

In order to use this you will need to change out the Node class used here with whatever TreeNode based class your using in your NodeView.

So nifty code in mono/c#:

public Gtk.TreePath GetPath (Node target)
{
	int Count = 0;
	foreach(Node n in view.NodeStore)
	{

		ArrayList path = RecursiveIndexSearch(target,n);

		if (path != null)
		{
			path.Insert(0,Count);
			if(path.Count == 1 && target != n)
			{
				return null;
			}
			else
			{
				return new Gtk.TreePath((int[])path.ToArray(typeof(int)));
			}
		}
		Count++;
	}
	return null;
}
public ArrayList RecursiveIndexSearch(Node target, Node Start)
{
	if(Start.ChildCount > 0)
	{
		for (int i = 0; i < Start.ChildCount; i++)
		{
			ArrayList Path = RecursiveIndexSearch(target,Start[i] as Node);
			if (Path != null)
			{
				Path.Insert(0,i);
				return Path;
			}
		}
	}
	if(Start.ChildCount == 0)
	{
		if (Start == target)
		{
			return new ArrayList();
		}
	}
	return null;
}

Tags: , , ,
Posted in Software | Comments (0)

Nifty Gtk Snippets.

August 20th, 2009

So in my recent works with Gtk I’ve come across (and written) some useful snippets so I thought I’d post a few of them.

The first comes from this site (its in Spanish), this snippet allows you to take a System.Drawing.Image to a Gdk.Pixbuf and it looks like this (slightly modified to fix an ambiguous reference in my project).

static Gdk.Pixbuf ImageToPixbuf( System.Drawing.Image image )
{
  using ( MemoryStream stream = new MemoryStream() )
  {
    image.Save( stream, System.Drawing.Imaging.ImageFormat.Png );
    stream.Position = 0;
    return new Gdk.Pixbuf( stream );
  }
}

So, we can take this first function and we can use it in this second snippet which takes an list of images and makes a single pixbuf that contains all of the images. This allows us to take a group of icon files and string them into a single image to be used in a gtk nodeview so that it only requires one column to show a variety of status icons, which is what I’m using it for maybe you can find something more interesting for it to do. Any ways the second snippet I share with you today looks like this.

public Gdk.Pixbuf GenerateIconImage(List<System.Drawing.Image> images)
{

	if(images != null && images.Count> 0)
	{
		Gdk.Pixbuf Composite = ImageToPixbuf(images[0]).Clone() as Gdk.Pixbuf;
		images.RemoveAt(0);

		foreach (System.Drawing.Image i in images)
		{
			Composite = CreateComposite(Composite,ImageToPixbuf(i).Clone() as Gdk.Pixbuf);
		}
		return Composite;
	}
	else
	{
		Gdk.Pixbuf Composite = new Gdk.Pixbuf(Gdk.Colorspace.Rgb,true,8,16,16);
		Composite.Fill(0);
		return Composite;
	}

}

public Gdk.Pixbuf CreateComposite(Gdk.Pixbuf p1, Gdk.Pixbuf p2)
{
	Gdk.Pixbuf composite = new Gdk.Pixbuf(Gdk.Colorspace.Rgb,true,8,p1.Width+ p2.Width,p1.Height);
	p1.Composite(composite,0,0,p1.Width,p1.Height,0,0,1,1,Gdk.InterpType.Hyper,255);
	p2.Composite(composite,p1.Width,0,p2.Width,p2.Height,p1.Width,0,1,1,Gdk.InterpType.Hyper,255);
	return composite;
}

Tags: , , , ,
Posted in Software | Comments (0)

Python URL grabber!

April 27th, 2009

I’m experimenting with building a web crawler in python (maybe even a small search engine bot) and I thought I would post what I have so far. Basically you give it a starting url (in the PendingURL array) and it goes to that site, uses regular expressions (some of the expressions might not be the best ones to use but they work for now) to find html links then extracts the url and adds them to the PendingURL array. The provided sample stops when its checked 10 urls but its very easy to change.

Currently If there is a issue with a link (e.g. cannot connect, cant find server) it just ignores it and moves on. I’ll probably change that later on. But for right now it’s a nifty tool can grab quite a few urls off of just a few pages. When its done running it outputs all of the links to a text file.

This code requires httplib2 and the regular expression modules.

import httplib2
import re

URLList = []
PendingURL = ["STARTING URL"]

RegLinks = "((<a).*?(href).*?(>).*?())"
RegURL = '.*?((?:http|https)(?::\\/{2}[\\w]+)(?:[\\/|\\.]?)(?:[^\\s"]*))'
RegLinks = re.compile(RegLinks, re.IGNORECASE|re.DOTALL|re.MULTILINE)
RegURL = re.compile(RegURL, re.IGNORECASE|re.DOTALL|re.MULTILINE)

def LoadHttp (url):
    global URLList
    global PendingURL
    PendingURL.remove(url)
    H = httplib2.Http(".cache")
    resp,  content  = H.request(url, "GET")
    URLList.append(url)
    return RegLinks.findall(content)

def GetUrls (Result):
    global PendingURL
    for R in range(len(Result)):
        URL = RegURL.findall(Result[R][0])
        if URL <> []:
            if URL not in PendingURL:
                PendingURL.append( URL[0])

while (len(URLList) < 10):
    try:
        GetUrls(LoadHttp(PendingURL[0]))
    except:
        print "Something broken, Ignoring it cuse I'm lazy"

for A in PendingURL:
    if A not in PendingURL:
        URLList.append(A)

file = open("urls.txt", "w")
for U in URLList:
    file.write(U+"\r\n")
file.close()

Posted in Software | Comments (0)