hondros 25 Junior Poster

I'm using C++.
I'm planning on expanding to throwing this into classes, kinda like (psuedocode):

class BaseDevice {
    int isinitialized();
    int id(); // Get ID of device
    void update(); // update device if initialized
}
BaseDevice[0xFFFF];

Then I can just add multiple devices and interface with them. I'm actually trying to learn how computers work, and build my own CPU/computer from scratch. albeit, not too complex, of course!

Macros were used in this little section because it allowed easy access to change them. I was focused primarily on if the actual logic could use any changes.

hondros 25 Junior Poster

Essentially, I'm learning how emulators work. I've got the core down, but I wanted to know if I'm actually doing this the right way, or if I should be doing it differently.

#include <stdio.h>

// Opcode + Argument Retriever
#define GetOpCodeControl1(x) (x>>14)
#define GetOpCodeControl2(x) ((x>>12)&0x3)
#define GetOpCode0Arg(x) (x&0x0FFF)
#define GetOpCode1Arg(x) ((x&0x0FF0)>>4)
#define GetOpCode2Arg(x) ((x&0x0F00)>>8)
#define GetArg1A(x) (x&0x000F)
#define GetArg2A(x) ((x&0x00F0)>>4)
#define GetArg2B(x) (x&0x000F)
#define GetArg3A(x) (x&0x3FFF)

// Limits 
#define REGISTERS_AVAILABLE 0xF+1
#define RAM_AVAILABLE 0xFFFF+1
#define SIZE_OF_STACK 0xFFFF+1
#define DEVICES_AVAILABLE 0xFFFF+1
#define FUNC_LIMIT 0xFF

// The registers
#define $pc     0x0 // Program Counter      What instruction are we on
#define $ram    0x1 // Ram Fetch            The result of RAM fetch
#define $e      0x2 // Overflow/Error if != 0
#define $l      0x3 // Load
#define $j      0x4 // Jump
#define $r      0x5 // Result
#define $d0     0x6 // Device 0             The address of the device to access
#define $d1     0x7 // Device 1             The command being sent to device (if applicable)
#define $p      0x8 // Stack Pop            Value from popped stack
#define $t0     0x9 // Temporary Registers  Expect these to change at any given time
#define $t1     0xA
#define $s0     0xB // General Registers    These will never be changed by the CPU itself
#define $s1     0xC
#define $s2     0xD
#define $s3     0xE
#define $s4     0xF

int main(void) {

    // Program Control
    int running = 1;

    // CPU control
    int halted = 0;
    int IP = 0x0;
    int lastOp = 0x0;
    int stackPos = 0x0;
    int funcCount = 0x0;
    int _0 = 0x0; …
hondros 25 Junior Poster

So how exactly do you create references? I thought that was what I was doing, was passing references using (&variable) to the function? That's what is a bit confusing to me.

So am I doing the endian-ness stuff right then? By explicitly defining the endian-ness?

Wait, you can actually create code that causes the compile to fail if not used correctly? I've been trying forever to find something like that for months. How would I go about doing that? I think I might have an idea. Say you have an if...else block. If one of the values doesn't agree, then that block would never compile, correct?

I will take a look at that. I think once I actually completely understand what I'm doing with the code, I'll use a library. But if I understand it enough to do that, I might as well write my own code. xD

hondros 25 Junior Poster

Thank you for critiquing the code, not too often people do that.
1) The only place I used pointers for was with the reader, which I believe you did as well? If not, can you clarify? This was the only way I could get the reader to work correctly in my code
2) I actually just learned file I/O as a whole, so I really didn't know about any of those classes or anything. Thank you for pointing that out :D
3) I figured the standard size of char is 1, so I probably should've used that, but I forgot about it. Again, thank you for pointing that out.
4) This is where I get confused. Because what if I want to use my file on a separate computer that has a different endianness? Say this one is Big, and the other one is Small. If I were to save the file as Big on one, and open it up as Big, it's fine. How do I keep it cross-compatible, if that's at all possible?
5) See above, I think.
6) I like naming my union types :(
7) Ah yes, I did not notice that. I was copying and pasting from my project, and modified it a bit, so that would be the reason.
8) I already know it doesn't support non-POD types. For my purposes, I don't have a need to contain those right now, and as such I didn't …

