mapleman's restroom graffiti
Wed, 02 Jul 2008
Embedding Python in C++

Adding python scripting capabilities to your code is an interesting thing to do, it can help you enhance an application without as much hard work. This is just an example on how to use code from memory as part of your program.

 1 // Embedded Py.cpp
 2 //
 3 
 4 #include "stdafx.h"
 5 #include <iostream>
 6 #undef _DEBUG /* Link with python24.lib and not python24_d.lib */
 7 #include <Python.h>
 8 
 9 
10 using namespace std;
11 
12 /* Python function code */
13 char script[] = 
14 "def doSomeStuff():\n"
15 "	import sys\n"
16 "	print sys\n"
17 "	return 3+2+2";
18 	
19 					
20 int _tmain(int argc, _TCHAR* argv[])
21 {
22 	PyObject *pName = NULL, *pModule = NULL, *pDict = NULL, *pFunc = NULL, *pCode = NULL, *pReturn = NULL;
23 	Py_Initialize();	
24 
25 	/* Compile the script defined in the array script */
26 	pCode = Py_CompileString(script, "mini-script", Py_file_input);
27 
28 	if (!pCode || PyErr_Occurred())
29 	{		
30 		PyErr_Print(); 
31 		return 0;
32 	}
33 
34 	/* Import the code compiled */
35 	pModule = PyImport_ExecCodeModule("mini-script", pCode);
36 
37 	if (!pModule || PyErr_Occurred())
38 	{
39 		PyErr_Print(); 
40 		return 0;
41 	}
42 
43 	/* Get the Dictionary of the module */
44 	pDict = PyModule_GetDict(pModule);
45 
46 	if (!pDict || PyErr_Occurred())
47 	{
48 		PyErr_Print();
49 		return 0;
50 	}
51 
52 	/* Grab the function with the name doSomeStuff() */
53 	pFunc = PyDict_GetItemString(pDict, "doSomeStuff");
54 
55 	if (!pFunc || PyErr_Occurred())
56 	{
57 		PyErr_Print();
58 		return 0;
59 	}
60     
61 	/* Call the function */
62 	pReturn = PyObject_CallObject(pFunc, NULL);
63 
64 	if (!pReturn || PyErr_Occurred())
65 	{
66 		PyErr_Print();
67 		return 0;
68 	}
69 
70 	/* Make sure return value is of int type */
71 	if (PyInt_Check(pReturn))
72 	{
73 			long returnOfFunc = PyInt_AsLong(pReturn);
74 			cout << "The return of doSomeStuff() function is: " << returnOfFunc << endl;
75 	}	
76 
77 	/* Cleanup */
78 	Py_XDECREF(pReturn);
79 	Py_XDECREF(pCode);
80 	Py_XDECREF(pFunc);
81 	Py_XDECREF(pDict);
82 	Py_XDECREF(pModule);	
83 	Py_Finalize();
84 
85 	return 0;
86 }

posted at: 17:50 | path: /python

Thu, 19 Jun 2008
Playing with templates

Dumb strokes of C++ templates while bored.

 1 #define QueueSize 5
 2 
 3 template <typename T>
 4 class Queue
 5 {
 6 
 7 public:
 8 	Queue() : head(NULL), tail(-1) { for (int i=0; i < QueueSize; queue[i++]=NULL); }
 9 	void insert(T in);
10 	bool isEmpty() { return ( queue[head] == NULL ) ? true : false; }
11 	bool isFull() { return (head == tail && queue[head] != NULL) ? true : false; }	
12 	T remove();
13 	void showContents();
14 
15 private:
16 	T queue[QueueSize];
17 	int head, tail;
18 	
19 };
20 
21 template <typename T> 
22 void Queue<T>::showContents()
23 {
24 
25 	int loc=0, i=0;
26 
27 	if(isEmpty())
28 	{
29 		cout << "Empty" << endl;
30 		return;
31 	}
32 		
33 
34 	for (i=head; i < tail || i < QueueSize;  i++)
35 		cout << queue[i] << " ";	
36 
37 	if(head > loc)
38 		while(loc < tail && loc < head && queue[loc] != NULL)
39 			cout << queue[loc++] << " ";
40 		
41 	cout << endl;
42 
43 
44 }
45 
46 
47 template <typename T> 
48 T Queue<T>::remove() 
49 {  
50 	int retVal = 0;	
51 
52 	if (!isEmpty())
53 	{
54 	
55 		retVal = queue[head];			
56 		queue[head] = NULL;
57 
58 		if (head == QueueSize - 1)
59 			head = 0;
60 		else
61 			head++;			
62 
63 	}
64 	else
65 		cout << "Stack Underflow" << endl;
66 
67 	return retVal;
68 
69 }
70 
71 template <typename T>
72 void Queue<T>::insert(T in)
73 {	
74 	int prevTail = tail;
75 
76 	if (tail == QueueSize - 1)
77 		tail = 0;
78 	else
79 		tail++;
80 
81 
82 	if (isFull())
83 	{
84 		cout << "Stack Overflow" << endl;	
85 		tail = prevTail;
86 	}
87 	else
88 		queue[tail] = in;
89 	
90 
91 	return;
92 }

posted at: 22:13 | path: /

Mon, 07 Apr 2008
Updates

Did a minor update on the book code since Amazon moved their webservices from ECS 3.0 to 4.0 and it broke all my code, now it is fixed.

posted at: 19:33 | path: /

Fri, 10 Nov 2006
Amazon Web Services

Been very busy lately, going back to school to finally get my bachelors. Lately I have been playing with Amazon Web Services so I decided to add a list of my programming and personal books to the personal menu using the awesome AWS platform. I am only touching the tip of it obviously. Too much Web 2.0 hype lately, bring back the telnet days please =P

