Thursday, April 01, 2010

Extending Python with C or C++

I'm learning how to write C++ code that can extend python.

To help myself and possibly anyone else, I'm going to write what I've learned so far.

the first thing that's required is to include the python header. On ubuntu if you haven't installed it yet, you can with this:
sudo install python-dev


Then you can start editing a cpp file with whatever your fave editor is. I choose you, vim!

$ vi knightmodule.cpp
Apparently for historical reasons the file is called XXXmodule, though if you have a "long" module name you can just use the name, like knight.cpp.

Continuing on, the first line in your file needs to be:
#include
which contains all the useful bits you need to make a good extension.


#include

extern "C"{

static PyObject * whosayni(PyObject *self, PyObject *args){
const char * knight;

if(!PyArg_ParseTuple(args, "s", &knight))
return NULL;

printf("%s is a knight who says, \"Ni!\"", knight);

Py_RETURN_NONE;
}

static PyMethodDef MyMethods[] = {
{"whosayni", whosayni, METH_VARARGS,
"Param knight: prints knight is a knight who says, \"Ni!\""},
{NULL, NULL, 0, "Testing"}
};

PyMODINIT_FUNC

initmyknights(void){
(void) Py_InitModule("Hello", MyMethods);
}

} // end extern


Then we create a python build script. It can be named anything you want, but convention dictates setup.py

$ vi setup.py


then


from distutils.core import setup, Extension

module1 = Extension('knight', sources = ['knightmodule.cpp'])

setup (name = 'Knights',
version = '1.0',
description = 'They say ni!',
ext_modules = [module1])


And fire it off with
$ python setup.py build


it will put your file in build/lib.linux-i686-2.6/knight.so - you can copy this .so file anywhere or navigate to the directory. When you're in the same dir as your knight.so


$ python
Python 2.6.4 (r264:75706, Dec 7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import knight
>>> knight.whosayni("Lancelot")
Lancelot is a knight who says, "Ni!">>>


Notice that the >>> is on the same line? That's because we didn't add a newline at the end of our print string.

So go ahead and edit that, rebuild your knight, and import again (just make sure if you copied it that you copy it again). You should get something like this:

>>> knight.whosayni('Richard')
Richard is a knight who says, "Ni!"


Now you've written your very first C++ extension for Python.

Keep looking for updates when I come back and explain what all this stuff does.

Labels: , , , ,

Wednesday, November 12, 2008

Best. Toys. Evar!

http://www.8020.net

The Industrial Erector Set, or big toys for big boys ;)

Labels: , ,

Monday, August 11, 2008

From the Onion


Report: Many U.S. Parents Outsourcing Child Care Overseas

Am I the only one who seriously laughed at the quote from the little girl? Ah, the Onion... yay for satire

Labels: , , ,

Tuesday, July 29, 2008

Gas Sucks

So... Unless you've been living in a cave, you know that gas is expensive.

Where I currently live, gas is around $3.70-3.80USD/gal. And unless you've been living under a rock, you also know that people are trying to save money, by shopping at the cheapest gas stations. I haven't played with the figures before, so for your joy and education, I'll explain several figures and numbers.

First off, let's figure out some statistics. This fall I will be traveling at least 40 miles a day, 5 days a week. I may be doing more, so lets go with 240 miles a week. My car gets about 20 mpg.

Today, I purchased gas for $3.74, instead of $3.88 at the highest station I saw. According to my calculations, (assuming 240 gallons), I would have paid $44.99, rather than $46.67, coming to a savings of a whopping $1.68. I suppose I could have bought something at the dollar store or off a dollar menu at a fast food joint for that much.

On a yearly basis (52 weeks - though I don't drive 240 each week, so this won't even be accurate), that would mean I would save a total of $87.36. If I continually managed to save $.14/gallon. That is a fairly substantial annual savings, however usually the prices are less.

What does it look like if we average $.05 per gallon savings, for a whole year, at 240 miles? That's 60₵ per week, or $31.20 a year.

So we've been looking at a weekly average of 240 miles. What if you average less, say around 100 miles per week, with a 5₵ savings in gas. That's 25₵ per week, or $13 per year. Not as substantial, although for $13 you can almost go see a movie with two people. Once a year. With your gasoline savings.

So, in some cases it makes a lot of sense to find the cheapest gas, in others, it doesn't. If you'd like to experiment with your own data, this program allows you to change the gas prices, mpg, and miles driven. It then computes monthly and annual savings.

It's written in python, if you don't have python, you'll have to download it here.

Enjoy!