hondros 25 Junior Poster

Alright , so I spent _forever_ trying to figure this out. So, if any newbies here need to know how to write and read ANY object (with the exclusion of pointers, but I'll get to that), this is something that can help.

First and foremost, you have to take endianness into account whenever you are working with binary data. We simply use a #define to explicitly state to write with big or little (1 being big, 0 being little).

The code should be fairly straightforward, and what is wonderful is you don't have to explicitly state what the types are thanks to templates. So the following code would work

You should be able to figure out writing pointers/arrays ;) If not, you're not ready to be saving them anyways :P

Also, you should try to roll your own functions after trying this out. I didn't know how to use Unions (hell I didn't even know what they were), and my pointer/dereference was a bit rusty. Also, it helped me learn how memory is mapped better.


This probably won't save complete class objects correctly, you might want to roll your own class function for saving and loading them. If you need to get a head start, I can post my class's functions for you, but you should try to figure it out on your own.

EDIT: Shoot, I forgot to put everything in a main function. Oh well, you should be able to …

hondros 25 Junior Poster

Fixed the problem, never mind. Just had to call System, instead of making two instances of it.

hondros 25 Junior Poster

I posted a while back ago on making directx work in classes. I'm having more issues now. On line 125 (system.cpp), when in debugging, it tells me that it has an access violation. I googled the issue, and someone had said something about initializing the pointer, but that is taken care of in d3d->CreateDevice. If anyone could help me out here, that would be great. Here's my code:
SYSTEM.CPP

#include "system.h"

//////////////////////////////////////////////////
// Class: System
// Private
//////////////////////////////////////////////////

void System::initD3D (void) {
    this->d3d = Direct3DCreate9(D3D_SDK_VERSION);

    ZeroMemory(&(this->d3dpp), sizeof(d3dpp));
    this->d3dpp.Windowed = WINDOWED;
	this->d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD;
	this->d3dpp.hDeviceWindow = this->window;
	this->d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
	this->d3dpp.BackBufferWidth = SCREEN_WIDTH;
	this->d3dpp.BackBufferHeight = SCREEN_HEIGHT;
	this->d3dpp.EnableAutoDepthStencil = TRUE;
	this->d3dpp.AutoDepthStencilFormat = D3DFMT_D16;

	this->d3d->CreateDevice(D3DADAPTER_DEFAULT,
		D3DDEVTYPE_HAL,
		this->window,
		D3DCREATE_SOFTWARE_VERTEXPROCESSING,
		&(this->d3dpp),
		&(this->d3ddev));

	d3ddev->SetRenderState(D3DRS_LIGHTING, FALSE);
	d3ddev->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
	d3ddev->SetRenderState(D3DRS_ZENABLE, TRUE);
};

void System::cleanD3D (void) { 
    this->d3d->Release();
    this->d3ddev->Release();
};

void System::setUpHWND (
                        HINSTANCE hInstance,
				        LPSTR lpCmdLine,
				        int nCmdShow) {
    this->hInstance = hInstance;
    this->lpCmdLine = lpCmdLine;
    this->nCmdShow = nCmdShow;

    ZeroMemory(&(this->windowClass), sizeof(WNDCLASSEX));
    this->windowClass.cbSize = sizeof(WNDCLASSEX);
    this->windowClass.style = CS_HREDRAW | CS_VREDRAW;
    this->windowClass.lpfnWndProc = System::StaticWindowProc;
    this->windowClass.hInstance = this->hInstance;
    this->windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
	this->windowClass.lpszClassName = "WindowClass";
    RegisterClassEx(&(this->windowClass));

    this->window = CreateWindowEx(NULL, "WindowClass", "The Direct3D Program", 
        WS_OVERLAPPEDWINDOW, SCREEN_X, SCREEN_Y, SCREEN_WIDTH, SCREEN_HEIGHT,
        NULL, NULL, this->hInstance, NULL);
};

