hondros 25 Junior Poster

Well, since there was no option for "tutorial" in the type of post, it has been created as a simple thread...
Obfuscation - confusion resulting from failure to understand
obfuscated code - Code that is hard to read
In this tutorial, I will show you how to convert something readable, to something completely unreadable, but it still works, exactly the same. There are multiple thing you can do in Python to achieve obfuscation, one of the main ones being one-liners and exec(). I have not understood the lambda function yet, but you can still pull off loops and if statements that have one statement, by putting them on the same line; I.e.:

x = 1
# This:
if x == 1:
    print("x is equal to 1")
# Becomes this:
if x == 1: print("x is equal to 1")

Both work exactly the same.
Next, we shall take a look at a string:

toexec = '''x = 0
if x == 0:
    print("Hello world")
'''

You might be asking, well, what does this have to do with anything? Here's the answer, the exec() can execute this string as actual code. If you type in toexec in the interpreter, you're shown this: 'x = 0\nif x == 0:\n print("Hello world")\n' Now, if you type this: exec(toexec) You are now presented with this: 'Hello world' Nifty, eh? Another way of obfuscating your code is through use of ord() and chr(). That toexec code can also be represented …

hondros 25 Junior Poster

Ah, you misunderstand the code. You call the function, and it will return a string object that you can write. Thus, you can do this:

e = tohex('Hello world')
'''e = '48656c6c6f20776f726c64''''

And then whatever you need to do, in order to display a text string in your GUI (Tkinter, I presume? I have no experience with Tkinter, so I cannot help with that). Ah, and perhaps something to speed up your read times?
Perhaps you can read in only 5~10 lines at a time, and hex that, then do that for the whole file. That should help it out. That's what I usually do

hondros 25 Junior Poster

Ah buddy... Okay, let me show you some hints on hex values. Your code has confused me beyond belief xDDD
Okay, here are some basic functions you're going to have to get comfortable using:

int(x [, base])
hex(x)
ord(c)
chr(i)
str.replace(old, new)

Okay, here's how we can use this information. Say we have this string here: 'Hello world' Now, we want to convert this to a hex value, correct? Also, we don't want a nasty string like this: '0x480x650x6c0x6c0x6f0x200x770x6f0x720x6c0x64' Kinda hard to read, right?
Okay, here's how we convert that string into a readable 2 digit hex code

# First off, some background:
# ord(c) will return the ascii value of a character
# That should help in understanding this
# Get rid of the print statements if you want

def tohex(s):
    hexed = ''
    for x in s:
        a = ord(x)
        print(a)
        a = hex(a)
        print(a)
        a = a.replace('0x', '') # Get rid of that ugly '0x'
        print(a)
        hexed += a
    return hexed

tohex('Hello world')

Okay, so now we have a hex representation of that string, right? Well, now you can do your hex editing if needed be. But, we want to go ahead and reconvert that back into a string, right?

# More background:
# chr(i) returns a character based on the number you type
# int(x [, base]) can take two arguements
# Normally, you just want something like int('9') to return an int 9
# However, we are working with a …
hondros 25 Junior Poster

Er, what have you managed to do so far? Can you convert strings into hex strings? Such as a hex view of 'Hello world!!!'? Here is the hex values for it if you don't know: '48656c6c6f20776f726c64212121'
Good luck :D
Post if you need help
Also, do a google seach for Tkinter python manual. That'll help

hondros 25 Junior Poster

Okay, not sure if this is the right spot, but here's my issue. So, my mom is taking a php programming class, and she's learning how to use MySQL and the phpMyAdmin. She wanted to activate the passwords for the root and admin users, and instead of asking me for help like usual, she followed this tutorial:
http://guides.jlbn.net/setpw/setpw1.html
Now, she can log in from the command prompt, but phpMyAdmin won't log in. Any help?

hondros 25 Junior Poster

Um, the best tutorial that I know of is the one that is included with Python itself, also available at their website. Other than that, just look up the manual for any module you use.

GUI-wise, I'd have to go with wxPython, it's very simple and easy to use. I have been using it for about 2 weeks now, no problems with it. I've attemped Tkinter, PyGt, and a few others, but I find wxPython to be the best.

Good luck with your project my friend :D

hondros 25 Junior Poster

I bet he's making a game which takes place on a different planet :D

hondros 25 Junior Poster

Alright, got it figured out. You'll have to excuse my extra variables. It's going to be a password prompt thing. here it is:

// Make the program take user input
// Replace the password with '*'
#include <iostream>
#include <conio.h>