1 # Wayne Werner
2 # Copyright July, 2008
3 # This code may be distributed and modified for personal or non-commercial
4 # use only.
5 # Gas Savings Calculator
6 # Used for calculating weekly, monthly, and yearly gas savings
7
8 from decimal import Decimal
9 from os import system
10 clear = system('clear') # Change 'clear' to 'cls' on a Windows machine
11
12 # Retrieves information from user, converting it to decimal type
13 gasA = Decimal(raw_input('Lower Gas Price: $'))
14 gasB = Decimal(raw_input('Higher Gas Price: $'))
15 mpg = Decimal(raw_input('Miles per gallon: '))
16 miles = Decimal(raw_input('Miles Traveled: '))
17
18
19 clear # Clears the screen
20
21 # Creates a list of miles, by 10, up to the miles traveled, to show
22 # what the savings would be for lesser miles traveled
23 24 my_range = range(10, miles, 10)
25 if my_range[-1] != miles:
26 my_range.append(int(miles))
27
28 # Prints column headers
29 print "%6s %7s %7s %11s\n" % \
30 ('Miles', 'Price A', 'Price B', 'Difference')
31
32 # Loops over the values in my_range, computing the total price for
33 # each price of gasoline.
34 for x in my_range:
35 if x == my_range[-1]: # Linebreak before the final values
36 print "\n",
37 priceA = (x/mpg) * gasA
38 priceB = (x/mpg) * gasB
39 diff = priceB - priceA
40 print "%6i $%6.2f $%6.2f $%4.2f" % (x, priceA, priceB, diff)
41
42 # Computes yearly and monthly savings, based on the difference
43 annual_savings = 52 * diff
44 monthly_savings = 4 * diff
45 print "\nAt an average weekly savings of $%.02f, your monthly savings will b
e $%.02f.\nYour annual savings will be $%.02f." \
46 % (diff, monthly_savings, annual_savings)

Labels: , , , , ,

Saturday, June 28, 2008

Hive Mind

This article brings to light some interesting research. Basically, when you ask two people to guess about something, the average of their two guesses is closest to accurate. When you ask a group of people, the accuracy increases.

And that sort of phenomenon could be expected. However, the strange thing is that when someone guesses *twice* - differently than their first, the average is also closer. At a second guess period of about three weeks, the average of the two guesses was about 16% more accurate. Not as accurate as a group, but more accurate than an individual.

I found strange a question they asked;
But that this happens at all raises questions about “individuality” within an individual. If guesses can shift almost at random, where are they coming from?


I don't know if it really raises questions about individuality. Certainly it seems like random, by my guess is that it might have something to do more with survival of the population. If a group of people (population of species) are able to correctly determine X, and correct decisions about whether something is dangerous or harmless tend to promote the survival of the species... those individuals who tend to guess too extreme will be removed from the population, and their genetics and learned behavior both will be removed.

*shrugs* but that's just my theory.

Labels: , , , ,

Tuesday, June 03, 2008

This that and the other...

So... right now I think I'm bored out of my skull. I'm tired, and there's no one to talk to and nothing really to do. At least in 3 hours I get to go home and read or something. I suppose I'll probably draw some or something...

I suppose I can tell you how awesome last weekend was, because my geekheart came on a surprise visit! Friday afternoon I'm just sitting there, minding my own business, learning about the structure of man, and how to draw it, when I look up and there my mom has one of our geeklings in her arms, and my geekheart walks through the door.

I sat there like a deer caught in the headlights. My brain disengaged and I sat there for a moment with a bit of "Durrrrrrrrrr?" going through my head. And then I woke up and gave them all a great big hug.