LRESULT CALLBACK System::StaticWindowProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
    System *SystemPtr = (System*)GetWindowLong(hWnd, GWLP_USERDATA);
 
    if(SystemPtr)
    {
        return SystemPtr->WindowProc(hWnd, message, wParam, lParam);
    }
    else
    {
       return DefWindowProc(hWnd, message, wParam, lParam);
    }
};

LRESULT System::WindowProc (HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) {
	switch(message)
	{
	case WM_DESTROY:
		{
			PostQuitMessage(0);
			return 0;
		} break;
	}
	
	return …
hondros 25 Junior Poster

Jesus XD
That's a lot of info to take. Needless to say, saved into a .txt file for further review.
Thank you very much for the explanation.
And I guess it doesn't have anything to do with DirectX, but I'm a huge newb at windows programming, so I didn't know what to classify it as.

hondros 25 Junior Poster

Oh, so it requires that too. I guess I missed that.
So, what exactly does that code do additionally? I mean, I can understand what it does, but why do you need to do that?

hondros 25 Junior Poster

NOTE:
Never mind, I got it working. Turns out you can't have the WindowProc function set in a class, it has to be a global function.
The way I was doing it was wrong. I got it working.

hondros 25 Junior Poster

I am at my wit's end with this thing. I just can't figure out, why I cannot set the WNDCLASSEX.lpfnWndProc equal to my class's function. Can someone help? Here's my code:
system.h

#ifndef SYSTEM_H
#define SYSTEM_H

#include "stdinc.h"

class System {
  private:
    void initD3D (void);
    void cleanD3D (void);
    LRESULT CALLBACK WindowProc(UINT, WPARAM, LPARAM);
    void setUpHWND (HINSTANCE, LPSTR, int);

    HWND window;
    WNDCLASSEX windowClass;
    LPDIRECT3D9 d3d;
    LPDIRECT3DDEVICE9 d3ddev;

    HINSTANCE hInstance;
    LPSTR lpCmdLine;
    int nCmdShow;
  public:
    System (void);
    System (HINSTANCE, LPSTR, int);
    System (const System&);
    ~System (void);

    void renderFrame (void);
};

#endif

system.cpp

#include "system.h"

//////////////////////////////////////////////////
// Class: System
// Private
//////////////////////////////////////////////////

void System::initD3D (void) {
};

void System::cleanD3D (void) { 
};

LRESULT CALLBACK System::WindowProc (UINT message, WPARAM wParam, LPARAM lParam) {
	switch(message)
	{
	case WM_DESTROY:
		{
			PostQuitMessage(0);
			return 0;
		} break;
	}
	
	return DefWindowProc(this->window, message, wParam, lParam);
};

void System::setUpHWND (
                        HINSTANCE hInstance,
				        LPSTR lpCmdLine,
				        int nCmdShow) {
    this->hInstance = hInstance;
    this->lpCmdLine = lpCmdLine;
    this->nCmdShow = nCmdShow;

    ZeroMemory(&(this->windowClass), sizeof(WNDCLASSEX));
    this->windowClass.cbSize = sizeof(WNDCLASSEX);
    this->windowClass.style = CS_HREDRAW | CS_VREDRAW;
    this->windowClass.lpfnWndProc = this->WindowProc;
    this->windowClass.hInstance = this->hInstance;
    this->windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
	this->windowClass.lpszClassName = "WindowClass";
    RegisterClassEx(&(this->windowClass));

    this->window = CreateWindowEx(NULL, "WindowClass", "The Direct3D Program", 
        WS_OVERLAPPEDWINDOW, SCREEN_X, SCREEN_Y, SCREEN_WIDTH, SCREEN_HEIGHT,
        NULL, NULL, this->hInstance, NULL);
};

//////////////////////////////////////////////////
// Class: System
// Public
//////////////////////////////////////////////////

/*
System::System (void) {
    this->setUpHWND(HINSTANCE hInstance, LPSTR lpCmdLine, int nCmdShow);
};
*/
System::System (void) {
};

System::System (
                HINSTANCE hInstance,
                LPSTR lpCmdLine,
                int nCmdShow) {
    this->setUpHWND(hInstance, lpCmdLine, nCmdShow);

	ShowWindow(this->window, this->nCmdShow);

    this->initD3D();
};

System::System (const System &) {
};

System::~System (void) {
    this->cleanD3D();
};

void …
hondros 25 Junior Poster

I dont get exactly what it does still is there no good documentation for it? and how come you post on all my posts do you live on daniweb and post on all newb stuff? lol im no complaining you have helped me out a bit , are you a forum shark?

Those two are probably the most knowledgeable people on python here ;D

hondros 25 Junior Poster

You need to call the function "input"
So it'd look like:

input()
vegaseat commented: sharp eye +15
hondros 25 Junior Poster

Yes, it said "segmentation fault" yet again. What do I do with this?

hondros 25 Junior Poster

1. I couldn't find which header strlen is in :/
2. It should. But I'm not sure what it's supposed to return.
3. Well in that case, I'll just have it return -1 than what it usually does.

EDIT:
And it still says segmentation fault

hondros 25 Junior Poster

Hello, I'm trying to take a C array of char's and trying to take all of the spaces out of it. Yet I keep running into a segmentation fault. Can anyone help me here?

#include <stdio.h>
#include <stdlib.h>

int strlen(char* Str) {
    int toret=0;
    int i=0;

    char tmp = ' ';

    while (tmp != '\0') {
        toret += 1;
        tmp = Str[i];
        i++;
    }

    return toret;
}

char* deblank(char* OrgStr) {

    char* chr1 = OrgStr;
    char* chr2;

    int len = strlen(OrgStr);

    char* NewStr = (char*) malloc(len + 1);

    int i=0;
    int j=0;

    while (len >= 0) {
        *chr1 = OrgStr[j];
        if (*chr1 != ' ') {
            NewStr[i] = *chr1;
            i++;
        }
        j++;
        len--;
    }

    NewStr[i] = '\0';
    return NewStr;
}

int main(void) {

    printf("TEST\n");

    char* test = "Hello there";
    char* b = deblank(test);
    
    printf("%s\n%s\n", test, b);

    return 0;
}
hondros 25 Junior Poster

You're just missing another quote. I think.
So look for a string that looks like this:

chr(102)+chr(46)+chr(119)+chr(114)+chr(105)+chr(116)+chr(101)+chr(40)+chr(34)+chr(37)+chr(115)

And then add this to it:

+chr(34)+chr(41)

That should fix it.

hondros 25 Junior Poster

I'm pretty sure it's your syntax. First off, if you're opening a file, always use a file descriptor. Such as:

f = open('./tmp/file.txt', 'a')
f.write("%s\n" %(str(saveData[i-1])))
f.close()

Now, not actually having your complete error message, here are some possibilities:
1) You do not have permission to open and change that certain file
2) saveData is not initialized.
3) i is not initialized.
4) there might be an index error.
5) The %s needs to be explicitly a string. Make sure the data you're putting in is indeed a string