// Initialize all variables
int current; // Buffer for getch()
char buffer[3];
char pass [100]; // Actual password text to be stored
char passnum [300]; // Password ASCII code to be stored
int passcount; // Counter for array
int passnumcount; // Counter for array
int finalvalue;

int main()
{
  std::cout << "Please enter a password: \n";
  while ((current!= 13) and (passcount <= 99)) {
    current = getch(); // Capture user input
    pass[passcount] = char(current); // Add the letter to the array of password
    passcount++; // Add the current pointer
    // Now convert the int to a string
    itoa(current, buffer, 10);
    if (!buffer[2]) {
      buffer[2] = buffer[1];
      buffer[1] = buffer[0];
      buffer[0] = '0';
    }
    passnum[passnumcount] = buffer[0];
    passnum[passnumcount+1] = buffer[1];
    passnum[passnumcount+2] = buffer[2];
    passnumcount = passnumcount + 3;
    char buffer[3];
    //std::cout << buffer[0] << " " << buffer[1] << " " << buffer[2] << "\n";
  }
  std::cout << passnum << "\n";
  finalvalue = atoi(passnum);
  std::cout << passnum << "\n";
}
hondros 25 Junior Poster

Okay, as the name implies, I would like to change an integer (ascii code number), such as 65, to a string, '65', then back to integer, 65. Now, the reason for doing so, is because I'm working with ascii code, and want to return a string of a fixed length. As known, ascii ranges from 1 - 256. I only want to capture the values from 32 and up. Here are my issues:
1) Check the length of the integer; ( such as the python expression len(str(65)) == 2 )
2) If the length is 2, then make the string be '0' + number;
3) Combine all the strings into one;
4) Convert that back into a number
I have only recently begun c++ programming, after 3~4 months of python programming (Gotten really good at it), and c++ is really confusing.
In a more technical version of what I want to do, assume that my input is 65, 87, 121, 54
Then it'll return:
65087121054
Any help would be greatly appreciated. All I know to do is this:

#include <iostream>
#include <conio.h>

char current;
char pass[100];
int passcount(0);

/* For converting the getch() to ascii code and append to the char array:
pass[passcount] = char(current);
*/
hondros 25 Junior Poster

Stuff I want to work on:
1) Fix the (functions not valid) problem;
2) Change this whole thing into a class (simple enough);
3) Create a log of functions you make;
4) Show where the error was in your program

hondros 25 Junior Poster

This is a nice command prompt I wrote up a month ago. It's still in the Beta stages however. Anyways, here's a brief overlay of what it does:
1) Takes user input of a function, creates an x/y table and plots it
2) Change the x-range
3) Graph waves (Main thing I wanted to do)

Okay, here's how you use the program:
When ran, you'll enter a prompt:
y = ...
You can type the following commands it knows:
1) help():
- Prints out to the terminal what functions it knows
2) frange(start, end, step):
- Defines the x range. Step can be a float number ie (0.5); useful for the waves because you don't want to see a huge graph of waves; default x range is -100 - 100
3) set(radian):
- Just converts the x-range into a radian range. Takes no arguments
4) polar():
- Change the graph to a polar graph
5) line():
- Change the graph to a line graph (default)
6) show():
- Show the graph

It is beneficial to follow these steps to get it to show correctly:
optional(1) y = frange(0, 10, 0.01))
optional(2) y = line()) or (2) y = polar())
3) show()
4) any functions

All functions have to be completely typed out
Such as the y = 2*(x**2)
Nothing is implied as of …

hondros 25 Junior Poster

Umm... Details please? I have no idea what the problem appears to be.

hondros 25 Junior Poster

No no. That's the code I showed her earlier. I guess now she's wanting to have it without commas :/ I don't know

hondros 25 Junior Poster

You're still using .split(',') for commas. Therefore, anything you type without commas won't work. If you want it without commas, try doing this:

date = '20100315'
year = date[0:4]
month = date[4:6]
day = date[6:8]

Perhaps try to implement this into your code.

hondros 25 Junior Poster
# Hashes/Arrays are known as Libraries in Python:
a = {}
a['b'] = 0
print(a)
print(a['b'])
hondros 25 Junior Poster

You're welcome, and it's quite all right. Just a lot of code writing xP. Sorry if it seems like I came off as a butthead, didn't mean to

hondros 25 Junior Poster

