Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

EDIT: Never mind, you seem to have come up with more or less the same solution on your own while I was working on this. My version's a little more efficient in terms of space, but yours is easier to understand. You might want to look at my version anyway, if only because I used a few techniques you might want to learn.

Probably the easiest solution is to make a set of functions, each on of which prints a given die result, and call them from a jump table to print out the desired result:

def printOne():
    print """
    =========
    |       |
    |   O   |
    |       |
    =========
    """
   
def printTwo():
    print """
    =========
    |  O    |
    |       |
    |    O  |
    =========
    """


def printThree():
    print """
    =========
    | O     |
    |   O   |
    |     O |
    =========
    """
   
def printFour():
    print """
    =========
    | O   O |
    |       |
    | O   O |
    =========
    """
    

def printFive():
    print """
    =========
    | O   O |
    |   O   |
    | O   O |
    =========
    """
    
def printSix():
    print """
    =========
    | O   O |
    | O   O |
    | O   O |
    =========
    """
    

# This is a random dice game.
import random
die1 = 0
die2 = 0

DIE_ROLL = [printOne, printTwo, printThree, printFour, printFive, printSix]

def dice_roller():
    print "Dice Roller"
    print "==============="
    print "1) Enter 1 to roll a six-sided dice"
     
    sum = raw_input("> ")
     
    if sum == '1':
        die1 = random.randrange(1, 7)
        die2 = random.randrange(1, 7)
        print "The first 6-Sided Die Rolled", die1
        printDie = DIE_ROLL[die1 - 1]
        printDie()
        print "The second 6-Sided Die Rolled", die2
        printDie = DIE_ROLL[die2 - 1]
        printDie()
     
input = 'C'
while 1:
    if input == 'Q': break
    elif input == 'C': dice_roller()
    input = raw_input("press c to continue or q to quit: ").upper()
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The single vertical bar is for the bitwise OR operator. What the code is doing is taking the S_IFDIR flag (which indicates if a given file handle is actually for a directory), and overlaying the bitfield for the desired file permissions, which results in the overall file mode value. See here and here for more details.

BLUEC0RE commented: Very informative post +2
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