Hope this helps

hondros 25 Junior Poster

Oh okay, I was looking in the wrong place xD
I'll take a look, thank you

hondros 25 Junior Poster

Right. I downloaded that package and I can't seem to find it.

hondros 25 Junior Poster

I seem to not be able to find those files. Either in source or the build. I have a new dilemma. I was able to get the function to run through python, however, it now only returns a three character string of \x bits. Here's the code:

static PyObject *
WindowsH_ReadCharacters(PyObject *self, PyObject *args)
{
	DWORD length;
	int x;
	int y;
	
	if (!PyArg_ParseTuple(args, "iii", &length, &x, &y))
		return PyInt_FromLong(1);
	char* string=NULL;
	string = new char[length];
	COORD position;
	position.X = x;
	position.Y = y;

	HANDLE hOut;
	hOut = GetStdHandle(STD_OUTPUT_HANDLE);

	ReadConsoleOutputCharacter(
		hOut,
		string,
		length,
		position,
		NULL);

	return PyString_FromString(string);
}

* Note that the <string> header is not included in the source.

hondros 25 Junior Poster

Thanks, thought it was something else. I want to be able to call it like this:

ReadCharacters(amount, x, y) -> 
   Read the amount of characters at position x, y;
   return a string with the characters

That will call this C funtion