posted at: 23:17 | path: /

Tue, 18 Apr 2006
Just another day.

Working on RaidAlert which is a project that was customly ordered designed for my former boss. It is a systray Win32 application that connects to a web page using XML-RPC and checks for events issued by the web page administrator. And allows you to register or not to those events. Ironically this project is designed for a World of Warcraft clan. To the client what he wants right?

Been playing EVE Online a little bit. It is a great MMO that doesn't require as much attention as any other I have played and still allows you to advance. I use it as my Solitaire, just to relax between coding thoughts.

Following the elections in my country. I hope we beat Mr. Hugo Chavez's clone on the polls next July. Great blog about the current political situation in my country México en Peligro

I hope he gets squashed baaad in the polls otherwise I will have to run around like chicken little looking for an H1-B or an L1 *shivers*

Oh I finally updated the links on the projects in the page except mapleBlog which I can't find the original WAR file since the old site that hosted it shut down. *sobs*

posted at: 04:57 | path: /

Some code dare I just found. Simple matching algorithms. I love going nuts with pointers in C :^)

uncommon.c

#include <stdio.h>


int main( int argc , char ** argv , char ** env ) 
{
	if (argc != 3)
        {		
		fprintf(stdout, "Usage: %s <palabraX> <palabraY>\n\r", argv[0]);
		return -1;
	}

        /* find out the size for the registry */
	char * registry = NULL;
	registry = (char*)malloc( strlen(argv[1]) * sizeof(char) + 1);	
	memset(registry, 0, sizeof(registry) + 1);
	     
	char * wordX = argv[1], *wordY = argv[2], *startY = wordY; 

	while ( *wordX ) 
	{
		while( *wordY )
		{
			if (*wordX == *wordY)
			   break;	

			wordY++;
		}

		if (!*wordY)
		{
			char *rr = registry;
			while(*rr) rr++; 
			*rr = *wordX;	
		}

		wordY = startY;	
		wordX++;	
	}        	 

	fprintf(stdout, "output: %s\n\r", registry); 
	
	free(registry);
	return 0;
}

common.c

#include <stdio.h>


int main( int argc , char ** argv , char ** env ) 
{
	if (argc != 3)
        {		
		fprintf(stdout, "Usage: %s <palabraX> <palabraY>\n\r", argv[0]);
		return -1;
	}

        /* find out the size for the registry */
	char * registry = NULL;

	registry = (char*)malloc( strlen(argv[1]) * sizeof(char) + 1);	
	memset(registry, 0, sizeof(registry) + 1);
	     
	char * wordX = argv[1], *wordY = argv[2], *startY = wordY;

	while ( *wordX ) 
	{
	
		while (*wordY)
		{	
			if (*wordX == *wordY)
			{
				char * rr = registry; 
				
				while( *rr )
				{
					if (*rr == *wordY)
						break;
					++rr;
				}

			
				if (!*rr)
				{
				    *rr = *wordY; 
				    break;
				}
				wordY++;	
			} 
		        else		
			     wordY++; 
		}	 

		wordX++; 
		wordY = startY; 
	}        	 


	fprintf(stdout, "registry: %s\n\r", registry); 
	free(registry);

	return 0;
}

posted at: 04:57 | path: /

Thu, 18 Aug 2005
mapleman's Java Proxy

Lately I been messing with Medved QuoteTracker's API. It is an XML through TCP protocol. Medved only allows you to interact with its API from localhost. Unfortunately the PC that hosts the executable is not, well, mine. So I decided to rewrite my Java Proxy and make it extremely easy for anyone (the ones that use that particular PC) to run it without a hitch.

So obviously I had to write it with GUI. And well, it all went well, I think, and now its ready to battle the streaming protocols and beyond :)

mapleJProxy in action

Naturally the console based one is still included.

Ant Buildable source: mapleJProxy.jar

posted at: 09:42 | path: /java

Tue, 16 Aug 2005
Free Microsoft SQL Server 2005 Express Edition

Get your free Microsoft SQL Server while its hot!. Another alternative for small websites.

SQL Server Express is an ideal choice for independent software vendors (ISVs), server users, non-professional developers, Web application developers, Web site hosters, and hobbyists building client applications."

URL: Microsoft SQL Server Express 2005

posted at: 00:38 | path: /windows

Mon, 15 Aug 2005
Asynchronous Javascript and XML (AJAX)

The Buzzword of the year. It seems to be on everyone's mouth. Specially since GMail and other Google services started using it. So I jumped on the bandwagon, and wrote my menus using this technique. Totally unnecesary? Definitely. Entertaining? You bet. It turns the dullness of writing webpages into something interesting.

So how does it work? As you connect to the website, an XML Http Request is sent from your browser into a Python cgi. That Python CGI reads the variables and pulls the database table that match the parameters. It then proceeds to generate an XML that ultimately your browser (and the Javascript) parses and feeds to the DOM.

Source: toilet.js

posted at: 20:23 | path: /web

Sat, 13 Aug 2005
Javascript Closures

Closures are one of the most fascinating constructs ever IMHO. Not many people know about their existence, let alone in Javascript. However the knowledge of them can seriously leverage your designs.

So what is a closure? A function that keeps an environment. The best way to explain a closure is with an example, so thats what I will show you.

var globalVariable = 20;

function createClosure(arg)
{
   var env = 10;
   return function(x) { alert ( arg + env + x ); }
}

// main body
ourClosure = createClosure(globalVariable);
globalVariable = 0;
ourClosure(30);          // prints 60
alert(globalVariable); // prints 0 

ourClosure() will return 60 even though we have just set the value of the globalVariable to 0. That is, it keeps the values defined when the closure was created.

alert(globalVariable) will output 0, the current value of globalVariable.

IUnknown

posted at: 03:21 | path: /web