Change events = list(events[0] to events = list(events).split('\n'). Then make a loop to iterate through each events listing, then put the original loop inside of that. Please try and figure this one out before asking for help. You will have to show me all the tries you have done before expecting me to help with your homework anymore. No offense, but you should be trying to figure it out on your own. That should be a requirement of being a programmer: able to figure out why something works on your own by modifying what you are working on

hondros 25 Junior Poster
elif menu_choice == 3:
        filename = raw_input("Filename to load: ")
        pickle_file = open(filename, "r")
        events = cPickle.load(pickle_file)
        pickle_file.close()
        events = list(events[0])
        tabs = ""
        for x in events[:-1]:
            tabs += x + "\t"
        tabs += events[-1]
        print "Events:" + tabs
hondros 25 Junior Poster
import cPickle

def print_menu():
    print '1. Add an Event'
    print '2. Save Events to File'
    print '3. Load Events from File'
    print '4. Quit'
    print()

event_list = []
menu_choice = 0
print_menu()
while True:
    menu_choice = input("Select Menu Item (1-4): ")
    if menu_choice == 1:
        print "Add Event"
        date = raw_input("Date: ")
        # yyyy/mm/dd
        # Assuming that the user inputs this: 2010, 3, 13
        date = date.split(', ')
        if len(date[0]) == 2:
            date[0] = '20'+date[0]
        if len(date[1]) == 1:
            date[1] = '0'+date[1]
        if len(date[2]) == 1:
            date[2] = '0'+date[2]
        date = '/'.join(date)
        #
        time = raw_input("Time: ")
        title = raw_input("Title: ")
        desc = raw_input("Description: ")
        loc = raw_input("Location: ")
        attend = raw_input("Attendee(s): ")
        #ui = "Date: " + date, "Time: " + time, "Title: " + title, "Description: " + desc, "Location: " + loc, "Attendee(s): " + attend
        # Add a newline to seperate each entry
        ui = "Date: " + date, "Time: " + time, "Title: " + title, "Description: " + desc, "Location: " + loc, "Attendee(s): " + attend + '\n'
        event_list.append(ui)
    elif menu_choice == 2:
        filename = raw_input("Filename to save: ")
        pickle_file = open(filename, "w")
        cPickle.dump(event_list, pickle_file)
        pickle_file.close()
    elif menu_choice == 3:
        filename = raw_input("Filename to load: ")
        pickle_file = open(filename, "r")
        events = cPickle.load(pickle_file)
        pickle_file.close()
        events = list(events[0])
        print "Events:"
        for x in events:
            print "       "+x
    elif menu_choice == 4:
        break
    else:
        print_menu()

print "Goodbye"

My Output:

1. Add an Event
2. Save Events to File
3. Load Events from File …
hondros 25 Junior Poster

Okay, sorry. The tuple appears to not have a .split() function, only a list does. So, we shall go ahead and convert the tuple to a list, then iterate through the split:

n = []
for x in events:
    n.append(x)
# Make the tuple to a list
events = n[:]
# NOTE:
# You could just do a conversion using the list() function;
# IE. events = list(events)
# Less typing, but the other way you'll understand how the tuple and list works
# Separate the events at the '\n' marker
for x in events[0].split('\n'):
    # Iterate through the list of each entry
    for y in x:
        # print the result
        print y
hondros 25 Junior Poster
# Separate the events at the '\n' marker
for x in events[0].split('\n'):
    # Iterate through the list of each entry
    for y in x:
        # print the result
        print y
hondros 25 Junior Poster

Had to get rid of the commented part of code (First block), then change date = input() to date = raw_input(). You still have to change the way the event load presents itself. But I fixed the major part for you:

import cPickle

def print_menu():
    print '1. Add an Event'
    print '2. Save Events to File'
    print '3. Load Events from File'
    print '4. Quit'
    print()

event_list = []
menu_choice = 0
print_menu()
while True:
    menu_choice = input("Select Menu Item (1-4): ")
    if menu_choice == 1:
        print "Add Event"
        date = raw_input("Date: ")
        # yyyy/mm/dd
        # Assuming that the user inputs this: 2010, 3, 13
        date = date.split(', ')
        if len(date[0]) == 2:
            date[0] = '20'+date[0]
        if len(date[1]) == 1:
            date[1] = '0'+date[1]
        if len(date[2]) == 1:
            date[2] = '0'+date[2]
        date = '/'.join(date)
        #
        time = raw_input("Time: ")
        title = raw_input("Title: ")
        desc = raw_input("Description: ")
        loc = raw_input("Location: ")
        attend = raw_input("Attendee(s): ")
        #ui = "Date: " + date, "Time: " + time, "Title: " + title, "Description: " + desc, "Location: " + loc, "Attendee(s): " + attend
        # Add a newline to seperate each entry
        ui = "Date: " + date, "Time: " + time, "Title: " + title, "Description: " + desc, "Location: " + loc, "Attendee(s): " + attend + '\n'
        event_list.append(ui)
    elif menu_choice == 2:
        filename = raw_input("Filename to save: ")
        pickle_file = open(filename, "w")
        cPickle.dump(event_list, pickle_file)
        pickle_file.close()
    elif menu_choice == 3:
        filename = raw_input("Filename to load: ")
        pickle_file = open(filename, "r")
        events …
hondros 25 Junior Poster

Here you go. I still don't know how the user will be inputting data, so I included two choices for you. Just get rid of the one you don't want. I was half contemplating on getting rid of whitespace to make you tab each one like you did, but I left it in to be nice =]