BOOL ReadConsoleOutputCharacter(
HANDLE hConsoleOutput, (Type Handle to Change (use STD_OUTPUT))
LPTSTR lpCharacter, (char pointer to store Characters read)
DWORD nLength, (length to read)
COORD dwReadCoord, (Type COORD to start reading at)
LPDWORD lpNumberOfCharsRead (length actually read)

I'm having a big trouble with this one. I have a ton of other functions from windowsC.h that work. I realize there is win32Console, but it doesn't include all of the functions I need. I just need a C function that will allow me to use that function in Python.

hondros 25 Junior Poster

I have the following function (from windows.h) which I am trying to use the Python C API to allow python to call it. This is the function:

BOOL ReadConsoleOutputCharacter(
  HANDLE hConsoleOutput, (Type Handle to Change (use STD_OUTPUT))
  LPTSTR lpCharacter, (char pointer to store Characters read)
  DWORD nLength, (length to read)
  COORD dwReadCoord, (Type COORD to start reading at)
  LPDWORD lpNumberOfCharsRead (length actually read)

This is a function that uses it correctly:

#include <windows.h>
#include <iostream>
using namespace std;

int main()
{
    HANDLE hOut;
    char Letters[5];
    COORD Where;
    DWORD NumRead;
    int i;

    hOut = GetStdHandle(STD_OUTPUT_HANDLE);

    cout << "A line of little consequence." << endl;

    Where.X = 4;
    ReadConsoleOutputCharacter(hOut,
                               Letters,
                               5,
                               Where,
                               &NumRead);
    cout << "5 letters starting from (4,0) ";
    cout << endl;
	cin.get(); //To see output

    return 0;
}

This is the function that I have written to try to allow python to access it:

static PyObject *
WindowsH_ReadCharacters(PyObject *self, PyObject *args)
{
	int length;
	length = 1;
	int x;
	int y;
	
	if (!PyArg_ParseTuple(args, "iii", &length, &x, &y))
		return PyInt_FromLong(1);

	char read[60000]; //I know this is a large number, I'm not sure how much the user will need.
	char *_string;
	COORD position;
	position.X = x;
	position.Y = y;

	HANDLE hOut;
	hOut = GetStdHandle(STD_OUTPUT_HANDLE);

	ReadConsoleOutputCharacter(
		hOut,
		read,
		length,
		position,
		NULL);

	for(x = 0; x <= length; x++)
	{
		_string[x] = read[x];
	}



	return Py_BuildValue("s", _string);
}

Can anybody help me? Python crashes as soon as I call this. If anyone has a way that could make it better, …

hondros 25 Junior Poster

Here is my issue:
I have a program, that downloads roms off the internet. Everything works fine, but I would like to show an indefinite progress bar while it is downloading. I have that with the following code:

# -*- coding: utf-8 -*-

# Form implementation generated from reading ui file 'progressbar.ui'
#
# Created: Fri Jun 04 12:59:51 2010
#      by: PyQt4 UI code generator 4.7.3
#
# WARNING! All changes made in this file will be lost!

from PyQt4 import QtCore, QtGui

class Ui_ProgressBar(QtGui.QWidget):
    def setupUi(self, ProgressBar):
        ProgressBar.setObjectName("ProgressBar")
        ProgressBar.resize(261, 101)
        sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Fixed, QtGui.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(ProgressBar.sizePolicy().hasHeightForWidth())
        ProgressBar.setSizePolicy(sizePolicy)
        ProgressBar.setMaximumSize(QtCore.QSize(262, 101))
        self.progressBar = QtGui.QProgressBar(ProgressBar)
        self.progressBar.setGeometry(QtCore.QRect(10, 50, 241, 21))
        self.progressBar.setMaximum(0)
        self.progressBar.setProperty("value", -1)
        self.progressBar.setAlignment(QtCore.Qt.AlignCenter)
        self.progressBar.setTextVisible(True)
        self.progressBar.setOrientation(QtCore.Qt.Horizontal)
        self.progressBar.setInvertedAppearance(False)
        self.progressBar.setTextDirection(QtGui.QProgressBar.BottomToTop)
        self.progressBar.setObjectName("progressBar")
        self.Downloading = QtGui.QLabel(ProgressBar)
        self.Downloading.setGeometry(QtCore.QRect(0, 0, 261, 41))
        self.Downloading.setObjectName("Downloading")
        self.partofpart = QtGui.QLabel(ProgressBar)
        self.partofpart.setGeometry(QtCore.QRect(0, 80, 261, 20))
        self.partofpart.setObjectName("partofpart")

        #self.retranslateUi(ProgressBar)
        #QtCore.QMetaObject.connectSlotsByName(ProgressBar)

    def retranslateUi(self, ProgressBar, part1, part2):
        ProgressBar.setWindowTitle(QtGui.QApplication.translate("ProgressBar", "Form", None, QtGui.QApplication.UnicodeUTF8))
        self.progressBar.setFormat(QtGui.QApplication.translate("ProgressBar", "%p%", None, QtGui.QApplication.UnicodeUTF8))
        self.Downloading.setText(QtGui.QApplication.translate("ProgressBar", "<font size=\'25\'><center>Downloading...</center></font>", None, QtGui.QApplication.UnicodeUTF8))
        self.partofpart.setText(QtGui.QApplication.translate("ProgressBar", "<center>Part %s of %s</center>" %(part1, part2), None, QtGui.QApplication.UnicodeUTF8))

    def __init__(self, part1, part2):
        QtGui.QWidget.__init__(self)
        self.setupUi(self)
        self.retranslateUi(self, part1, part2)

if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)
    PB = Ui_ProgressBar(2, (3))
    PB.show()
    sys.exit(app.exec_())

That works fine. This is the issue that I am having. I have the following code, but the gui of the program freezes while it is downloading.

#EXCERPT
    def dlfile(self):
        QtGui.QMessageBox.question(self, "Downloading",
                                       "<html><center>There are %s parts<br />Please wait while all are downloaded</center></html>" %(len(self.curgame)),
                                       QtGui.QMessageBox.NoButton)
        counter = 1
        for x in self.curgame:
            print(self)
            # Set the bar
            self.PB = Ui_ProgressBar(counter, len(self.curgame)) …
hondros 25 Junior Poster

- I will add that to the things that need to be done. Won't be too hard to do, but I just wanted to finish a version that could actually be released
- It was already rar'ed, and I felt too lazy to unrar then rezip it. So I just threw it in.

hondros 25 Junior Poster

I have created a program, and wanted some critique on it. There is a website that I go to in order to download roms, and I do not like clicking a ton of links and waiting 15 seconds to download it, so I created a program to fetch it for me. It is actually quite quick. Anyways, any critique would be appreciated. I have attached the source as there are numerous files.
Note:
Since this site doesn't allow .rar's, it is first rar'ed, than zipped, so you'll need a program that does both

hondros 25 Junior Poster

Hmm... Perhaps use a dictionary to sort it all?

# Original values
L1=['v1', 'v2', 'v3', 'v4', 'v5'] 
L2= [3, 1, 7, 6, 5]
# Dictionary to keep them in order
d = {}
for x in range(0, len(L2)):
    d[L2[x]] = L1[x]
# The dictionary should automatically sort by number, so your output of the dictionary is:
#{1: 'v2', 3: 'v1', 5: 'v5', 6: 'v4', 7: 'v3'}
# Now, create two new lists to store each value if you want
L11 = []
L21 = []
for x in d.items():
    L11.append(x[0])
    L22.append(x[1])
hondros 25 Junior Poster

Or perhaps you could do this:

import os
var = 'test.txt'
os.system('gedit '+var)
hondros 25 Junior Poster

Never mind, I got it all working out

hondros 25 Junior Poster

Okay, so I'm sitting here bashing my head against the desk. I've been googling this for what seems the past hour. I cannot find any relative good links for making Python work with WAMP server. Yes, I understand how CGI scripts work. Unfortunately, I have no idea how to configure Apache to run with Python or anything. I have this script:

#!C:/python26/python.exe -u
print "Content-type: text/html\n"

print('''\
<html>
<head>
<title>Hello</title>
</head>
<body>
Hello world!
</body>
</html>
''')

That I want to run using WAMP. Thought it'd be simple, no? xD Anyways, can anyone give me a detailed explanation on how to get it to work? Without Mod-Python would be nice, because I have no idea what that is, and I keep hearing different thigns about it, such as you don't need it, blah blah blah. Please and thank you.

hondros 25 Junior Poster

Hey, why not just store it in a string and eval() it?

_main = eval("__name__ == '__main__'")

if _main:
    main()
hondros 25 Junior Poster

Hey, just to show you something dangerous you can do with input(), (If the module 'sys' has been imported):

>>> input("> ")
> sys.stdout.write('OGGA')
OGGA

I know it's not much, but think of things you could do with that

hondros 25 Junior Poster

Look, if you want a new function, and you're sure that it'll always be a 3x3 matrix, think about what you need to do. Outline it. Do it by hand a few times, and then list EVERY step needed to do it. Then translate it into the python code. So let me show you something:

# Our 3x3 matrix
matrix = \
[
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9],
]
# What we want it as:
new_matrix = \
[
    [1, 4, 7],
    [2, 5, 8],
    [3, 6, 9]
]
# What steps do we need?
# If we take a look at the number placements, we get this:
# matrix[0][0] = 1
# matrix[0][1] = 2
# matrix[0][2] = 3
# matrix[1][0] = 4
# matrix[1][1] = 5
# matrix[1][2] = 6
# matrix[2][0] = 7
# matrix[2][1] = 8
# matrix[2][2] = 9

