_personalPrez

Prez Jordan - Blogger, House Enthusiast, Coder, and President.

http://twitter.com/ilictronix
http://ilictronix.com
http://facebook.com/jscales
~ Saturday, February 27 ~
Permalink

Extending Fractals

So last time I posted about fractals, I gave you guys some code to render a monochrome Mandelbrot Set. Granted it’s cool, how about we throw some color into the mix?

As I explained in the last post, the mandelbrot set is colored if the iteration z(c) stays contained within z(c) < 2. So to color it, we will select appropriate hues based how quickly the complex point (x, yi) exceeds 2. Here’s the new mandel(c) method.

def mandel(c):
        z = 0
        i = 0
        for h in range(0,20):
            z = z**2 + c
            if abs(z) > 2:
                return cols[i / 4 - 1]
            i += 1
        return "black"

What’s different about it? Rather than returning True or False, this method returns a color, based on how quickly the iteration becomes chaotic. Now, we will always draw a point, it just depends what color that point is.

for x in range(0,600):
    real = x / 200.0 - 1.5
    for y in range(0,600):
        img = y / 200.0 - 1.5
        c = complex(real, img)
        col = mandel(c)
        w.create_line(x,600-y,x+1,601-y,fill=col)
        w.pack()

And here’s the beautiful result…

dayum

Pretty straightforward, huh? Yeah, I thought so too. But let’s take this one step further, how about we tweak our code to accomodate all fractals in the Julia Set? To explain with this “Julia Set” thing is, think of squares and rectangles. A square is always a rectangle, but not all rectangles are squares. The Mandelbrot Set is a Julia Set, but not all Julia Sets are Mandelbrot Sets. You know what? It’ll become clearer once you see the code.

Now to render the Julia Set, we have to pass it two methods, a complex point (x, yi) and an equation. Each julia set depends on the equation you pass it, and this requires either a great amount of tweaking, or just looking up some cool patterns.

The Julia Set is determined the same way - equate z(c) = z_n-1(c)^2 + c. Except, for Julia Sets, c remains constant throughout the test. This c is the equation you pass the method. This c determines what your fractal will look like. Let’s take a peak at some code. We’ll keep the same “colorizing” theme. t is the complex point, c is the static equation.

def julia(t, c):
    z = t
    i = 0
    for h in range(0, iter):
        z = z**2 + c
        if abs(z) > 2:
            return cols[i / 10 - 1]
        i += 1
    return "black"

Pretty straightforward. Except Julia sets produce some amazing figures. I’ll post my favorites below. But for now, here is the complete code. I’ve including some “favorite equations” so feel free to test em out.

# Julia Set generator by Jordan Scales
# 12/02/2009

from Tkinter import *

cols = ["orange", "yellow", "red", "blue", "white"]

# favorites... 
# -0.8+0.156j
# -0.70176-0.3842j
# -0.4+0.6j
# -0.835-0.2321j

eq = -0.8+0.156j
iter = 50

def julia(t, c):
    z = t
    i = 0
    for h in range(0, iter):
        z = z**2 + c
        if abs(z) > 2:
            return cols[i / 10 - 1]
        i += 1
    return "black"

root = Tk()
w = Canvas(root, width=600, height=600)
w.pack()

for hx in range(0, 600, 75):
    w.create_line(0,hx,600,hx,fill="blue")

for hy in range(0, 600, 75):
    w.create_line(hy,0,hy,600,fill="blue")

print 'Loading...'

for x in range(0, 600):
    real = x / 200.0 - 1.5
    for y in range(0, 600):
        img = y / 200.0 - 1.5
        com = complex(real, img)
        col = julia(com, eq)
        w.create_line(x, 600-y, x+1, 600-y+1, fill=col)
        w.pack()
            
print 'Done!'

root.mainloop()

Now, I bet you wanna see some pictures, huh. No problem, I should really get this tatooed on my body.

woot

Enjoy, and get experimenting! If I didn’t make anything clear, feel free to hit me up at prezjordan@ilictronix.com, or just drop me a tweet @ilictronix

/prez


38 notes
~ Sunday, December 27 ~
Permalink
13 notes
~ Thursday, December 10 ~
Permalink

Mandelbrot Set in Python

The Mandelbrot Set is sexy as hell, there’s no getting past that. Learning about it for 15 minutes in my Algebra II class years ago was more confusing than anything for my fellow classmates, thanks to an atrocious teacher, but my curiosity was sparked. I had started coding about that time, mainly in QBasic (hehe), and it was not until I picked up Python that I really thought about drawing this thing.