WolfShield: You've omitted some crucial details here, starting with, what GUI library you're using (I'd normally assume TkInter, since that's bundled with Python, but this doesn't seem like Python/Tk code). While it is not exactly relevant to the code section in question, it does make it harder to judge where the error is occurring.

Tonyjv: If you look, WS is in fact passing the values as parameters when calling calculate() in the equPressedF() event handler. The problem is, the function doesn't seem to be using the passed values, for some reason.

Or perhaps not... I suspect that the error is coming up in equPressedF() rather than in calculate() . WolfShield, could you please post the traceback that you get when you omit the globals?

Where are the values being passed to equPressedF() meant to be coming from? I am guessing that you intend for them to be read from a pair of textboxes, correct? so where are you reading the values in those?

You might want to decompose the code a bit more, separating the implementation of the calculate() function from the GUI code. This should make testing the parts easier. I tried the following successfully:

def calculate(num1, num2, oper):
    """ Function to act as a simple six-function calculator.
    
    arguments:
        num1 -- first argument of the operation
        num2 -- second argument of the operation
        oper -- string representing the operation to perform
    """
    print("calculate() called")
    if(oper=="+"):
        answ = num1 + num2
        return answ
    elif(oper=="-"):
        pass …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

While Gribouillis's answer is correct, it could probably use more explanation, because the dot-member notation is used somewhat differently in C++ than in Python and it may be somewhat confusing.

In C++, variables have an explicit type, unlike in Python, where variables are typeless (type being a property of the objects which variables reference, not the variables which reference them). There are many different types in C++, but for our purposes there are two broad categories that matter: value variables and pointer variables.

All local named variables in C++ are stored on the stack, a system data structure which keeps track of function calls. When a function in C++ is called, all the information needed for that function - both where it needs to return to, and what variables and arguments it has - is pushed onto the stack, and access to the variables is done by offsets into the stack area. Most of the time, you have variables whose values are the actual data you are working with - for example, if you have an integer value, the integer is stored in the very location on the stack which the variable name refers to. You usually don't need to know all of this - the compiler does this part for you - but it is important to understand that the amount of local memory you have for the function is fixed when the function call is made, and that the local values only exist during the lifetime …

TrustyTony commented: You put your heart in it +13
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Under other circumstances, I would agree; normally, I would have used a MySQL database and been done with it. However, the crux of the problem is that there is an existing MS-SQL database which I need to build a front end for, which means connecting to SQL Server is the paramount priority. I didn't mention this before, though in retrospect I should have.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Before I mark this as solved (or at least resolved), I'd still like to actually see what could be done for this, in case it or something similar arises in the future.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

UPDATE: The PYTHON_EGG_CACHE issue seems to have resolved itself silently, which is almost as perplexing as the problem in the first place. However, I am now back at another problem I've had, namely that I am getting an import error when loading PyODBC:

Request handler failed

Traceback (most recent call last):
  File "C:\Python26\Lib\site-packages\AllProBugProWeb\Http\Isapi.py", line 67, in Request
    return RunWSGI(Handler, Base=Base)
  File "C:\Python26\Lib\site-packages\AllProBugProWeb\Http\WSGI.py", line 155, in RunWSGI
    Result = Application(Environ, StartResponse)
  File "c:\Python26\Lib\site-packages\django\core\handlers\wsgi.py", line 250, in __call__
    self.load_middleware()
  File "c:\Python26\Lib\site-packages\django\core\handlers\base.py", line 39, in load_middleware
    for middleware_path in settings.MIDDLEWARE_CLASSES:
  File "c:\Python26\Lib\site-packages\django\utils\functional.py", line 276, in __getattr__
    self._setup()
  File "c:\Python26\Lib\site-packages\django\conf\__init__.py", line 42, in _setup
    self._wrapped = Settings(settings_module)
  File "c:\Python26\Lib\site-packages\django\conf\__init__.py", line 89, in __init__
    raise ImportError("Could not import settings '%s' (Is it on sys.path?): %s" % (self.SETTINGS_MODULE, e))
ImportError: Could not import settings 'proj.settings' (Is it on sys.path?): DLL load failed: The specified procedure could not be found.

Not that it matters much anymore, as the time I had to try and resolve this has past; despite the preference of both myself and my manager for Python, we have to move forward on this project, which means setting Django aside and going with ASP.NET and C#. Thank you for your efforts, in any case.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

It says then it tries to create file with name of existing folder and fails as it should.

Well, yes. The issue is that it ought to be using the path given in PYTHON_EGG_CACHE, but it appears to have a hard-coded path instead. I've looked up similar cases, and found several references to similar (but not quite identical) problems, but haven't found any solutions to it so far.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

No; it is actually a directory, not a file per se, and it contains files the system needs.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I am making a last-ditch effort to get Django 1.3 configured to talk to SQL Server (both running on the same Windows 7 system), before I have to make a final decision whether to move on to ASP.NET instead. I am using PyODBC (I had tried PyMSSQL but was recommended by one of the developers to switch) and Django-PyODBC as the database driver. I have been able to get manage.py syncdb to work, despite continued problems running the PyODBC test programs, and have tried accessing http://localhost/ in my browser, but with the current configuration, I get the following error:

Request handler failed

Traceback (most recent call last):
  File "C:\Python26\Lib\site-packages\AllProBugProWeb\Http\Isapi.py", line 67, in Request
    return RunWSGI(Handler, Base=Base)
  File "C:\Python26\Lib\site-packages\AllProBugProWeb\Http\WSGI.py", line 155, in RunWSGI
    Result = Application(Environ, StartResponse)
  File "c:\Python26\Lib\site-packages\django\core\handlers\wsgi.py", line 250, in __call__
    self.load_middleware()
  File "c:\Python26\Lib\site-packages\django\core\handlers\base.py", line 39, in load_middleware
    for middleware_path in settings.MIDDLEWARE_CLASSES:
  File "c:\Python26\Lib\site-packages\django\utils\functional.py", line 276, in __getattr__
    self._setup()
  File "c:\Python26\Lib\site-packages\django\conf\__init__.py", line 42, in _setup
    self._wrapped = Settings(settings_module)
  File "c:\Python26\Lib\site-packages\django\conf\__init__.py", line 87, in __init__
    mod = importlib.import_module(self.SETTINGS_MODULE)
  File "c:\Python26\Lib\site-packages\django\utils\importlib.py", line 35, in import_module
    __import__(name)
  File "C:\Python26\Lib\site-packages\AllProBugProWeb\proj\settings.py", line 3, in 
    import pyodbc
  File "build\bdist.win32\egg\pyodbc.py", line 7, in 
  File "build\bdist.win32\egg\pyodbc.py", line 4, in __bootstrap__
  File "c:\Python26\Lib\site-packages\pkg_resources.py", line 882, in resource_filename
    self, resource_name
  File "c:\Python26\Lib\site-packages\pkg_resources.py", line 1351, in get_resource_filename
    self._extract_resource(manager, self._eager_to_zip(name))
  File "c:\Python26\Lib\site-packages\pkg_resources.py", line 1373, in _extract_resource
    self.egg_name, self._parts(zip_path)
  File "c:\Python26\Lib\site-packages\pkg_resources.py", line 962, in get_cache_path
    self.extraction_error()
  File "c:\Python26\Lib\site-packages\pkg_resources.py", line 928, in extraction_error
    raise err
pkg_resources.ExtractionError: Can't extract file(s) to egg cache

The following error occurred while trying …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Odd, I was able to test it myself (after finding some suitable pictures to replace yours with), and the 'correct' and 'incorrect' images seemed to work - though it did sometimes show them overlaying each other if you clicked on two different images. I did have to disable music play, so that may be part of it. Or was it also supposed to show the words 'correct' and 'wrong' as well?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Unfortunately, without the extra image and sound files, there's no way to test your program. Thus, all we have to go on is your comments here. Can you explain just what isn't working? What is going wrong?

I gather you aren't used to these forums; it can take a while to get an answer, so please be patient here.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Let's go back to the original problem spec: what exactly does the assignment say? Does it have to actually open the program Notepad.exe, or do you simply need to display the results in some kind of textbox? Does the data have to be editable? Does it have to be saved to a file, and is it just a scratch file or do you need to let the user give it a specific name? Can you post the actual assignment for us?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The easiest solution would be to use a list, and simply append each new object to the list in a loop. To follow your book list example, here's a sample program that does what you seem to be looking for:

class Book (object):
    def __init__(self, title):
        self.title = title


titles = ("The Joy of Snackes", "Tales of Beedle the Bard", "One Human Minute",
          "The King in Yellow", "The Fragile Path", "The Necronomicon")

books = []
for index, title in enumerate(titles):
    books.append(Book(title))
    print(books[index].title)

(I included the part about enumerating the loop just to show how you could then access the individual objects with an index, even in the loop that creates them if needed. You probably don't need to do it quite this way.)

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You will want to start by reviewing the Bittorrent Protocol Specification, if you haven't done so already. You may want to see this as well, as it gives a somewhat easier to follow version of the protocol spec. The Wikipedia article about the protocol may also prove useful.

The first thing to know is how to encode and decode in the Bencode format; fortunately, this is particularly easy to do in Python, as the format was designed with the Python types in mind. I am guessing you're already passed that hurdle, but it is the first one to mention.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As you can see, LogicallyInsane, the question you're asking isn't very clear as the answers were focused on the example rather than the actual meaning behind it. What is it you are trying to accomplish? Just how are you trying to 'combine' if: statements? Do you mean, how do you write nest if:s? Or do you mean, how do you combine two or more conditionals into one? Or (as Tonyjv interpreted it), how do you simplify if:/elsif:/else: combinations when two or more of them are redundant? What you want isn't entirely clear.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Is it safe to assume that there is more to this code somewhere? I ask this because the index values never get changed in the code as given, which would result in an endless loop.

As for initializing the arrays to zero, the best approach is the one given by Gerard4143 earlier: iterate through the array of arrays and clear all of the values, before using them arrays. If you want a general solution to clearing blocks of memory (which is exactly what arrays are), you can use memset().

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You have to keep in mind that the goal is to get the month, not the amount. To get that, you need to actually iterate through the months where the rainfall occurred, and save the one which had the highest rainfall. That having been said, this version will return both the month and the amount:

def main ():
    rainfall = rainInput ()
    totalRain = totalRainfall (rainfall)
    average_Rainfall = averageRainfall (totalRain)
    highestMonth, highestMonthly = highestMonthNumber (rainfall)
    print #this is for spacing output
    print 'The total rainfall for the year was: ' +str(totalRain) + ' inche(s)'
    print #this is for spacing output
    print 'The average rainfall for the year was: ' +str(average_Rainfall) +\
          ' inche(s)' 
    print #this is for spacing in output
    print 'The highest amount of rain was', highestMonthly, 'in' , highestMonth


def highestMonthNumber (rainfall):
    month = ['January','Febuary','March','April','May','June','July','August'\
                ,'September','October','November','December']
    highestMonthly = 0
    for m, n in enumerate(rainfall):
        if n > highestMonthly:
            highestMonthly = n
            highestMonth = m
    return month[highestMonth], highestMonthly
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, I'm confused; you appear to have switched suddenly from selection sort to quicksort. Any particular reason?

Selection sort is considerably simpler to implement. Here's a simple variant of it:

def selectionSort(unsorted):
    if len(unsorted) <= 1:
        return unsorted
    else:
        sorted = list()
        element = min(unsorted)
        sorted.append(element)
        unsorted.remove(element)
        sorted.extend(selectionSort(unsorted))
        return sorted

Whereas what you're doing now is more like this:

def qsort(unsorted):
    if len(unsorted) <= 1:
        return unsorted
    
    pivotPos = len(unsorted) // 2
    pivot = unsorted[pivotPos]
    smallerlist = list()
    largerlist = list()
    
    unsorted.remove(pivot)
    
    for x in unsorted:
        if x <= pivot:
            smallerlist.append(x)
        else:
            largerlist.append(x)

    sorted = list()
    sorted.extend(qsort(smallerlist))
    sorted.append(pivot)
    sorted.extend(qsort(largerlist))
    return sorted

Any particular reason for the switch?

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The min() function finds the smallest element of a list. If you type min([4, 3, 5, 7, 11, 9, 22]) , at the Python interactive prompt, it returns 3. So you can use it to find the smallest element, as you are saying.

With the selection sort, the idea is not to compare the smallest value with the other values - you already know it is the smallest - but to replace the lowest element with the smallest, then the next lowest with the next smallest, and so on until you have a sorted list. In this case, it is easiest to make a new list rather than moving the elements around, because lists are so inexpensive in Python.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The easiest solution is to use min(), which finds the object in a list that sorts lowest. You can then use remove() on the original list and call selsort() on the remaining part of the original, which can be added to the sorted list with the extend() method.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Actually, you are already breaking them down into three parts with your existing code. The split() function returns a list, which can then be either accessed by index:

for line in inputFile:
    values = line.split()
    name = values[0]
    rate = float(values[1])
    hours = int(values[2])

... or assigned directly to named variables:

for line in inputFile:
    name, rateString, hoursString = line.split()
    rate = float(rateString)
    hours = int(hoursString)

Either approach should give you the values you need out of an individual line of text; the indexing approach is probably a bit more stable, as the named variables approach could cause problems if there were accidentally more or fewer than three items on a line.

If you don't mind me asking, what languages have you worked in before? You mention that you've done similar assignments in the past, and knowing what you already know could help in putting the explanations into a familiar context.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

You still need to change Transaction so that it gives a price for the RetailItem in question. Here's one way to do it:

import java.util.Scanner;
import java.text.DecimalFormat;

public class Transaction  {
   
    //Methods
   
    public static void main(String[] args)    {
        String itemName = " ";
        double itemCost = 10.00;
        
        Scanner sc = new Scanner(System.in);
        DecimalFormat df = new DecimalFormat("#0.00");
     
        System.out.print("What is the name of the item being purchased? : " );
        itemName = sc.nextLine();
           
        System.out.print("How many " + itemName + "(s) are you buying? ");
        int quantity = sc.nextInt();
      
        System.out.println();
        
        RetailItem myRetailItem = new RetailItem(itemName, quantity, itemCost);
        CashRegisterA myCashRegisterA = new CashRegisterA(myRetailItem, quantity);

        System.out.print("Subtotal:     " + df.format(myCashRegisterA.getSubTotal()));
        System.out.println();
        
        System.out.print("Salestax:     " + df.format(myCashRegisterA.getTax())); 
        System.out.println();
            
        System.out.print("Total:        " + df.format(myCashRegisterA.getTotal()));
    }
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I don't think you would need RetailItemDemo in Transaction , but you will definitely need RetailItem and CashRegisterA . What I would suggest is to create the c'tor I mentioned above, and then create myCashRegisterA like so:

RetailItem myRetailItem = new RetailItem("Widget", 10, 10.00);
         CashRegisterA myCashRegisterA = new CashRegisterA(myRetailItem, 4);

With the name and amounts set to whatever you feel suitable.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, you never set retailPrice , which presumably should be getting it from myRetail.price , or else from a method of some sort.

Also, the price for myRetailItem isn't being set in the Transaction class' main() function. Furthermore, the myRetailItem object in Transaction is not the same as the one in the myCashRegisterA object (and change the default c'tor so that you initialized an empty myRetail there instead of at the declaration), so setting that price has no effect on the one which would be used to calculate the total.

Most likely, you need to set up a non-default constructor for CashRegisterA which can take a RetailItem object as an argument, which would then be used as the value of myRetail :

public CashRegisterA(RetailItem ri, int q) {
        myRetail = ri;
        quantity = q;
        retailCost = myRetail.getPrice();
    }

    public CashRegisterA(int q) {
        this(new RetailItem(), q);
    }

    public CashRegisterA() {
        this(0);
    }
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The try blocks are not necessary in the first place. Printing "the hourly rate is not a number" is worse than letting an exception propagate, because the exception gives you the line number where the error occurred and the functions which where called, etc.

Ordinarily I would agree, but in this case, the error would almost always be in the data file, not the code. Therefore, it makes sense to indicate where in the data the problem occurred, and then attempt to continue processing the rest of the data.

TrustyTony commented: Good point of warning about specific bad data and going on +2
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I found two serious problems with the convert() function. First, you are returning a pointer into a local variable, a variable which is likely to be partially or wholly overwritten by the time you are trying to print it. The solution to this is to one more character buffer and pass that as an argument to convert(); even if the buffer is not used directly, it will hold the data even after the convert() function ends, allowing you to use pointers to walk through it.

More seriously, the function does not address whitespace characters at all. This is a serious problem, because even if you haven't deliberately added any whitespace, the fgets() function will read in the trailing newline character, meaning that the whole function stalls out. Adding another clause to the function to test for spaces and newlines, and walking past them, appears to fix the problems you are experiencing.

char *convert(struct stack *s,char *source, char* dest)  //converting source into prefix
{
    char *t,opr;
    dest[0]='\0';                              //Null added at end of dest
    t=&dest[1];
    while((*source)!='\0')
    {
        if(*source == ' ' || *source == '\n')
        {
            source++;
        }
        else if(isdigit(*source)||isalpha(*source))
        {
            while(isdigit(*source)||isalpha(*source))
            {
                *t=*source;
                t++;
                source++;
            }
        }
        else if(*source==')')
        {
            push(s,*source);
            source++;
        }
        else if(*source=='+'||*source=='*'||*source=='-'||*source=='/'||*source=='$'||*source=='%')
        {
            if(s->top==-1)
                push(s,*source);
            else
            {
                opr=pop(s);
                while(priority(opr)>priority(*source))
                {
                    *t++=opr;
                    opr=pop(s);
                }
                push(s,opr);
                push(s,*source);
            }
            source++;
        }
        else if(*source=='(')
        {
            opr=pop(s);
            while(opr!=')')
            {
                *t++=opr;
                opr=pop(s);
            }
            source++;
        }
    }
    while(s->top!=-1)
    {
        opr=pop(s);
        *t=opr;
        t++;
    }
    t--;
    return t;
}

I've only tested this with some …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I'll look over the code and see if I can find anything that stands out but there is one thing I can say: you would be wise to use fgets(str1, 10, stdin) with instead of gets(str1) , as gets() can all too easily have a buffer overrun and crash the program. The gets() function has been consider deprecated for some time now, though it presumably isn't getting removed from the standard I/O library for reasons of backward compatibility.

As I said, I'll try to find something more relevant to the problem at hand.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Can you tell us about the format of the text file your reading - that is to say, in what order do you expect things in? For example, does it have the name of the employee followed by the hourly wage followed by the hours worked? Or is it in some other order? Are the fields of the record separated by spaces (as seems to be the case) or something else (e.g., semicolons)? could you post a few lines from the data file so we can see what you are trying to work on?

I suspect that rather than having that inner loop, you will need five different sections inside the main file loop:

for each line of the text file:
    split the line into individual words
    read in the name
    read in the hourly rate and convert it to a float
    read in the hours worked and convert it to an int
    compute the total salary
    print the result as a line of the table

The exact order of the first three will depend on file format, but the last two would definitely be at the end. I would recommend writing the part that computes the salary as a separate function, so that you can think out the logic of it independent of the rest of the program. If you need help with that ask.

Don't forget to put the float and int conversions in try: blocks, in case something is wrong in the text file:

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

One of the things you need to see as well about segment:offset addressing is that segments can overlap; a segment can begin on any 16-byte paragraph boundary (not page, that was a careless error on my part). It has to do with the particular way in which addresses are calculated in real mode, where the physical address is computed by the system by adding the value of the 16-bit segment offset to a 16-bit local address, with the segment value being offset by four bits:

0000 0000 0000 0000          segment address
     0000 0000 0000 0000     offset address (local address)
------------------------
0000 0000 0000 0000 0000     20-bit linear address

(There is actually a 64Kbyte-16byte section of addressing space that was lost this way in the original design, when the addresses added up to more than 1Mbyte; later systems, which had 24bits and eventually 32-bits of physical addressing would call this the Real Mode High Memory Area, and MS-DOS was hacked to allow it to be used for part of the system software.)

Anyway, the point is that segment addressing in the original x86 was not a straightforward matter of having a series of separate segments one following the other, as one might assume. One aspect of this is that most linear addresses had more than one segment:offset address which could refer to it. For example, both 0000:00f0 and 000f:0000 refer to linear address 000f0.

You might ask why this was done this way. Well, at the time, …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

It depends on how you're handling the inserts, and whether you're using the list as a queues or not. If you are inserting to the end of the list, then having a pointer to the last element is a practical way of speeding up insertions. However, how you insert may depend on how you are using the list.

If you are using the list as a first-in-first-out queue, then it makes sense to have an end pointer, as you would need rapid access to both ends of the list, and would want to insert to the end.

However, if you're using the list as a stack, it would make more sense to insert to and remove from the top of the list, in which case having an end pointer isn't helpful.

If it is an ordered list, you can use the end pointer to see if an inserted element sorts higher than the current end of the list, in which case you can insert to the end directly; otherwise, you would have to traverse the list to find the insertion point. Whether this optimization is worth the trouble would depend on whether you expect most new elements to come at the end of the list or not.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Actually, the align type doesn't impact the maximum size of the segment. In real mode, a segment has a maximum size of 64K, regardless of any other factors, and segments are always aligned on 16-byte pages. In other memory modes, things get more complex, and you can have segments of up to 4Gb in size.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The best place to look for operating system development information would be The OS-Dev Wiki and Forum. They have a wealth of knowledge and several experienced systems programmers on the message boards.

I will warn you, however, that they expect you to come well-prepared when asking questions on the fora, and do not tolerant laziness or failure to follow the forum guidelines; read through the wiki and the forum archives before posting.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I've done some checking, and it seems that under the MARS program (which appears to be what you're using) the equates I recommended don't work. This is unfortunate, and I am sorry if I misled you in any way. Without them, the function above would look like this:

###############################
# (char*, object*) read_line(char*) 
# Read a line of text into the input buffer and parse it
###############################

read_line:
    addi $sp, $sp, -12  # set aside 12 bytes on the stack
    sw $fp, 0($sp)      # save the old frame pointer
    addi $fp, $sp, 0    # set the frame pointer to the stack, plus the number of s-regs
    sw $ra, 4($fp)      # save the current return address
    sw $a0, 8($fp)      # a0 == pointer to current position in input buffer

    li $v0, 8 
    syscall

    lw $a0, 8($fp)
    jal parse_object

    lw $a0, 8($fp)      # restore the values of the saved registers
    lw $ra, 4($fp)
    lw $fp, 0($sp)
    addi $sp, $sp, 12   # reset the stack
    jr $ra
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

To control $ra, what you to do is use the system stack to store it (as well as the frame pointer and any s registers which are used in a subroutine) and then restore it back to it's previous value when the routine ends. There is a convention for doing this established by the MIPS designers and while you don't need to follow it, it makes it much easier to use a routine with other existing ones if you do.

The overall approach is the same as the one I discussed in my previous post. What you do is, at the beginning of a function that will need to call other functions in turn, you increment the stack by an amount sufficient to hold the frame pointer, the return address pointer, and any s registers (the s stands for 'saved') which the function uses (to ensure that the previous functions which used them don't lose them), and any argument registers which the function may need to change when calling other functions. Before the function exits, you need to reverse this, restoring the saved registers and then resetting the stack pointer.

As I said earlier, if you can, it is helpful to define some equates which hold the offsets for the frame pointer; the offsets in questions are

#stack offsets
fp.ra = 4
fp.a0 = 8
fp.a1 = 12
fp.a2 = 16
fp.a3 = 20
fp.s0 = -4
fp.s1 = -8
fp.s2 = -12
fp.s3 = -16
fp.s4 = …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

we can start by 'correcting' the indentation, courtesy of astyle:

#include<stdio.h>

int main()
{
    int i, j;
    int n,M[10][10],min=3267;

    /* read in the values of the matrix */
    printf("\nEnter the order of square matrix:");
    scanf("%d",&n);

    for(i=1; i<=n; i++)
    {
        printf("\nEnter the elements of the row %d:",i);
        for(j=1; j<=n; j++)
        {
            scanf("%d",&M[i][j]);
        }
    }

    /* print out the matrix as confirmation */
    for(i=1; i<=n; i++)
    {
        for(j=1; j<=n; j++)
        {
            printf("\t %d",M[i][j]);
        }
        printf("\n");
    }

    printf("\nNow subtract each element from every row from their respective minimum  value\n");

    /* find the minimum value for each row and subtract it from the row elements */
    for(i=1; i<=n; i++)
    {
        min = M[i][0];      /* reset the minimum value to the first element of the row */
        for(j=1; j<=n; j++)
        {
            if(M[i][j]<min)
                min=M[i][j];
        }
        for(j=1; j<=n; j++)
            M[i][j]=M[i][j]-min;
    }

    /* print the resulting matrix */
    for(i=1; i<=n; i++)
    {
        for(j=1; j<=n; j++)
        {
            printf("\t %d",M[i][j]);
        }
        printf("\n");
    }
}

And I have to concur about the SMS crap - if you persist in it, I doubt anyone will bother reading your posts, never mind answering them.

Finally, I think you'll find that Adak was right: I added the line

min = M[i][0];      /* reset the minimum value to the first element of the row */

and the program now runs correctly. HTH.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, what hardware and/or emulator is this for (PS2, SPIM, MARS, MIPSsym, etc.)? Keep in mind that, if this is for actual MIPS hardware and not SPIM, then you have to take the branch and load delay slots into account (unless the assembler is doing that for you automatically, but even then it's something you need to be aware of).

Second, where is it hanging? Does the program do anything unusual before it hangs?

Third, were you aware that you syscall twice in a row in play_short?

And some advice: if your assembler allows them (I know that MARS doesn't), you might find it worthwhile to define equates which name the various system calls, as well as for the standard stack offsets. Here are the ones for SPIM which I have used in the past, based on those provided by my old assembly language professor:

################################################################################
#stack offsets
fp.ra = 4
fp.a0 = 8
fp.a1 = 12
fp.a2 = 16
fp.a3 = 20
fp.s0 = -4
fp.s1 = -8
fp.s2 = -12
################################################################################
#System calls
print_int   = 01 #$a0  = integer
print_float = 02 #$f12 = float
print_double= 03 #$f12 = double
print_string= 04 #$a0  = string
read_int    = 05 #returns integer in $v0
read_float  = 06 #returns float   in $f0
read_double = 07 #returns double  in $f0
read_string = 08 #$a0 = buffer, $a1 = length
malloc      = 09 #$a0 = size of request returns pointer in $v0
Exit        = 10
print_char  = 11 #$a0 …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Basically, the function returns the difference between the lower number and the higher number, if and only if the lower number is the first number. The 2 is to account for the fact that both the lower number is being incremented and the higher decremented when they are passed to the recursive call.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Ordinarily, I would simply direct you towards Google, but after quickly checking the results myself I find that there aren't many such resources to be found. This online textbook is probably the best resource I was able to find.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I'll do the OP a favor here and repost his code (retrieved via Reply) with appropriate formatting:

import urllib
import zipfile
import re

totaal = 0
commentaar = []
lus = True
image = urllib.URLopener()
image.retrieve("http://www.pythonchallenge.com/pc/def/channel.zip","channel.zip" )
bestand = "readme.txt"
zf = zipfile.ZipFile('channel.zip')

while lus == True :

    for filename in [ bestand ]:

        try:
            data = zf.read(filename)

        except KeyError:
                print 'ERROR: Did not find %s in zip file' % filename
        else:
                print filename, ':'
                data = repr(data)
                print data
                comments = zf.infolist()

                for test in comments:
                    commentaar.append(test.comment)
                print

        nummer = re.search('\d{2,}', data)

        try:
            bestand = str(nummer.group())+".txt"
            print bestand

        except:
            lus = False 

print commentaar
vegaseat commented: thanks +13
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Oh dear. I recently used this over at DevShed, and now I fear I need to use here, too. Pity.

First off, we don't do other people's homework for them. Second, we don't do other people's homework for them. And third, we don't do other people's homework for them. Sensing a pattern here yet?

No one here will simply hand you a solution on a silver platter. If you show us what you've done, what you've tried to do, and what problems you've had with it, then we'll be happy to help. If you have specific questions, we can answer them, or at least point you in the right direction. If you have a program with a bug you can't swat on your own, we'll be glad to assist, so long as you pay attention to the forum rules and post sensible questions in an intelligent manner that we have some reasonable hope of answering.

But just cutting and pasting an assignment into a message, without even prefacing it with something like, "I have this homework problem that I can't solve...", is likely to get you booted from the message boards here and elsewhere - if you're lucky. What happens to you if you are unlucky is... well... let's just say that this guy probably won't be trying that again, on that forum or this one.

We take this issue seriously here. Very seriously. Asking us to do homework for you is …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If OS development is what you have in mind, you might want to look into the OS-Dev Wiki and forums. I'll warn you, though, they are not very tolerant of those who come into their message board unprepared, or who don't follow the forum rules; make sure that you've exhausted your other resources before posting a question there.

Ancient Dragon commented: Excellent :) +33
sree_ec commented: Excellent URL :) +1
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I just noticed that I forgot to change the subscripts in one section - it should have been

printf("\n\nEnter inventory type: ");
            scanf("%s", &dontype[donc]);
            printf("Enter the amount: ");
            scanf("%d", &donamt[donc]);
            printf("\n\t* Donation Added! *\n\n");
            donc++;

However there is another problem with this code that I recommend attending to before tackling part three. As it is now, if two donations of the same type are processed - say, two entries of 'MILK' - then they are recorded separately. You need to read the donation type into a temporary buffer, then check through the list of donations to see if it is a match for an earlier one, and if it is, you need to add the amount of the new donation to the old one. The main function you'll need for this is strcmp(), string compare, which returns 0 if the two strings match, and strcpy(), to copy the value in the buffer to the dontype string when there's no match.

Since you'll need to use those two functions in the third part, it make sense to make sure you have them working correctly in the first part, which is less complicated.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I am curious about the follow set of loops:

for (i=donc;i<donc+1;i++)
            {
                while (stop !=1)
                {
                    printf("\n\nEnter inventory type: ");
                    scanf("%s", &dontype[i]);
                    printf("Enter the amount: ");
                    scanf("%d", &donamt[i]);
                    printf("\n\t* Donation Added! *\n\n");
                    stop = 1;
                }
            }

With the for() loop, you have the value of i set to donc, the then comparison tests against donc+1; in other words, it stops after the first pass, as if the loop weren't there. Similarly, you have the while() loop testing against stop != 1, followed by unconditionally setting stop to 1 - again, ensure that there effectively isn't any looping. Why did you include these around them? This seems very cargo-cultish, as if you were copying a particular idiom you'd seen or used elsewhere (probably in the menu part, where you need the loop to verify that the input is valid) without really understanding it. The whole section could be boiled down to:

printf("\n\nEnter inventory type: ");
            scanf("%s", &dontype[i]);
            printf("Enter the amount: ");
            scanf("%d", &donamt[i]);
            printf("\n\t* Donation Added! *\n\n");
            donc++;

I hope you can see why this simplifies the code without losing any of its effect.

On another note, you have this conditional:

else if (choice !=1,2,3,4,5)
        {
            printf("Sorry, that was an invalid choice.\n\n");     
        }

Unfortunately, in C, you can't compare a single value against a list of values like this; the commas only confuse the issue, since they become comma operators and are effectively null operations. I'm not certain that this would even compile, to …

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, here's the thing: Python, by itself, is not a language designed specifically for web-page design, the way the (for example) PHP or Javascript are. It can be used for this purpose, but you need to import some particular tools for it, namely the cgi module.

What CGI stands for is Common Gateway Interface, and it is a way to let the HTTP server run programs on the server automatically when the program file is requested, rather than serving it to the browser. Python is just one of the languages that can be used with CGI. The HTTP server, for it's own part, usually needs to have the CGI script in a specific directory and has other settings for how it has to be handled so that it knows that the Python source file is a CGI script and not some general program.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The new code posted has a very incomplete feel to it, as if it were from somewhere in the middle of some function. Could you please give some idea where this would be going in the program? I'm assuming that it would be somewhere after the menu, but where? It looks like the part for fulfilling a request, but I can't tell for certain.

By the way, has the professor gone over the subject of functions yet? I wouldn't expect so, unless the class is moving forward very rapidly, but it seems to be about where you might be starting to break the program into smaller parts.

Finally, as I'd asked before, if you tell us what parts are confusing you, we may be able to do more to help.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

While Dev-C++ and Code::Blocks are indeed good IDEs, that's all they are - development environments. They both use the MinGW version of GCC for their default compiler, and that may be the best choice to use with Eclipse,too.

OTOH, if you get Visual C++ Express, which like MinGW is free, you should be able to configure Eclipse to work with it as well.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, then. Assuming that we're talking about 16-bit code, a simple linked list node in MASM might look like this:

node STRUCT
    data WORD ?
    next WORD ?
node ENDS

Of course, the structure itself isn't the only important factor; it's how you use it that counts. The structure is more or less a template or pattern for a particular interpretation of a block of memory. In the case of a linked list, generally speaking this memory will be allocated at run time from the operating system.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

If you have interest in mathematical computing, you could try Project Euler. Also, you could join one of the many projects on SourceForge or Savannah, or simply download the source code from a few of them to read it. Finally, you could try learning about different languages, as this can give you a lot of insight as to what is specific to a language versus what is common across languages - look at Rosetta Code for examples from several different languages.

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As a piece of advice, you could probably make the program a lot more readable if you broke main() down into several separate functions. Also, you could use switch() rather than the long series of if/else if/else statements when testing (for example) nCheckOut - though in that particular case you could instead just use

if (nCheckOut > 0)
                Queue.Enqueue(Weapons[nCheckOut - 1]);

instead.