# We want it to look like this:
# new_matrix[0][0] = 1
# new_matrix[0][1] = 4
# new_matrix[0][2] = 7
# new_matrix[1][0] = 2
# new_matrix[1][1] = 5
# new_matrix[1][2] = 8
# new_matrix[2][0] = 3
# new_matrix[2][1] = 6
# new_matrix[2][2] = 9

# What steps can we take to make this possible?

If you need further help, don't be hesitant to ask

hondros 25 Junior Poster

Ah okay. I think i understand. What I meant was that I didn't really study types. I get the gist, like str, unsigned int, etc. Just what you said was a bit confusing xP Thank you

hondros 25 Junior Poster

I'm so confused. So only the technical names change, correct? I never really learned about "types" or anything. I've been programming an making full-blown applications without learning that kind of stuff. So do I have to learn it now?

hondros 25 Junior Poster

I don't understand? So something like this in python 2: print("Hello") is a string in 2, and a byte string in 3;
while print(u"Hello") is a unicode string in 2, and a string in 3?

hondros 25 Junior Poster

@ Vegaseat:
What is the difference between a byte string and a string?

hondros 25 Junior Poster

No problem. Glad I could be of help.

hondros 25 Junior Poster

You have a valid point

hondros 25 Junior Poster

It's been dead for 4 years!!! Why would you revive it!