My lack of understanding for OOP at the tender age of 14 really set me back when working with the Tk interface library, so the first few weeks were chock full of copypasta, but I got better. In this code, however, I did not create any classes or anything, just kinda used the preset Tk() methods and whatnot. But it works :)

So let’s take a look at this beautiful code…

from Tkinter import *

def mandel(c):
        z=0
        for h in range(0,20):
            z = z**2 + c
            if abs(z) > 2:
                break
        if abs(z) >= 2:
            return False
        else:
            return True

root = Tk()
w = Canvas(root, width=600,height=600)
w.pack()

for hx in range(0,600,75):
    w.create_line(0,hx,600,hx,fill="blue")

for hy in range(0,600,75):
    w.create_line(hy,0,hy,600,fill="blue")

print "Initializing..."

for x in range(0,600):
    real = x / 200.0 - 1.5
    for y in range(0,600):
        img = y / 200.0 - 1.5
        c = complex(real, img)
        if mandel(c):
            w.create_line(x,600-y,x+1,601-y,fill="black")
            w.pack()

print "Complete!"

root.mainloop()    

My main function “mandel()” may confuse some of you. The mandlebrot set basically works like this. You have a set of numbers: z1, z2, z3, and z4. When given a complex number, c, you square the previous “z” and add c to it. z1 starts as just c, while z2 = z1^2 + c. If z4 is less than z2 and z3 is less than z1, the number c is a part of the Mandlebrot Set. To make things even more secure, I calculate up to z20, and if any z is greater than 2, said number c is NOT part of the set. Confusing, maybe.

So I have a 600 by 600 grid. To calculate the mandlebrot set, I assign the y axis to the coefficients of i, and the x axis to the coefficients of the real part. So 4+2i maps to (4,2). Using a bit of math, I scaled this system to easy-to-use integers so I could draw on a 600 x 600 grid.

I then simply check if a number is part of the set, using my method mandel(), and if it is, I map the complex number on the graph. To do this, I draw a line from x,y to x+1,y+1, because the Tkinter canvas does not support single pixels to be drawn, I think (hehe).

It’s pretty cool code, and the end result is beautiful.

Mandlebrot Set

Enjoy.

/prez


7 notes
~ Saturday, December 5 ~
Permalink

Project Euler: 17

So today I REALLY wanted to code something, but I had absolutely no idea what to code. Usually, when stricken with such problems I make some nice GUIs, but I just wasn’t feeling that today. So I went back to ol’ Project Euler and decided to solve one of those problems that I COULD do, but didn’t want to dedicate the time to.

Problem 17 deals with converting integers into speakable English. To be more specific, making the following conversions…

2 -> “two”

14 -> “fourteen”

156 -> “one hundred and fifty-six”

Easy? Eh, kinda. It’s more logic than math, especially with the use of “and.” So the problem calls for the total number of letters used to write out all the numbers from 1 to 1,000 (including 1,000). Because I was so intrigued by this math-to-english number parser, I decided to make a library for it. Here’s the source code, written in Python, including comments :)

final = ''

## just some references
prefixes = 'one','two','three','four','five','six','seven'\
           ,'eight','nine','ten','eleven','twelve','thirteen'\
           ,'fourteen','fifteen','sixteen','seventeen','eighteen','nineteen'
tens = 'twenty-','thirty-','forty-','fifty-','sixty-',\
       'seventy-','eighty-','ninety-'

def parse(num, reset = 1):
    global final            # make final global so we can keep using it
    if reset == 1:
        final = ''          # workaround for our recursion-ness
    x = num
    if x > 99:                          # for the hundreds spot
        primeint = int(str(x)[0])
        if x % 100 <> 0:                # test if a multiple of 100
                                        #    (include 'and'?)
            final += (prefixes[primeint - 1] + ' hundred and ')
            parse(x % 100,0)            # recursion  
        else:
            final += (prefixes[primeint - 1] + ' hundred')
    elif x >= 20:                       # deals with tens
        primeint = int(str(x)[0])
        final += tens[primeint - 2]
        parse(x % 10,0)                 # some more recursion
    elif x > 0:                         # finishes off with teens and digits
        final += prefixes[x - 1]
    return final                        # return result

I used a lot of recursion here. Another way to approach this would be to create individual methods for each “step,” sorting out the hundreds, tens, and ones place. Then executing these functions in an appropriate order. I’m cool, so I did recursion.

My code essentially starts by looking for the hundreds spot, adds the appropriate strings, and then parses the remaining number. I kept a global variable, final, which is what contains the entire string.