import cPickle

def print_menu():
    print '1. Add an Event'
    print '2. Save Events to File'
    print '3. Load Events from File'
    print '4. Quit'
    print()

event_list = []
menu_choice = 0
print_menu()
while True:
    menu_choice = input("Select Menu Item (1-4): ")
    if menu_choice == 1:
        print "Add Event"
        date = input("Date: ")
        # yyyy/mm/dd
        # Assuming that the user inputs this: 20100313
        date = date[0:4]+"/"+date[4:6]+"/"+date[6:8]
        # Assuming that the user inputs this: 2010, 3, 13
        date = date.split(', ')
        if len(date[0]) == 2:
            date[0] = '20'+date[0]
        if len(date[1]) == 1:
            date[1] = '0'+date[1]
        if len(date[2]) == 1:
            date[2] = '0'+date[2]
        date = '/'.join(date)
        #
        time = raw_input("Time: ")
        title = raw_input("Title: ")
        desc = raw_input("Description: ")
        loc = raw_input("Location: ")
        attend = raw_input("Attendee(s): ")
        #ui = "Date: " + date, "Time: " + time, "Title: " + title, "Description: " + desc, "Location: " + loc, "Attendee(s): " + attend
        # Add a newline to seperate each entry
        ui = "Date: " + date, "Time: " + time, "Title: " + title, "Description: " + desc, "Location: " + loc, "Attendee(s): " + attend + '\n'
        event_list.append(ui)
    elif menu_choice == 2:
        filename …
hondros 25 Junior Poster

Your code looks like it's running fine to me. Would you be able to edit your post and put

tags around the code? It's hard to read. I also don't know what exactly you want. It's definitely taking the input how you want it. Perhaps just ask the user to put it in the format dd/mm/yy?

hondros 25 Junior Poster

1) Convert the .py or .pyw files to a .pyc (python compiled file)
This is accomplished by importing the file; distribute the .pyc (Note that there are .pyc decompilers if they are wanting to know your code _that_ badly)
2) Obfuscate your code
This is accomplished by taking your code and making it as unreadable as possible. Take for example, the following code:

# For logging in to the system
class Secure():

    logbase = {'admin':'123456'}
    logged = False
    invalid = False

    def login(self, user, passw):
        self.logged = False
        self.invalid = False
        try:
            if self.logbase[user] == passw:
                self.logged = True
            else:
                self.logged = False
        except:
            self.logged = False
            self.invalid = True

    def __init__(self):
        while self.logged == False:
            user = raw_input('Username: ')
            passw = raw_input('Password: ')
            self.login(user, passw)
            if self.invalid == True:
                print "Invalid username"
            elif self.logged == False:
                print "Username and Password do not match"
            elif self.logged == True:
                print "Welcome to the system %s" %(user)

S = Secure()