We pretty much had a blast, except for the whole leaving part. That always sucks :(

But other than ending, it was a great weekend!

Labels: , , , , ,

Thursday, May 15, 2008

Quick Blog

Well, I'm just posting this quick little blog. I watched this neato cheeto thing on TV about the science of laughter. It was really neat. And funny. I just finished watching the Colbert Report, it was rather amusing... I laughed at it, too :D

I'm super excited for tomorrow, because my geekheart will be coming to visit! Freakin' Sweet!

Also NAPA auto parts has the bushing for my car... so I'll creep my way down the boulevard and back, to pick it up. I'll also swing by Fuller & Son to see if they have any T nuts and some screwy type things so I can fix my girls' table.

Maybe I'll even post some pics.

I also made an instructable. Check it out!

Labels: , , , , ,

Friday, April 18, 2008

Philosophy Outline

So in my philosophy class, we have to write a paper by next thursday, so I figured I'd start with an outline... and you (un)lucky souls get to read the questions I get to answer, plus some of my outline. Our paragraphs are supposed to be no less than 5 sentences, and 25% example, 75% explanation, so I plan on doing two sentences of example, six of explanation, which should result in 8 sentences a piece. At least that will be my attempt.

What is the distinction Hume makes between impressions and ideas

1. Impressions are current sensory input or original contents of psychological states.
2. colors, sounds, tastes, feelings are impressions, as are hate, love, desire, will, at the moment we experience those.
3. Ideas are similar to memory. They are not the actual impressions, only what we remember about them
4. Ideas can be associated with other ideas. Creativity simply takes the ideas/memories we have and links them together.
5. Ideas can be linked together in different ways, resemblance, contiguity, and cause and effect.
6. Resemblance is when one thing resembles another, i.e. "You remind me of so-and-so", or a caricature of a person reminds you of that person.
7. Contiguity is the association between ideas near each other in time and thought, i.e. my friend sally leads me to think of her mother, father, siblings, and the family as a whole. Cause and effect is similar, such as when I push keys on the keyboard, letters appear on the screen.
8. Both impressions and ideas are what Hume calls perceptions, or contents of consciousness

`
Do you agree with Hume that all of our ideas can be traced back to sensory impressions?


1. Yes. Anything I can think about is something that has entered into my senses and associated in some way.
2. If I think about happiness, I can only refer to the way I felt physically and/or psychologically at a particular moment.
3. If I think about the delicious smell of that pizza yesterday, I am simply recalling the sensation, or impression, of the scent at that particular moment.
4. The attempt to imagine a new creature, or planet, or shape, or psychological state requires me to refer to some other creature, or part of that creature, or planet, shape or psychological state.
5. An example, try to explain what salt tastes like. Without the experience, the best you might do is that it tastes like an ionic bond breaking up and attaching itself to various receptors on a certain region of the tongue.

Why does Hume think that reason alone cannot prove God's existence?


1. Reasoning from a priori suggests that there are truths that can be known before or independently of experience, but the existence of God is either a fact or it is not, and if it is a fact, then simply conceiving the idea that he exists is not enough to prove his existence, for it is equally possible to conceive of his non-existence.
2. Hume also rejects empirical arguments that every event has a cause, on his claim that causality is simply a habit of mind based on the constant conjunction of events in our own experience.
3. In one of his works, his character Philo points out that we see that the existence of houses depend on a builder, because every house had a builder.
4. This only refers to this universe, and so relying on our reason is insufficient to explain how universes come into existence.
5.Through Philo, Hume points out five problems. Infinite cause is not provable from a finite effect, there are improvements to make to this world, even if this world is the best it can be, it's not evidence for excellence, What evidence that there is only one God? And if we're anthropomorphic about this diety, why not suppose he's physical as well?

Why is Hume considered to be an agnostic rather than an atheist?


1. An atheist is one who disbelieves the existence of any god.
2. An agnostic is one who doubts the existence of God.
3. While an atheist claims that no god exists, an agnostic looks at the evidence for and against the existence of God, and cannot determine which case is valid.
4. Hume stated that we live in a world in which "all events seem entirely loose and separate," so anything is possible, including the non-existence of God, or even the existence of God.
5. Though he attacked typical arguments in favor of the existence of God, simply showing that the argument failed to support the conclusion, that was not proof that the conclusion was false, and Hume never claimed to establish the conclusion that God does not exist.

Do you agree and/or disagree with David Hume's ideas concerning the existence of God?




Well, that's all I have time for now, I should head over to my chemistry class. Adios!

Labels: , , ,

Tuesday, August 21, 2007

First day o' classes!

So... it's my second semester at UCA.

My list of things to do today include

  • Waking up - accomplished!

  • Taking a shower

  • Eating breakfast

  • Making it to my first class (WRTG 1320 - starts at 9:25AM) by 9AM. Maybe earlier

  • Meet a friend that I pretty much haven't seen since last semester, even though she lives in conway and I've been there 3x/week! Darn schedule conflicts!

  • Arrive for my (MATH 1580) class 30 mins early

  • Eat lunch somewhere in there

  • Depending on what's going on with UCA Welcome Week, possibly go have some fun doing something or another

  • Get home safely

  • Get ready for classes tomorrow.



That schedule neither constitutes the entirety of what's goin on for me today, nor what I'll probably end out doing, such as - getting there *ing early to go see financial aid and see about more money... le sigh sigh sigh!

With a 4.0 last semester, you'd think they'd be throwing money at me, eh? I guess I have to wait till after next semester for that!

How's YOUR school coming?

Labels: , , , , , , ,

Wednesday, August 15, 2007

Friends and fun

So I got to see two of my friends yesterday. It was good, I had fun :)

Tomorrow I get to see at least one of my friends, so that's also swell.

And now I have to get moving to work... so I shall.

Labels: ,

Wednesday, August 08, 2007

Boys vs. Girls

So, I'm planning on writing a two part piece on Boys vs. Girls.

It's gonna be about the dumb things, relationship-wise, that boys and girls do.

If you have any comments or ideas, feel free to leave a comment for my consideration!

Should be fun, mainly because I'm going to thrash us both. wzerozerot.

Labels: , , ,