hondros 25 Junior Poster

It's not that it's impossible, just not really practical.

hondros 25 Junior Poster

Also, you'll need to learn a few languages here:
1) HTML (Most definitely)
2) CSS
3) PHP
4) MySQL (or another good database)
Also, you'll need to read up on servers and apache, find what to use, etc etc.

hondros 25 Junior Poster

I'm still using 2.6, but I have the newest 3 installed. I don't use 3, because there aren't many modules made for it. However, I do try and use 3's syntax in 2.6 where applicable (ie print("") not print ""). I do wish that I could do one liner "for" statements with Python, but I guess that'll have to wait xP

hondros 25 Junior Poster

Well, you could just do this as well:

import time
timevar1 = time.time()
# YOUR CODE GOES HERE
timevar2 = time.time()
print(timevar2-timevar1)

That will determine how many seconds it takes for your script to execute

hondros 25 Junior Poster
import os
for x in os.listdir(''):
    if os.path.isfile(x): pass
    else: print(x)

^ The above is for printing only folders.

import os
for x in os.listdir(''):
    print(x)

^ Above code is for printing all folders/files in the directory. No subdirectories

hondros 25 Junior Poster

The escape character "\t" for tabs works wonders ;)

hondros 25 Junior Poster

Okay, first off... See all of those purple words now that it's in the [-code-] tags? Yeah, those mean that they are internally defined, and do something. You want to change all of those variables to something else.
Second, your error is self-explanatory, the variable "line" is not defined anywhere in the program.