Readable, right? Well, go through and rename every single variable to something else (_, __, ___, ____, etc.), and use import * as _. Also, try and fit as much as you can on one code; if possible, use the lambda function (I don't even know how to use it, sorry). So, our code now looks like this:

class _():
    _, __, ___ = {'admin':'123456'}, False, False
    def ____(_, __, ___):
        _.__ = False
        _.___ = False
        try:
            if _._[__] == ___: _.__ = True
            else: _.__ …
hondros 25 Junior Poster

I'm sorry, but doesn't Bash already support remote ssh log-in? And that's not remote desktop, but rather remote log-in. Two different things. Can you give a better explanation of what you want?

hondros 25 Junior Poster

Well, even though I'm in a bad mood, I'm not going to just give you a link to the file module. Here's how you open, and create an xml file:

xml = """
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
"""
filename = 'file.xml'
f = open(filename, 'w')
f.write(xml)
f.close()

I suggest that you read up on file formats and the python language for simple things like this.

hondros 25 Junior Poster
num = int(raw_input("Enter a Number: "))
for x in range(0, num):
    raw_input()

That should provide a basis for your loop

Also, do not assign variables to built-in functions, such as 'list'. It's a bad idea to do

hondros 25 Junior Poster

Double click it :/
Or copy the file to your python directory, and import your script
Or if on windows: python C:\pathtoscriptnamehere.py in a command prompt
Or a number of other ways
Also:
R.T.F.M.

hondros 25 Junior Poster

Alright, I went through and did a test myself. The code had a lot of bugs, but I worked it out. Here's the code snippet, it has an option to take you through the steps:
http://www.daniweb.com/code/snippet265043.html

hondros 25 Junior Poster

This simple script will copy all music files that were not purchased from the iTunes store to a directory of your choosing. It requires the ID3 module (Created by some person, from somewhere, I forget where, but I DID NOT make this module). The syntax is as follows:

ipoddir = 'E:'
newdir = 'C:\\Documents and Settings\\#\\My Documents\\ipodtest'
a = iPod(ipoddir, newdir debug='on')

That's it, it'll run just like that, and show you which file it's working on, and where it's putting it. It'll organize it by Artist, then Album. As of now, I have not included options for organizing, or for going through steps yet. But it will copy the files, so long as the iPod is not a iPod touch or iPhone
ID3 Module: http://id3-py.sourceforge.net/

hondros 25 Junior Poster

Okay, so I have about 6 GB of music on my iPod. I don't want to go through and copy everysingle file and rename it manually, so I am making a python script to do it for me. I would just like to have some feedback on my code, make sure that it will work before I run it. I really don't want it getting halfway through copying and freeze or something. Anyways, here's my code (note that ID3 module is required for it to work. I did not create it, but it is attached):

'''
iPod Music Copy Module
Copies the music from your iPod to a folder on your computer
'''

from os import rename,  \
               chdir,   \
               getcwd,  \
               listdir, \
               mkdir
from shutil import copy2
from ID3 import ID3

class iPod():

    def __init__(self, iPod, direct, new?='no', organize='yes', debug='off'):
        '''
        iPod is the root directory of the iPod
        direct is the directory to copy to
        define new? to 'yes' to take you through steps
        '''
        if new? != 'yes':
            self.iPoddir = iPod+"\\iPod_Control\\Music"
            self.newdirect = direct
            self.organize = organize
            self.debug = 'on'
            runipodchange()

    def runipodchange(self):
        chdir(self.iPoddir)
        self.folders = listdir()
        songtoappend = []
        songnum = 0
        for x in self.folders:
            for y in x:
                songtoappend.append(y)
        for x in self.folders:
            if self.debug == 'on': print("Working on folder: %s" %(x))
            for y in tocopy:
                songnum += 1
                if self.debug == 'on': print("Copying file: %s, %d of %d" %(y, songnum, len(songtoappend)))
                if self.organize == 'yes':
                    song = ID3(y)
                    try:
                        mkdir(self.newdirect+"\\"+ID3['ARTIST']+"\\"+ID3['ALBUM'])
                    except …
hondros 25 Junior Poster

I believe that whole module was deprecated as of version 2 or so. I think anyways.

hondros 25 Junior Poster

Thank you very much vegaseat. You have helped me greatly. I am going to be making a module for music, with a scale, interval, and chord finder, along with the ability to write what you type in. I am hoping to make it into a nice synthesizer on the computer. I'm not sure though. Anyways, without further ado, here is the semi-finished code for writing a chord to a .wav file:

# .wav file chord writer
# ~ Hondros
# Much thanks to vegaseat
try:
    from numpy import *
except:
    try:
        from math import *
    except:
        print("No module numpy or math found;\nThese are vital for the performance of this program")
import struct
import wave

class SoundFile():

    def __init__(self,
                 freq=[440],
                 data_size=10000,
                 fname="test.wav",
                 frate=11025.0,
                 amp=8000.0,
                 functions = None):
        """Create a synthetic wave file,
           with combined frequencies freq,
           file fname has a length of about data_size*2
           Note if you want a certain wav other than sin,
           type function as a string, replacing frequenice as: 'freq'"""

        if functions == None:
            def func(number, x, frate, function):
                function = ''
                for frequencie in number:
                    a = 'sin(2*pi*'+str(frequencie)+'*(x/frate))+'
                    function += a
                function = function[:-1]
                return eval(function)

        if type(functions) == type(""):
            def func(number, x, frate, function):
                numfunction = ''
                for frequencie in number:
                    for splits in function.split('freq'):
                        numfunction += splits +\
                                       str(frequencie)
                        numfunction = numfunction[:-len(str(frequencie))]
                    numfunction += 'x'
                numfunction = numfunction[:-1]
                return eval(numfunction)

        sine_list = []
        for x in range(data_size):
            sine_list.append(func(freq, x, frate, functions))
        wavfile = wave.open(fname, "w")
        nchannels = 1
        sampwidth = 2
        framerate = int(frate) …
hondros 25 Junior Poster

Okay, here's what I am up to now. I am trying to figure out how to write sin waves to a .wav file, for playback. Here's the issue: I have no idea what I'm doing. I looked up the documentation for the wave module, and have been able to open a wav file and write to it. It'll save a .wav file for a number of seconds, playing a frequency. Here's the code for that:

import numpy as N
import wave

# Here, create all files to playback
class SoundFile:

    def __init__(self, duration=5, frequency=400, samplerate=44100):
        sr = samplerate
        samples = duration*samplerate
        period = samplerate / float(frequency)
        omega = N.pi * 2 / period
        xaxis = N.arange(int(period),dtype = N.float) * omega
        ydata = 16384 * N.sin(xaxis)
        signal = N.resize(ydata, (samples,))
        ssignal = ''
        for i in range(len(signal)):
           ssignal += wave.struct.pack('h',signal[i])
        filewriteto = frequency
        self.file = wave.open(str(filewriteto)+'.wav', 'wb')
        self.file.setparams((1, 2, sr, 44100*4, 'NONE', 'noncompressed'))
        self.file.writeframes(ssignal)
        self.file.close()

# Test that the soundfile class works
S = SoundFile(5, 220)

I have a small gist of what's going on here. Now, I know how sine wavs work, and can add/subtract them. The only issue I have is writing them. No, I don't want a premade module for it. I don't even know if there's anything that exists for it. I've googled multiple times for information, but none have been found by me.
So, I guess what I need help with is just writing sine waves to a .wav file.
Any help would …

hondros 25 Junior Poster

Okay, fixed it. Again, don't know what the issue is. Anyways, if anyone wants the finished code, here it is:
(note that numpy and pylab are required)

from numpy import *
from pylab import *

def frange(start, end=None, inc=None):
    "A range function, that does accept float increments..."

    if end == None:
        end = start + 0.0
        start = 0.0

    if inc == None:
        inc = 1.0

    L = []
    while 1:
        next = start + len(L) * inc
        if inc > 0 and next >= end:
            break
        elif inc < 0 and next <= end:
            break
        L.append(next)
        
    return L

def funceval(function, numlist=frange(-100, 100, 0.01), splitat='x'):
    y = []
    for x in numlist:
        try:
            numfunction = ''
            for c in function.split(splitat)[:-1]:
                numfunction += c
                numfunction += '(%f)' %(x)
            numfunction += function.split(splitat)[-1]
            y.append(eval(numfunction))
        except:
            numlist.pop(numlist.index(x))
    return y

def ranradians(ran):
    a = []
    for x in ran:
        a.append(radians(x))
    return a

def menuhelp():
    print("Function Plotter v2.0")
    print("Help")
    print("")
    print("Functions can be in any form, so long as there is an 'x'")
    print("Standard form for parabola's typing in the function is:")
    print("A*(x**2)+B*x+C")
    print("Carry this form to any function")
    print("Make sure to type in every symbol, none are implied")
    print("Pi is: pi")
    print("Using sine or similar functions: sin(x)")
    print("""Functions usable are:
'abs'
'absolute'
'angle'
'sqrt'
'log'
'sin'
'sinh'
'cos'
'cosh'
'tan'
'tanh'
""")
    print("For further help, please look at the source code to figure it out,")
    print("Or, e-mail me at: alexpolosky@gmail.com")

def menu(ran=frange(-100, 100, 0.01), once=False):
    if once != True:
        print("Function Plotter v2.0")
        print("~Hondros") …
hondros 25 Junior Poster

Okay, I redid the code, and it's all working now. Don't know what the issue was, but this version works a LOT better. However, I have a new issue. This time, it won't do anything except the "else" clause. Any ideas?

from numpy import *
from pylab import *

def frange(start, end=None, inc=None):
    "A range function, that does accept float increments..."

    if end == None:
        end = start + 0.0
        start = 0.0

    if inc == None:
        inc = 1.0

    L = []
    while 1:
        next = start + len(L) * inc
        if inc > 0 and next >= end:
            break
        elif inc < 0 and next <= end:
            break
        L.append(next)
        
    return L

def funceval(function, numlist=frange(-100, 100, 0.01), splitat='x'):
    y = []
    for x in numlist:
        try:
            c = '%s%s%s'%(function.split(splitat)[0], str(x), function.split(splitat)[1])
            y.append(eval(c))
        except:
            numlist.pop(numlist.index(x))
    return y

def ranradians(ran):
    a = []
    for x in ran:
        a.append(radians(x))
    return a

def menu():
    print("Function Plotter v2.0")
    print("~Hondros")
    print("Type in a function, or type 'help' for function commands")
    print("Type frange(x, y) for a specific x range)")
    print("Type set(radian) to convert list of numbers to radians (for sin)")
    print("Type show to show the plot window")
    print("example: 2*sin(x)")
    print("")
    while True:
        try:
            ran = frange(-100, 100, 0.01)
            f = raw_input("y = ")
            if f == 'help':
                menuhelp()
            if f[0:6] == 'frange':
                ran = eval(f)
            if f == 'set(radian)':
                ran = ranradians(ran)
            if f == 'show':
                show()
            else:
                y = funceval(f, ran)
                plot(ran, y)
        except:
            print("The function %s is invalid" %(f))

#menu()
hondros 25 Junior Poster

Hello everyone, my latest project is this:
1) Ask user to input a function
2) Plot said function
Well, I figured out how to strip the function into two parts, input a number, and evaluate the function. That all works fine outside of a defined function I created. The trouble I have, is now when asking for user input, it screws it up. I can't really explain it, but it looks like the results are just repeats of a few numbers. Here's my code:

from numpy import *
from pylab import *

numpyfunctions = [
    'abs',
    'absolute',
    'angle',
    'sqrt',
    'log',
    'sin',
    'sinh',
    'cos',
    'cosh',
    'tan',
    'tanh']

def frange(start, end=None, inc=None):
    "A range function, that does accept float increments..."

    if end == None:
        end = start + 0.0
        start = 0.0

    if inc == None:
        inc = 1.0

    L = []
    while 1:
        next = start + len(L) * inc
        if inc > 0 and next >= end:
            break
        elif inc < 0 and next <= end:
            break
        L.append(next)
        
    return L

def funeval(function, numbers=range(-5, 5), splitat='x'):
    '''Takes the function (string) and runs through a list of numbers,
       then return a list of numbers that equals the function'''
    # List of the function's results
    result = []
    for number in numbers:
        # Usually not a good idea to divide anything by zero :D
        if number != 0:
            # Split the function input
    	    # Usually at 'x'
            # Then, we put together the number
            # inside the function in …
hondros 25 Junior Poster

Have you tried using the telnet client for windows or whatever it is for linux? I suggest you try using that before you start that with python, it'll help you immensely.

hondros 25 Junior Poster

@ Sahiti:
Please learn netiquette and some english, not "eubonics", or "txtspeak" on online forums. While we will help you, we would like if you spoke as you would in a normal conversation. Also, if you need help with the 'C' syntax/language, please ask in the appropriate forum.
Thank you :D

