You are currently browsing the category archive for the ‘Programming’ category.
Working on a project to potentially building a piece of art to put up in my room next year. The idea is this one: with the help of a friend who is better at hardware than myself, some ICs, my Arduino, and lots of patience and soldering, I want to build a 30 inch by 30 inch board with 100 discrete 3 inch by 3 inch “pixels” which are lit by a single RGB LED, that would look something like this, if the LEDs were set to display red, green, blue, repeating:
Since each LED can display any mix of red, green, and blue, any color is possible within each pixel, so designs can be displayed. It will maintain a USB connection to the computer (although extra power will probably be needed as the Arduino/USB won’t supply enough for 100 bright LEDs) so the computer can run more complex algorithms than the ICs could normally handle, and maybe even be able to display simple visualizations that follow music, fades and sweeps, and any color that I desire to set a certain mood to my room.
Other ideas include Conway’s Game of Life. The board could be mounted on a piece of foam board or plywood, with the elctronics hidden beneath, and the LEDs shining through either translucent acrylic or some sort of cloth, most likely.
Anyway.. mostly I have to keep it cost effective. Ordering LEDs from eBay, I can get 100 RGB LEDs for about $35, which beats DigiKey’s $150-ish for 100, but I still have to find integrated circuits and learn how to do it. Wish me luck :)
(Any suggestions are more than welcome)
Sometimes. And telling when it’s stupid is important to being a good coder, in my opinion.
Maybe I’m wrong. I don’t have a degree yet. But I know that when I write a Python script that I want to rotate the screen on my tablet, I’m not worrying about extensibility or modularity, I just want a small procedural script that does this, this, and this, and then finishes. The faster the better, both in writing the script and in the script’s execution.
So, in beginning work on JORSnix, I decided I’d get my tablet working perfectly first, as a system to model it on. Part of this made rewriting my tablet.rb script that rotated my tablet between landscape and portrait mode in Python. I spent about 20 minutes on it, not counting the time I spent learning that the os module was deprecated and thus learning how to use the subprocess module.
Anyway, the finished product is this:
#!/usr/bin/python
from subprocess import *
import re
p1 = Popen(["xrandr"],stdout=PIPE)
p2 = Popen(["grep", "current"], stdin=p1.stdout, stdout=PIPE)
output = p2.communicate()[0]
current = output[output.find("current "):output.find(", max")]
pattern = re.compile('[0-9]+')
resolution = pattern.findall(current)
if resolution[0] > resolution[1] : #landscape
Popen("./xrotate"+" 3", shell=True)
Popen("cellwriter &",shell=True)
Popen("easystroke &",shell=True)
else : #portrait
Popen("./xrotate"+" 0", shell=True)
Popen("pkill cellwriter && pkill easystroke", shell=True)
As you can see, it's pretty simple and straightforward. It's no piece of art, but it does what it needs to do. No more, no less. And it will work on any single-monitored tablet, no matter the resolution, for swapping the screen from portrait to landscape and back.
If it needs to be turned into a couple functions so I can use it in a class, that would work. But that's not what the plan is, at least not yet. But I was told by a friend on IRC that it was unreadable, and wrong simply because my code isn't "modular and extensible" without first examining why it would need to be extended upon. He gave this as the "correct version:"
#!/usr/bin/python
from subprocess import Popen,PIPE
def bash(c):
if c.startswith('cd '):
chdir(''.join(list(c)[3:]))
else:
return Popen(c, shell=True, stdout=PIPE).stdout.read().strip()
class Display():
def getCurrentResolution(self):
res = bash("xrandr")
res = res[res.find("current ")+8:res.find(", max")].replace(' ','')
return (res[:res.find('x')],res[res.find('x')+1:])
def rotate(self):
res = getCurrentResolution()
if res[0] > res[1]: # Landscape Mode
self.xrotate(3);
bash('cellwriter &')
bash('easystroke &')
else: # Portrait Mode
self.xrotate(0)
bash('killall cellwriter')
bash('killall easystroke')
def xrotate(self, mode):
# unknownmosquito can fill it in from here
class Wacom(Display):
def getStylusMode(self):
return bash('xsetwacom get stylus Mode')
display = Wacom()
display.rotate()
Besides going into the fact that the "better version" would no longer use regular expressions (and thus would be less resilient to oddly shaped displays), it aliases Popen to bash for "readability." Overall, being accused of using procedural programming for a systems script in a language like Python (which allows you to do this for a reason), and to have this given to me as a "correction," just rubs me the wrong way.
Especially when I'm told that it needs to be done like this to make it more "readable."
Object Oriented Programming is wonderful. Unless using it is just wasting time.
Note: If it becomes necessary to integrate this script into a larger part, obviously it will get OOP'd. But for now, it'll remain a script.
Ironically I’m going to post again so soon after my “I’m not posting during the summer” post, but I got a bug and designed a single-page portfolio for my friend Luis. I thought to myself, “There should be a simple introduction to his work that he shouldn’t be afraid to put on a business card.” And he seemed to like it until it was almost done, and then started asking for things like tabs with more content.. but I feel like his blog is for that. So I finished it as I saw fit and told him he may do with it what he pleases. It is his domain, after all.
But for now, it is quite a masterpiece, if I do say so myself. I am very proud of it, and I find it very aesthetically pleasing, and straight and to the point.
Here is a permanent screen capture, in case he decides it just isn’t for him:
The thumbnails are rollovers; when you mouse over, the shading and text are removed so you can see the (still cropped) original image. As of this writing the links don’t even go anywhere, besides the Twitter, email, and blog links at the top, but I suspect if Luis decides to keep the design, he will add links for his work. It is organized the way he wanted it, and it’s his color scheme.
Please keep it, Luis! :(
I’ve been messing around with Pygame to some extent. It’s a neat little Python library, designed for the easy creation of some simple games. It’s cross platform, so it runs anywhere Python does.
I haven’t done much; the tutorials on the website provide much more instruction than I could at the moment, but I’d like to post the short program I wrote just for my own amusement. The button merely makes an image appear on-screen and work as a “button.” I wrote a short Button class as well as the main script, and am pretty impressed with the results. It’s a very basic example, but maybe it’ll help someone out there having some trouble getting started.
#!/usr/bin/python
import pygame
from pygame.locals import *
import os
import sys
from Button import *
pygame.init()
window = pygame.display.set_mode((640,480))
screen = pygame.display.get_surface()
pygame.display.set_caption("My Game")
bgcolor = 255, 255, 255
clock = pygame.time.Clock()
button = Button("play.png","play_invert.png",50,50)
while True:
for event in pygame.event.get() :
if event.type == QUIT :
sys.exit(0)
elif event.type == MOUSEBUTTONDOWN :
if button.isInside(event.pos) :
button.switchStatus()
elif event.type == MOUSEBUTTONUP and not button.getStatus() :
button.switchStatus()
else :
print event
time_passed = clock.tick(50)
window.fill(bgcolor)
button.draw(screen)
pygame.display.flip()
That was the main script. It requires four things: pygame, Button.py (coming), and two images (the button up and the button pressed).
Those are the two images I used. This is Button.py:
import pygame class Button : def __init__ (self, path, invertpath, x, y) : self.x = x self.y = y self.button = pygame.image.load(path) self.invert = pygame.image.load(invertpath) self.status = True def draw (self, screen) : screen.blit(self.button, (self.x, self.y)) def isInside (self, pos) : if (pos[0] >= self.x) and (pos[0] <= self.x+self.button.get_width()) : if (pos[1] >= self.y) and (pos[1] <= self.y+self.button.get_height()) : return True else : return False else: return False def getStatus(self) : return self.status def switchStatus(self) : self.status = not self.status temp = self.button self.button = self.invert self.invert = temp
Of course I failed to comment it… figures. Most of this should be pretty obvious though.
Also: consider this code public domain. Use it, make money with it, I don’t care. Whatever. I shouldn’t have to say that, but I will just in case.
Actually, this is about Frets on Fire X:
Frets on Fire X takes the base that Frets on Fire built as an open source clone for PC and makes it awesome. You can get the game for Windows, Mac, or Linux from http://code.google.com/p/fofix/. It’s pretty slick but the download itself doesn’t include any music. However, if you head on over to http://geetarfreaks.webs.com they can hook you up with music from the games and their original note charts. The site is also full of great stuff like themes (make FoFiX look like Guitar Hero or Rock Band) and a tech center for ripping the songs off the games if you, say, find the game for sale used and don’t have a console, and feel uncomfortable about downloading the songs off the site for whatever reason. Disclaimer: The song downloads do seem to be in a gray legal area. The site is not distributing full copies of any copyrighted material, so I think this falls under Fair Use. However, if you get in trouble for this, it is in no way my fault. OK, now that I’ve covered my own hide:
First of all you’re going to need a guitar, and toysrus has one for $20 that works in Windows and Linux. I actually got mine on sale for $10 so if you hit up slickdeals.net you might be able to get it cheaper. That one is Red Octane too so it’s not a cheap knockoff; it’s a great guitar and it’s not expensive. The only drawback is the wire, but the wireless ones just aren’t worth $60+ to me.
In Windows you need to go to Google and find the Xbox 360 Controller driver. This guitar uses the same one.
In Linux the guitar is usually plug-and-play, but I had some issues plugging it in before booting. When you plug it in, the light on the guitar should be your only indication. Start FretsOnFire and go into Options->Controls. Start changing the controls and if you can select a control and press a button on the guitar you’re golden. If this doesn’t work, make sure the “joystick” package is installed on your distribution.
Now, if you did download some music from GeetarFreaks and you’re on Mac or Linux the music isn’t going to work, and it’s due to some naming problems. I’ve written a python script (make sure you have python 2.x and not 3k when you run this) that will take their .zips, rename them properly, and organize them. Other than that, follow their how-to. Here is the code for the script:
import string
import os
import zipfile
import shutil
def lowercase() :
contents = os.listdir(".")
for x in contents :
if os.path.isdir(x) :
print "Entering " + x
os.chdir(x)
lowercase()
else :
print "Renaming "+x+" to "+x.lower()
os.rename(x,x.lower())
os.chdir("..")
def unzipall() :
zips = os.listdir("./")
for filename in zips :
if (zipfile.is_zipfile(filename)) :
print "Unzipping "+filename
short = filename[:-4]
os.mkdir(short)
shutil.move(filename, short)
os.chdir(short)
unzip(filename)
os.chdir("..")
song = open(short+"/Song.ini")
for i in song.readlines() :
if (not i.find("Name")) :
Name = i[7:-2]
song.close()
print "Renaming "+short+" to " + Name
os.rename(short,Name)
os.remove(Name+"/"+filename)
else :
print "Skipping "+filename
def unzip(filename) :
fh = open( filename , 'rb')
z = zipfile.ZipFile(fh)
for name in z.namelist():
outfile = open(name, 'wb')
outfile.write(z.read(name))
outfile.close()
fh.close()
unzipall()
lowercase()
print "Finished."
I had the wrong script up for the first day.
Apologies to anyone who tried to use it.
This is Python so make sure you keep the indentions. This is known to work in Windows (useful for the mass unzipping) and Linux, and possibly works in Mac OS X. To use:
- Place the script in the same folder as all of the .zips you downloaded from Geetar Freaks.
- In Windows, just put it in something.py and run it.
- In Linux/Mac be sure to put it in a file named something and make it executable (chmod +x something.py), then run it. (./something.py).
- Be careful with this script because it will keep renaming files to the same name but lowercase all the way up the directory tree, so if you put it in /home/ it will rename everything in /home/username/etc/etc/etc/etc but if you just put it in /home/username/etc it will only rename etc/etc/etc :P In that vain: Second Disclaimer: This script is provided as-is with no warranty or copyright (consider it public domain), and if it breaks your computer, that’s your problem, not mine.
Everything not covered here is covered in either the FoFiX howtos and/or the Geetar Freaks “Tech Centre.” This is just what I had to figure out on my own.
This is actually me tooting my own horn for a past project.. but I’ve been meaning to do it for so long I’ve lost all the good screenshots :(
I used to attend a very specific boarding school, and one of the more annoying school policies was blocking software called “Websense” which some of you may be familiar with. Websense blocked access to a lot of sites, some legit (porn), some not (Facebook, MySpace, and anything about guns or Dick Cheney). On top of this, the internet cut off at midnight every night, again thanks to Websense. Every student at the school understood that midnight was far too early to lose internet access, and while I was there we went to great odds to find proxy servers to connect to on the internet to access the internet after midnight and to get to Facebook during the day.
When I graduated I had friends still there, notably my girlfriend, and I wasn’t going to settle for letting them suffer through what I went through. I set out to design a proxy server that would be secure, easy to use, and most importantly, undetectable by the IT department. While I was there we discovered that ssh could be used to obfuscate proxy services.
I opened The Senseless Web soon after my Freshman year began. The Senseless Web offered a shell account on my desktop to any NCSSM student. The student verified his identity by providing an NCSSM email to which the site sent a verification code. He then provided an alternate email for future communication so that the domain wouldn’t attract too much attention from ITS.
The shell accounts were neutered with a nonfunctional python shell and restrictive permissions. The account’s password was changed every ten minutes by a cron job and the user would enter his email in the only box on the homepage, receive the password via email, and sign in to the single shared account. I had instructions on the site and after a one-time setup the connection was simple. Everything was encrypted and I did little logging besides a counter to see how much it was being used so that the users had assurance of privacy.
Early on, ITS caught on to SSH forwarding that was going on to other sites, and blocked all outgoing ports except HTTP, HTTPS, POP, and IMAP. Since the others were all being used, I set up SSH to serve on port 143 (IMAP). I told users to change their settings and the site continued undisturbed until the end of the year. The command to connect was ssh -D 8080 efas@trantor.boldlygoingnowhere.org -p 143 if in Linux or a similar setup using putty in Windows. Then Firefox was told to look for a SOCKS proxy on localhost at port 8080. Clever! I wrote a script (since lost) that would set up the whole thing for Linux users, and Windows users could use a modified shortcut for putty and foxyproxy to make it a very short setup for a free-internet session.
By the end, we had over 5600 individual sessions. The whole thing was a huge success. Every user was allowed unfiltered, free internet whenever he or she wanted. From what I understand, the school has since lifted the more draconian of the rules, and students do not need/want such a service any longer.
Below are the only remaining screenshots, unfortunately, I have reinstalled all of my PCs since then and managed to lose all other screenshots. However I do have the code in a tarball if anyone is interested in seeing it.

This is the homepage. Note the use (not hit) counter, bottom left, and the one-box sign-in form at the bottom right.
Long live free internet!
This made me laugh. I was stumbling and I found this site:
http://24ways.org/2005/edit-in-place-with-ajax
which might look fine in your browser but the headline didn’t in mine:
I thought that was pretty funny. A site about impressing your friends with web design with the biggest web design failure I’ve seen in awhile. I mean, I know sometimes things don’t work in Linux but it’s not like he was using Flash.
Web design fail.