Here's a good working program:

# PURPOSE: to count the number of words, lines, and characters in a file
#
# INPUT(S): a file name to be used
#
# OUTPUT(S): count for number of lines, words, and characters in the file
#
# EXAMPLES: input:  ; output:
#           input:  ; output:
#
################################################################################
def fileCount(f):
    # Define all variables required
    linecount = 0
    wordcount = 0
    charcount = 0
    words = []

    # Open the file
    _file = open(f, 'r')

    # Loop through each line
    for line in _file:
        linecount += 1
        word = line.split()
        words += word

    # Loop through all words found
    for word in words:
        wordcount += 1
        # Loop through each word for characters
        for char in word:
            charcount += 1

    return (linecount, wordcount, charcount)

# Name of the file
fname = raw_input('Enter the name of the file to be used: ')
# Unpack the tuple returned by the fileCount
lineCount, charCount, wordCount = fileCount(fname)
print "There are", lineCount, "lines in the file."
print "There are", charCount, "characters in the file."
print "There are", wordCount, "words in the file."

EDIT: Didn't notice your post when I quick posted xD

hondros 25 Junior Poster

@ Dan09:
Okay, in order to get those chr(x) values, all you have to do, is create a string of your code, and run it through this:

def getascii(string):
    torun = 'eval('
    for x in string:
        torun += 'chr(' + str(ord(x)) + ')+'
    torun = torun[:-1] + ')'

Then, you display the code, and save everything in between the quotes as your source. Those numbers are the ascii value of the letter. If you need more help, post back

hondros 25 Junior Poster

Dude, what's up that? It shouldn't be returning '0' for hex(ord('\x00')). It will return '0x00'.

EDIT:
After relooking at the code snippet on my computer, I realize that it does not return what I thought. xD It does indeed return '0x0'. However, you can just do a check of len of each 's'. :D

if len(s) == 1: s = '0'+s

So, here's the whole code:

def tohex(s):
    hexed = ''
    for x in s:
        a = ord(hex(x)).replace('0x', '')
        if len(a) == 1: a = '0' + a
        a += ' ' #add spaces between hex (looks like an editor)
        hexed += a
    a = a[:-1] # Get rid of the last space
    return hexed
hondros 25 Junior Poster

Okay, it wouldn't let me add an attachment, so to confuse the tutorial with my files, here are the two files:
Un-obfuscated:

class _Encryption():

    class NoEncryptValue(Exception):
        def __init__(self, value):
            self.value = value
        def __str__(self):
            return repr(self.value)

    def tobin(self, s):
        '''
        Converts a string to a binary string
        '''
        binary = ''
        for letter in s:
            e = bin(ord(letter)).replace('0b', '')
            if len(e) != 8:
                if len(e) == 1:
                    e = '0000000' + e
                if len(e) == 2:
                    e = '000000' + e
                if len(e) == 3:
                    e = '00000' + e
                if len(e) == 4:
                    e = '0000' + e
                if len(e) == 5:
                    e = '000' + e
                if len(e) == 6:
                    e = '00' + e
                if len(e) == 7:
                    e = '0' + e
            binary += e
        return binary

    def bintostr(self, b):
        '''
        Converts a binary string to a normal string/ BINARY NOW
        '''
        s = ''
        for letter in range(0, len(b), 8):
            s += chr(int(b[letter:letter+8], 2))
        return s

    def tohex(self, s):
        '''
        Converts a string to a hex string
        '''
        encrypted = ''
        for letter in s:
            e = hex(ord(letter)).replace('0x', '')
            if len(e) == 1:
                e = '0' + e
            encrypted += e
        return encrypted

    def hextostr(self, h):
        '''
        Converts a hex string to a normal string
        '''
        s = ''
        for letter in range(0, len(h), 2):
            s += chr(int(h[letter:letter+2], 16))
        return s

    def get_key(self, key):
        '''
        Turns a string into a number for shifting
        '''
        k = []
        for x in key:
            k.append(ord(x))
        return …