vegaseat commented: nice way to handle this +10
hondros 25 Junior Poster

What have you tried so far?

hondros 25 Junior Poster

Okay, Im using Python 2.6, and the latest version of pygame. In my game, I have circles moving away from you, you have to catch them, and if you catch them, they disappear. The amount of circles can vary, and that is the issue I am having. As of now, I have the program create a bunch of circles in EasyAI().active, then in the loop, check if your circle is close to the AI circle, if so, then pop it from the EasyAI().active, then move the AI. Here's an excerpt of my code:

class EasyAI():

    active = []

    def _create(self, xpos, ypos, color, dif):
        self.active.append([xpos, ypos, color, dif])

    def _check(self, player, ai):
        for x in range(-8, 9):
            for y in range(-8, 9):
                if (player[0] == (ai[0] - x)):
                    if (player[1] == (ai[1] - y)):
                        self.active.remove(ai)

    def _run(self, xpos, ypos, color, dif, playerx, playery):
        self.circle = circle = pygame.draw.circle(window, color, (xpos, ypos), ray_circle)
        self.active.remove([xpos, ypos, color, dif])
        # If the circle is in the same position as the player:
        if (xpos != playerx) or (ypos != playery):
            # Sometimes, we don't want it just going in a straight line. It has a 2/3 chance of going straight, 1/3 random, 1/100 nowhere
            #### REALLY GOOD MEDIUM SETTING:
            # 0, 60; 60, 99
            a = random.randint(0, 100)
            # Straight
            if a in range(0, 60):
                nopx = (xpos - playerx)
                nopy = (ypos - playery)
                if nopx > 0:
                    xpos += random.choice(dif)
                if nopx <= 0:
                    xpos -= random.choice(dif)
                if nopy > 0: …
hondros 25 Junior Poster

Um, I realize that I'm not that great with web programming, but don't you first need to know what the variables of the site are for username and password? Then, you just set those variables in python, and pass those to the site's script that logs you in, such as: urllib.urlopen("http://sitehere.com/login.js", params)