Now that you have a nifty little parsing function, let’s go back to Project Euler.

## Project Euler 17 Solution by Jordan Scales
## 12/05/09
## If all the numbers from 1 to 1000 (one thousand)
##   inclusive were written out in words, how many letters would be used?

import numparser

total = 0                              # total letters
alpha = 'abcdefghijklmnopqrstuvwxyz'   # check alphabet
count = 1                              # counter

for count in range(1,1000):
    string = numparser.parse(count)    # converts integer to 'string'
    chars = 0
    for char in string:                # checks to see if character is
        if char in alpha:              #   is in the alphabet
            chars+=1                  
    total += chars
    print '%s: %s: %s letters' % (count, string, chars) # diagnostics

total += len('onethousand')            # add 1000 (just a workaround for now)
print '1000: one thousand: %s letters' % len('onethousand')
print 'Total characters: %s' % total

The code’s fairly self explanatory. I have a for loop from 1 to 1000, NOT including. I parse each integer, count the result’s letters - not including dashes!, and add them to a nice total. The output is buggy at parts, for instance “twenty-“. I could code in some workarounds, but I’ll find another way. I printed a lot of diagnostics because of a stupid little bug in the third to last nine, where I actually added ONE MORE character, the space, then I was supposed to.

Now everything works, and I still have a nice little parser for future “projects.” Feel free to use my code and publish it elsewhere, just give yours truly some credit.

Get coding,

/prez


3 notes
~ Saturday, November 14 ~
Permalink

More Cheating

So yesterday I wrote about how python could be used to exploit this game. Alternatively, there are two more ways to exploit this game. Both in JavaScript.

If you’re no good with JS, that’s cool. But I highly recommend learning it here. JS is widely used for non-secure (if they don’t need to be) web forms and other prototyping. I used over 1400 lines of it this summer working for a local university.

First step, get rid of that damn frame. Right click anywhere in the “game” and select, This Frame -> Open Frame in a New Tab. Depending on your browser, you might just need to select Open Frame in New Tab, instead of the former two-step process.

Now let’s examine the code…

<input id=”eon” type=”button” value=”Start game!” onclick=”mclick()” style=”width:100%;height:150px;font-size:37px;”>

So we have a button (eon) that calls mclick() when pressed. Easy enough. Let’s keep going.

function mclick(){

vclick += 1;

document.getElementById(‘eclick’).innerHTML = vclick;

document.getElementById(‘eon’).value = vclick;

if(start == 1){interval = setInterval(‘sec()’,1000);start = 0;}

}

Alright so mclick() basically just adds 1 to vclick and continues counting down. So how can we hack this thing? Simple javascript injection. Enter the following into your address bar.

javascript:var i=0;for(i=0;i<1000;i++){document.getElementById(‘eon’).click();}

What does this do? Basically “clicks” the button for you. Careful of the number here, I recommend not putting anything above 100,000 - but feel free to experiment. Hm, maybe we can make this a bit more elegant.

javascript:var i=0;for(i=0;i<1000;i++){mclick();}

Now we’re not even bothering clicking, let’s just call mclick() directly. Makes sense. Maybe we can really “hack” this thing though.

javascript:vclick=1000000;end();

Now we’re just editing vclick direction, then calling the end function. This is getting fun. Maybe we can screw with our friends a little more though. If you look closely at the javascript code, you can see that end() just displays the dialog, with the variable vclick mashed somewhere in there, which basically tells the world how many times you clicked. We already editing vclick, but who says we can’t go the extra mile?

javascript:var vclick=”Hacking is great!!”;end();

We just changed the variable type of vclick, and now all of your friends are gonna flip that a number isn’t even there.

Muhahahah. Have fun, and experiment - maybe exploit some other apps.

/prez


2 notes
~ Friday, November 13 ~
Permalink

I Like To Cheat

I recently came across a game on Facebook (here) that I just had to exploit. The goal is to click the button as many times as you can in 30 seconds. This is possible with JavaScript, but I’m a Python coder so I went the extra mile. Enjoy.

## MouseClicker v1.0
## Author: Jordan Scales
## Date:   11/13/09

import ctypes
import time

i = 0
intMax = 930 ## place the amount of clicks you want here.

time.sleep(5)

for i in range(0,935):
    ctypes.windll.user32.mouse_event(2,0,0,0,0)  ## mouse down
    ctypes.windll.user32.mouse_event(4,0,0,0,0)  ## mouse up
    time.sleep(0.015)
    
print 'Done.'

/prez