hondros 25 Junior Poster

This code should be able to get you started to design 2-D scrolling games, like Mario. I spent a few hours trying to figure this out, and firgured I'd put up my efforts. I think there might be a better way to do it, but this should help you get started.

hondros 25 Junior Poster

Okay, I'm creating a game where you are a red circle on a black background, and you can move it around the screen, and you have to pick up the other dots. It's more complex than that, but I seem to be having an issue. Some dots will go away when you're over them, which is what I want. However, sometimes they'll randomly disappear, and they won't disappear if you go over them. Also, none of the dots appear to be moving. I made a similar program that has the dots chase you, and I made this current game off that one. Anyways, here's the code I have, if you need it explained, I will. Can anyone help me debug it?

import pygame
from pygame.locals import *
import random

if not pygame.font:
    print 'Atention, there are no fonts.'

if not pygame.mixer:
    print 'Atention, there is no sound.'

pygame.init()

# The colors used here
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
orange = (255, 100, 0)
purple = (255, 0, 255)
black = (0, 0, 0)
white = (255, 255, 255)
colors = [green, blue, orange, purple, white]

# Window code
window_width = 800
window_height = 640
window = pygame.display.set_mode((window_width, window_height))

# How big the circles are
ray_circle = 10

# The player's code
# The list format: [xpos, ypos, color, (movementx, movementy)]
player = [(window_width/2),(window_height/2), red, [3, 3]]
pcircle = pygame.draw.circle(window, player[2], (player[0], player[1]), ray_circle)

# Setup the AI code
# …
hondros 25 Junior Poster

Thank you for giving me that info. I'll try to look into that. It's not that I want to create my own language, just an application that will do whatever you type. I don't like the setup of the current python interpreter, so I want to create my own, the way I did with Windows' Command Prompt.

hondros 25 Junior Poster

Okay, all I want to do for now, is create a rather simple python interpreter. I have already created a simple command prompt for windows, utilizing the os module, the script's code is here:

import os
os.system("title Command Prompt")
while True:
    osc = raw_input(os.getcwd()+">> ")
    if osc == "exit" or osc == "quit" or osc == "exit()" or osc == "quit()":
        quit()
    try:
        os.system(osc)
    except:
        print "Not a valid shell command"
    print ""

I want to do the same, but have it evaluate python commands instead. Any help would be appreciated! :D
Also, I've already tried setting a variable to raw_input, then doing eval(variable). That doesn't work.

hondros 25 Junior Poster

Yeah sure, here's what you do:
1) Learn propper grammar;
2) Understand that getting into game design is a risky business;
3) Ask specific questions e_e

hondros 25 Junior Poster

Okay, I have installed Damn Small Linux (I believe v4.something), with syslinux. I am trying to boot it on a Dell Mini laptop. I'm not sure if it runs on any other computer. This is the issue I am having. It always boots to the DSL screen, and waits for me to input the boot parameters. If I just type dsl , it comes up withe the "Welcome to DSL" screen, and shows Scanning for for USB devices... It freezes there. Now, here's where I'm at. If I don't get that message, but what I should get, which is Scanning for USB devices... Done. , it comes up with this message:

Can't find KNOPPIX filesystem, sorry.
Dropping you to a (very limited) shell
Press reset button to quit

This is what I am using so far: dsl waitusb root=sdax I have tried 0-9 for the sda, and just the plain sda.
Any ideas? I keep searching google, I get links, but they're not very informative. I really need to boot into linux to copy over my files.

hondros 25 Junior Poster

Okay, I am running Windows XP, on a Dell Mini Laptop. Thing sucks for hardware, but that's beside the point. Okay, for the past week, I've been having issues with the laptop's memory. If I have a few windows open of any program, then close out, it seems to not close the memory the program was using, because after a few programs are running, such as Python, Firefox, and iTunes (pretty much all I use), it starts telling me that I'm out of memory. So last night, I was using the laptop, and it had been on practically all day, and I had been opening and closing several applications, so the memory was being used up a lot. At the end of the night, all I had remaining was Internet Explorer. I was on GMail, and it decided to close itself. >.< I tried opening it back up, it kept saying it was out of memory. I gave up, turned it off, and put it away for the night. This morning, I tried booting it, and it froze at the BIOS screen, about 2/3's of the way through loading. So I rebooted, and it went through the BIOS, but it was stuck at a black screen, with a flashing underscore. It stayed there until I ctrl-alt-del. It rebooted, and did the same. I have DSL on a flash drive, but I can't seem to get it to boot from it. Anyways, does anyone have any idea what I can do …