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

If I understand what I've read here and here correctly, what is happening is that the timeout value isn't being set, which means that the socket is being treated as non-blocking (that is, it should not wait for the other end of the socket); however, certain socket operations apparently only work if there is a set timeout. Try using socket.setdefaulttimeout() with a suitable timeout factor.

If this doesn't work, please post the section of code in question (using code tags) so we can see what is actually happening.

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

You could also implement a discriminant union and make a queue of those; this would let you use doubles for the numbers.

enum QueueElementType {NUMBER, OPERATOR};

struct QueueElement 
{
    enum QueueElementType type;
    union 
    {
        double number;
        char operator;
    } element;

    struct QueueElement *next;
};
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I would actually start by implementing the GradeRecord class, if it hasn't been provided for you already. That's really more the key to this sort of problem than the main() function will be.

Also, I am assuming that <isostream.h> is supposed to be <iostream.h> , in which case I can only assume that your textbook, your compiler and most likely your professor are at least ten years out of date. The modern version is called simply <iostream> . Most modern compilers will support both versions, but the one without the ".h" extension is strongly preferred.

Finally, when posting here, you should always put your code in between [code] and [/code] tags, or use the [code] button at the top of the editing window and paste it in.

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

First, you would create the Fraction object using new Fraction(x, y); , with whatever values you need there instead of x and y. So, if you were multiplying 1/2 by 2/3, you would write:

Fraction first = new Fraction(1, 2);
Fraction second = new Fraction(2, 3);
Fraction third;

third = first.multiply(second);

Now, you note that you are using one of the Fraction objects to call the method. This is because, conceptually, the method is actually a message your sending the object telling it to do something according to a set of rules (hence the term 'method' instead of 'function'). When you write a (non-static) method, you don't need to explicitly name the object that it is called with; it has an implicit variable called 'this' which references the object. So, the signatures for Fraction.multiply() might look like:

public Fraction multiply(Fraction multiplicand) { ... }

public Fraction multiply(int multiplicand) { ... }

You'll note that I just defined two different methods with the same name, but different arguments - this is called overloading and it can make some things a lot easier, if you're careful not to abuse it.

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

The Portland Pattern Repository (aka Ward's Wiki) was originally founded for users to identify and name patterns; while it has drifted quite a ways from this original purpose, it still has a very comprehensive directory of the known patterns.

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

In which language?

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

I can think of a simple to this problem, but have two suggestions. First, declare an enumeration type to represent the potions, rather than using an int or a char:

enum POTIONS {NONE, HOGWART, ELVEN_TEARS, LIGHT_OF_HEAVEN};

The reason for this is that you can declare variables in this new type which can only be one of those three values, and it makes it a lot less likely that you'll make a mistake and use an invalid value.


Second, I recommend replacing the separate potion1 and potion2 variables with a two-element array, which you would declare in the main() menu:

POTIONS potions[2] = {POTIONS.NONE, POTIONS.NONE};

This not only makes the solution easier, it also makes the connection between things clearer, and makes it easier when the time comes to use a combination of more than two potions.

The simple solution, then, is to have printBuyPotionsMenu() run once when it is called, and return the potion value that was selected:

POTIONS printBuyPotionMenu()
{
    char potionChoice;

    while (true)
    {
        cout << "***************************************************\n";
        cout << "*        Available Potions           *\n";
        cout << "***************************************************\n";
        cout << "*The following potions are available for purchase:*\n";
        cout << "* a) Hogswart                      *\n";
        cout << "* b) Elven Tears                    *\n";
        cout << "* c) Light of Heaven                    *\n";
        cout << "* d) Back to main page                *\n";
        cout << "***************************************************\n";
        cout << "Enter your choice:";
        cin >> potionChoice; 
        
        switch (potionChoice)
        {
            case 'a':
                return POTIONS.HOGWART;
            case 'b':
                return POTIONS.ELVEN_TEARS;
            case 'c':
                return POTIONS.LIGHT_OF_HEAVEN; …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

That last part is valid, if confusing. There is a little-used comma operator in C and C++ that acts more or less the same as a semi-colon; it is mostly used to allow multiple statements in the initialization and increment sections of for() loops, but it works elsewhere as well. Unfortunately, this probably wasn't what the OP had in mind; as you stated, the typical idiom would be simply

char potion1 = '?', potion2 = '?';
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

I would recommend not using the lowercase 'l' as a variable name; it's too easily confused with the numeral '1'.

Also, you don't need the extra variable here; the two loop indices are enough information. if you rename 'l' as 'j' and reverse the test in the if statement, it ought to work.

Finally, I suggest that you be more careful with you indentation; you should have the inner loop indented more than the outer one, and the if indented even more. The exact style of indentation is up to you, but you really ought to indent it so that the levels of nesting are clear:

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

main()
{
      int i=0; // loop counter
      int j=0; // number of y's printed

      for(j=0;j<=10;j++)
      {
          for(i=0;i<10;i++)
          {
              if(j>i) 
                  putchar('Y');
              else 
                  putchar('X');
          }
          printf("\n");
      }
      system("pause");
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

And my professor hasn't taught us how to indent properly, lets put it this way, he doesn't even care, as long as the program does what he wants it to do and it works.

If so, then your professor is an imbecile who doesn't know his own business. Readability is one of the most important factors in programming; a working but unreadable (and hence unmaintainable) program is of little real use in the long run. You have to write programs as if they are to be read and changed, not just compiled.

Sorry to be so harsh, but this is an issue that I take very seriously, and I think you'll find that most others here do as well. If nothing else, there are enough programs such as astyle which can automatically indent the code for you that not indenting it is absolutely inexcusable for anyone but novices - it should have been one of the first things taught to you, and not doing so is a grave failure IMAO. I can understand that there are different styles of indentation, but indentation of some sort is nearly universal in C programming.

I'm not faulting you - you didn't know - but your professor's attitude is a major problem.

I noticed some issues with my earlier code, but since you haven't covered switch() statements in class yet, I'll hold off on posting the corrected code.

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

While there may not be much to it yet, it is a start. I would, however, recommend being more careful with indentation. I would also suggest changing the long series of if()s to a single switch() statement, as that would probably be clearer:

#include <stdio.h>
#include <string.h>

int main()
{
    int choice, i, t;
    char type[100][20];
    int amount[100];

    printf("Welcome to the food Bank Program.\n\n");
    printf("\t1. Add a donation\n\t2. Add a request\n");
    printf("\t3. Fulfill a request\n\t4. Print status report\n\t5. Exit\n\n");
    printf("Enter your choice: ");
    scanf("%d", &choice);

    while (choice != 5)
    {
        switch (choice)
        {
            case 1:
                printf("\n\nEnter inventory type: ");
                scanf("");
                printf("Enter the amount: ");
                scanf("");
                printf("\n\nDonation Added!\n\n");
                break;
            case 2:
                printf("\n\nEnter inventory type: \n");
                scanf("");
                printf("Enter the amount: ");
                scanf("");
                printf("\n\nRequest Added!\n\n");
                break;
            case 3:
                printf("\n\n--------Fulfilling Requests--------");
                printf("\n\nCannot be Fulfilled.\n\n");
                printf("\n\nPartially Fulfilled.\n\n");
                printf("\n\nRequest Fulfilled!\n\n");
                break;
            case 4:
                printf("\n\nPrinting the Donations Table\n\n");
                printf("\n\nPrinting the Requests Table\n\n");
                break;
            default:
                printf("Sorry, that was an invalid choice.\n\n");
        }
        printf("Welcome to the food Bank Program.\n\n");
        printf("\t1. Add a donation\n\t2. Add a request\n");
        printf("\t3. Fulfill a request\n\t4. Print status report\n\t5. Exit\n\n");
        printf("Enter your choice: ");
        scanf("%d", &choice);
    }
    printf("\nThank You for using the software. Bye for now.\n\n");
    return 0;
}

More to come as I go over the problem statement, if I get a chance.

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

Before we go further, can you tell us which assembler you're working in? There are significant differences in how different assemblers handles structures.

Also, if you're working in linked lists, we'll also need to know the operating system, as you'll need to use the system calls for memory allocation and deleting.

This thread may help you understand how structures in assembly work, though it uses a specific assembler/emulator (SPIM, a MIPS emulator) for its examples; more advanced assemblers such as MASM and Netwide Assembler have built-in support for structures that is comparable to languages such as C.

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

Certainly. Nested if:s are a common thing, though you generally don't want the nesting to go too deep for the sake of readability.

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

I have to agree with firstPerson, assuming that this is an option for you. MatLab is much better suited for what you're trying to do.

That having been said, here's the code I've been able to come up with so far:

#include <iostream>
#include <cstdlib>
#include <graphics.h>

using namespace std;

void FourierSquareWave(int *A, int amplitude, int harmonic);
void plotFourier(int *A, int n);


int main()
{
    int i, n, a;
    int *A;

    cout<<"Enter value of amplitude ";
    cin>>a;
    cout<<"Enter which harmonic you want to display ";
    cin>>n;

    A=new int[n+1];

    FourierSquareWave(A, a, n);

    for(i = 0; i <= n; i++)
    {
        cout<< A[i] << "\t";
    }
    cout << endl;

    plotFourier(A, n);

    delete A;
    return(0);
}


void FourierSquareWave(int *A, int amplitude, int harmonic)
{
    const double pi = 3.1415;

    A[0] = 0;

    for(int i = 2; i <= harmonic; i += 2)
    {
        A[i] = 0;
    }

    for(int j = 1; j <= harmonic; j += 4)
    {
        A[j] = (4 * amplitude) / (j * pi);
        A[j + 2] = -(4 * amplitude) / (j * pi);
    }
}

void plotFourier(int *A, int n)
{
    int gDriver = DETECT, gmode, errorcode;
    initgraph(&gDriver, &gmode, "");

    /* read result of initialization */
    errorcode = graphresult();

    if (errorcode != grOk)   /* an error occurred */
    {

        std::cout << "Graphics error: %s " << grapherrormsg(errorcode) << std::endl;
        std::cout << "Press any key to halt:";
        getch();
        exit(1); /* terminate with an error code */

    }

    initwindow(800, 600, "Fourier Square-Wave Approximation");

    for (int i = 0; …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

This article is probably the closest thing to what you are looking for that I've found. If you need further help, this page discusses the setup of the BGI library in Dev-C++.

If you decide to use Code::Blocks instead, the directions for setting up the libraries can be found here. The process is fairly simple and straightforward, though you need to include all of the libraries mentioned in the Dev-C++ article, not just GDI32. If you need further help with it, just ask me.

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

OK, just to clarify things: the <graphics.h> header provided with Dev-C++ is actually part of a package called WinBGIm, which is essentially a port of the older Borland Graphics Interface package to MinGW. There is a page explaining the functions in the library here. I'll try to see if I can get it to work with Code::Blocks as well (it ought to from what I've read) and try figuring out things so I can help you some more.

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

As a one-time service to the OP, here's the code (extracted by quoting the post) with the original indentation:

def egcd(a,b):
	u, u1 = 1, 0
	v, v1 = 0, 1
	while b:
		q = a // b
		u, u1 = u1, u - q * u1
		v, v1 = v1, v - q * v1
		a, b = b, a - q * b
	return u, v, a

def gcd(a,b):
	a,b=(b,a) if a<b else (a,b)
	while b:
		a,b=b,a%b
	return a

def modInverse(e,n):#will help me find the private key!
	return egcd(e,n)[0]%n

def totient(p,q):
	return (p-1)*(q-1)

#e=int(raw_input())
#ct=1520
#n=int(raw_input())
def encode(ct,n,e):
	ans=(ct**modInverse(e,n))%n
	return ans

def decode(n,e):
	ans=(encode(ct,n,e)**modInverse(e,n))%n
	return ans


e = 2667263
n = 118161264594682552213478835740008518638148382236836652791249450378665869820660982155245457006168819364532380817733
ct=4972012305304213038212726495362
#d=modInverse(e,n)
#print encode(ct,n,e)
#print decode(n,e)
print decode(n,e)

Please use [code] tags in the future for any code samples you post.

Having tried running the code, I would say that the issue is a simple one: you are trying to factor a very large number, a process that takes a very long time - on the order of years even with modern hardware - and the factoring simply isn't finishing in a reasonable amount of time. Given that this is the whole basis of this sort of encryption's security, this should not be surprising.

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

The MOVSB instruction shouldn't alter the source string, no. However, it does increment both the (E)SI and (E)DI registers so that they point to the next element of the strings.

Are you certain that you loaded the two registers correctly? What if anything does it do to the destination string?

And just for the record, which assembler are you using?

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

OK, so the code I posted a while back isn't working, now that I've tested it; however, I have a working function now for this purpose, though I have changed some details about. Before I post it, though, let me ask this: is the B array even necessary? All that you do with it in the original is clear it; the values aren't used anywhere except in the print-out. Why is it there?

Beyond that, I would recommend replacing Dev-C++ with a more current IDE such as Code::Blocks. Not only is Dev-C++ several years out of date - it hasn't been updated since 2005 - but also Code::Blocks fixes a number of problems with Dev-C++, such as the need to add the pause at the end of a console program. It also integrates support for wxWidgets, a very useful windowing and graphics library.

Finally you really ought to replace the older <iostream.h> and <stdlib.h> references with <iostream> and <cstdlib>, which are the newer standard versions of the headers. Note that you will need to add a 'using namespace std;' line as well if you do this.

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

Also, I would recommend separating the calculation out into a separate function, like this:

void FourierSquareWave(int& *A, int& *B, int n)
{
    int a, b, i;

    A[0]=0;
    
    for(i=0;i<=n;i++)
    {
        B[i]=0;
    }
    for(i=2;i<=n;i=i+2)
    {
        A[i]=0;
    }
    for(i=1;i<=n;i=i+4)
    {                  
                           
        A[i]=(4*a)/(i*pi);
        A[i+2]= -(4*a)/(i*pi);             
    }
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Graphics aren't a standard part of the C++ language; in order to help, we'd need to know what graphics library you were using, and which compiler and OS you were working in as well.

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

Odd... the code as given works fine on my system, in both the 2.6 and 3.0 interpreters. What version of Python are you using?

You might want to try using list() instead of [] when initializing meanBelow, as that's a little more explicit, but they both should work the same way in any version of the language I know of.

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

What have you tried so far? I would recommend writing out an algorithm for the conversion first, then try to work out what needs to be done to implement it in assembly language.

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

No, they probably wouldn't be; the x86 is notorious for it's relatively small register set. You can, however, use a memory variable for this purpose instead, either by a define-byte or by setting up an activation record on the stack.

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

Has your coursework covered writing your own functions, yet? Given the particular restrictions, and the usual solutions to them both, I would expect that this is meant as an exercise in function writing - more specifically, in writing recursive functions, as both exponentiation and converting a decimal string to an integer have simple recursive solutions.

As for the menu, the simple solution is to have an indefinite loop around the code which prints the menu and performs the calculations:

#include <stdio.h>
#include <conio.h>
#include <math.h>

void print_menu();
double exponentiate(double radix, int base);
int get_int();

int main(void)
{
    
    int selection = 0;
    double base = 1;
    double exponent = 1;
    int sum = 1;
    int repeat = 1;

    while (repeat)
    {
        print_menu();

        selection = get_int();

        switch(selection)
        {
            case 1:
                printf("Enter Base :");
                base = get_int();
                printf("Base = %d\n", base); 
                break; 
            case 2:
                printf("Enter Exponent :");
                exponent = get_int();
                printf("Exponent = %d\n", exponent); 
                break;
            case 3:
                printf("The Sum is %d\n", exponentiate(base,exponent));
                break;
            case 4:
                printf("Exiting Program\n");
                repeat = 0;
                break;
            default:
                printf("Invalid Choice\n");
                break;
        }
    }
    
    return 0;
}

void print_menu()
{    
    printf("\nPower Menu:\n");
    printf("  1. Change Base\n");
    printf("  2. Change Exponent\n");
    printf("  3. Display base raised to exponent\n");
    printf("  4. Exit Program\n"); 
    printf("Option:");
}

Writing exponentiate() should be trivial; you have most of it written already. Writing get_int() is rather more difficult, but you should try it yourself before getting more help. I will tell you that it is a recursive function (that is, one that calls itself), and …

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

I'm afraid you've misunderstood what Momerath was saying about using braces around if()/else statements, with results that are effectively meaningless. Rather than this:

{if} (lastYearProduction < 0)
            Console.WriteLine("Invalid");
        { else }
            Console.WriteLine("Enter This Year's Production");
            thisYearProduction = Convert.ToDouble(Console.ReadLine());

Momerath meant for you to do something more like this:

if (lastYearProduction < 0) {
            Console.WriteLine("Invalid");
        }
        else {
            Console.WriteLine("Enter This Year's Production");
            thisYearProduction = Convert.ToDouble(Console.ReadLine());
        }

To put it another way: an if() expression consists of three basic parts, the word 'if' followed by a conditional statement in parentheses; followed by either a single line of code or a block of code inside of curly braces; then an optional 'else' followed by the same sort of body as an if, but representing the code that should run if the condition is false. A BNF description of the syntax would be

<if-statement> ::= 'if' '(' <conditional> ')' '{' <body> '}' 'else' '{' <body> '}'

I don't know if this helps any, but it should clarify Momerath's earlier posting.

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

I think the main problem is that you're trying to apply the string operator .replace() on a dictionary. You need to get the individual keys and do a replace for each of them:

def wordReplace (wordText):
    """ Takes a list of strings and prints out the 
    equivalent text in Pirate-speak."""
    
    wordDict = { "Hello" : "Avast", "hello" : "avast", "excuse" : "arrr" , 
    "sir" : "matey" , "man" : "matey" ,"madam" : "ye proud beauty",
    "officer" : "foul blaggart" , "the" : " th'" , "my": "me" ,
    "your" : "yer" , "is": "be" , "are" : "be" , "restroom" : "head" , 
    "restaurant" : "galley" , "hotel" : "fleabag inn" , "treasure" :"booty",
    "drink" : "grog" , "flag" : "jack"}
    
    wordFile = (wordText) # wordFile and wordText are same thing
    for line in wordFile: #loop over characters in string wordText
        for key in wordDict.keys():
            line = line.replace(key, wordDict[key])
        print(line),
    return wordText # return

textFile = file("test.txt")


text = textFile.readlines()
wordReplace(text)

Applying this to the following file:

Hello, good sir. And what would
you and madam like to spend your 
hard earned treasure on this evening?

prints out:

Avast, good matey. And what would
you and ye proud beauty like to spend yer 
hard earned booty on thbe evening?

Not perfect by any means, but it does work this way.

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

Hold on here. Getting the mean (or average) is a fairly simple thing in and of itself:

import math

def mean(*alist):
    return sum(alist) / float(len(alist))

What you're doing doesn't seem to be aimed at just getting the mean of a list of values, however. What is item for, and just what should this function of yours return?

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

It also has similarities to another classic problem, the 'Readers and Writers problem', so you may want to look at that as well.

Furthermore, you may want to use the queue class rather than writing your own code. This is something I should have mentioned before, sorry.

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

Ah, I think I see what you need - this is related to what is called the 'Producers and Consumers' problem, a classic example of synchronization between different threads or processes. There are a number of articles around on how this works in Python, though they don't show exactly the solution you need.

In this case, I think the best solution is probably to set up a Condition variable that indicates when it is safe to write to the file, and have thread1 block when the condition is set. If you need to actually halt thread1 from main (as in stop it permanently), you may want to use another condition for that as well rather than simply killing the thread in the middle of it's actions.

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

For a single for() loop, the x86 instruction set has a special LOOP instruction.

mov ecx, 5
start_loop:
; the code here would be executed 5 times
loop start_loop

(Example taken from here.)

However, that has a number of serious drawbacks, with the most serious one being that it really isn't suited for nested loops (it uses CX as the counter, which if you have more than one loop means you have to somehow save the CX value before entering the inner loop and then restore it afterward).

A more solution is simply to use ordinary conditional branches. Here's a fairly typical example, which has a simple optimization of moving the test to the end of the loop (which avoids an unneeded unconditional branch on each pass):

; initialize the counter variable
    mov counter, 0
; jump to the conditional test
    jmp for_test

for_loop:
    ; add the body of the loop here
    
    ; increment the counter before going into the test
    inc counter
for_test:
    cmp counter, target
    jl for_loop

This is untested code, but should work.

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

I think I have the main showstopper problem worked out: while you set the DS segment prefix, you never set the SS segment prefix. Since the interrupts require a valid stack in order to work properly, the program crashed if this isn't set.

DOSCALL       EQU   21h
PRINTSTRING   EQU   09h
READSTRING    EQU   0Ah
EXIT_PROGRAM  EQU   4Ch

sseg segment para stack "stack"
    db 4096 dup(?)
sseg ends

dseg segment para public "data"
    msg db "Enter number: $"
    nline db 13, 10, "$"
    smaxlen db 50
    scurrlen db ?
    sdata db 50 dup(?) 
    number db "0000$"
    equal db "Equal!$"
    nequal db "Not equal!$"
dseg ends

cseg segment para public "code"
    assume cs:cseg, ds:dseg, ss:sseg

compare proc  
        cld  
        lea si, number
        lea di, sdata
        mov cx, 4
        repe cmpsb
        jnz not_equal
        mov dx, [offset equal]
        mov ah, PRINTSTRING
        int DOSCALL
        jmp exit_here
not_equal:
        mov dx, [offset nequal]
        mov ah, PRINTSTRING 
        int DOSCALL
exit_here:
        ret
compare endp

main proc
    mov ax, seg dseg
    mov ds, ax
    mov ax, seg sseg
    mov ss, ax
    
    
    mov ah, PRINTSTRING 
    mov dx, [offset msg]
    int DOSCALL
    mov ah, READSTRING
    mov dx, [offset smaxlen]
    int DOSCALL
    mov dx, [offset nline]
    mov ah, PRINTSTRING 
    int DOSCALL
       
    call compare   
    
exit:      
    mov ah, EXIT_PROGRAM
    int DOSCALL
main endp

cseg ends
end main

The comparison fails but at least it runs now.

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

Can you tell us exactly how it is misbehaving?

On a side note: while not directly connected to the problem at hand, I would recommend setting up equates for the DOS calls, as that will make the code a lot easier to read and correct:

DOSCALL       EQU   21h
PRINTSTRING   EQU   09h
READSTRING    EQU   0Ah

... and so on.

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

Answering the first question second, I would say that it depends, but generally speaking, you would want to keep the serial device open rather than repeatedly opening and closing it. Opening and closing may not have that high an overhead, but they do have some, just as with opening and closing files.

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

Well, first off, t.go = False isn't going to have the effect you're trying to achieve, as you can see if you run print(t.isAlive()) after that line - the answer you'll get is True, whereas if you used t.join() (which causes the main thread to wait until t is completed), it will give False. However, even if you explicitly waited for t to end, you can't re-start a thread that's gone to completion; you would need to instantiate a new thread1 object and set t to that, instead.

I'm curious as to the overall purpose of this, though. What are you actually trying to accomplish with this?

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

I tested this on my system (Ubuntu Linux 10.4, compiled with GCC 4.4.3) and it does print the child process' PID, but the Fibonacci print does fail even with the correct prototype and argument types. The problem appears to be in either computeFibonacci() or printFibonacci().

BTW, with the Unix C compiler (or the GCC compiler, either one), it should be possible to set the name of the compiled executable to something other than just 'a.out' using the '-o' option. For example:

cc forkfib.c -o forkfib

Alternately, you can just use 'mv' to rename the file.

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

As Scru said, if you're trying to pass the values as a GET, you need to URLencode the string containing the date. If you feel some overwhelming need to do this manually, the URL encoding for a forward slash is '%2F'. Thus, it would look like this:

http://www.host.com/script?%2F2008%2F05%2F05

Note the question mark (?) after the name of the script, rather than another slash. This indicates that the string following it should be treated as a GET parameter.

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

How are these two matrices being instantiated?

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

In NumPy, you don't use the standard list indexes. Instead, you need to pass it a list with the appropriate index values:

for i in range(3, n):
    temp[0, i] = 0.0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, you need to realize that you aren't converting a denary string to a string in another base; you are converting a binary integer into a string of numerals in the given base. This is important in understanding the rest of this.

The traditional approach, developed at MIT sometime in the early 1960s, is a rather simple recursive algorithm. For bases up to 10, it would be:

#include <string>
#include <iostream>
#include <sstream>
#include <exception>

class baseoverflowexception: public std::exception
{
  virtual const char* what() const throw()
  {
    return "My exception happened";
  }
} BaseOverflowException;


std::string bin2base(int value, int base) throw (baseoverflowexception)
{
    std::stringstream out;

    if (base > 10)
        throw (BaseOverflowException);
    else
    {
        if (value < base)
        {
            out << value;
            return out.str();
        }
        else
        {
            out << value % base;
            return bin2base(value / base, base) + out.str();
        }
    }
}

Allowing for an arbitrary base up to 36 complicates this a little, but not tremendously so. Solving this is left as an exercise. :P

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

I need to add one more thing: if you haven't been doing so already, I strongly recommend using the Bochs emulator while developing your system. Not only does it allow you to simulate various sorts of drives using ordinary image files, it also gives you much better turn-around time on testing, and has a built-in debugger. It will let you simulate the OS as if it were running live, before you try running it on actual hardware, and more conveniently than a virtualizer such as VMWare will.

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

If you look at the wiki a bit, you'll find this page on bootable CDs. However, the process they give does require an existing tool (mkisofs, or it's later replacement genisoimage) and basically allows the CD to emulate a floppy disk image. There's a second page that avoids the emulation, but uses GRUB for the loader.

Finally, there is this thread from their forum on how to write ISO images directly.

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

Probably the best place to look for information of this type is the OSDev Wiki and its corresponding forums. However, I will add that even there, most of the information on writing your own bootloader assumes floppy disks, as those were for a long time the easiest medium to come by and remain the easiest to work with for booting as the interface is completely standardized.

Note that writing your own bootloader, while informative, is neither necessary nor (in most cases) useful in writing the rest of an operating system; you may be better off using an existing bootloader such as GRUB to load your system, as that will save a great deal of effort and let you focus on the design of the system as a whole, rather than spending a lot of time on the the boot sequence.

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

You are declaring the function 'Iterator& operator++()' twice, once on line 41 and again on line 56. Since they have the same signature, there is no way for the compiler to disambiguate the two versions (which were probably not intentional anyway), so it gives an error.

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

Ah, you're right, Nezachem. Fortunately, I found my own old shell program. and was reminded that there is a simple solution:

char whitespace[] = "\n\t ";

    // ...
    argv[n++] = strtok (temp, whitespace);

This causes tabs and newlines to be removed as well as spaces.

Speaking of my own experiences, again: you may find it helpful to factor the code that parses the command line and the code that executes it into separate functions. This makes testing easier, as there are fewer places where they can interact with each other.

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

As for the original problem, I've tested the code and found a number of issues with it. First off, you did not #include either <unistd.h> or <sys/wait.h>, which contain the headers for some of the functions you are using. Also, the code as written requires that you compile with the -std=c99 option - not a problem in itsle,f but something that could cause it to fail if someone else tried to compile it without noticing it. I would finally add that you may want to make sure that you're compiling with -Wall set, just to make sure that you catch any minor problems in the syntax.

I also found that it doesn't not, in fact, run /bin/echo; it only appears to, because you are echoing the command line options on separate lines. If you change the test printf()s to the following it should be clearer:

// This is merely to print out what got splitted for the tokens////////////////////////////
    
    for (int b=0; argv[b] != NULL; b++)
    {
        printf ("%s\t", argv[b]); 
    }
    printf("\n");

I would also recommend changing the test on fork() so that it checks for an error condition:

int child = fork();
    if (child > 0)
    {
        waitpid(-1, &status, 0);
    }
    else if (child == 0)
    {
        if (execve(argv[0], argv, 0) == -1) /* execute command */
            printf(": %s\n", strerror(errno));
    }
    else
    {
        printf(": %s\n", strerror(errno));
    }

You'll note that this version does run /bin/echo properly, if given a suitable argument (it fails if no args are …

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

Ancient Dragon: The reason why 'ls' alone won't work is because with a simplified shell such as this one (or the one which I'd written for the same sort of project), it doesn't support a default executable path, so it needs a fully qualified path for any program it runs (the path is part of the argument passed to execve()). Since ls is a separate program, rather than a part of the shell, it has to have the full path, or else the OP would need to add support for a default path (reasonably simple, but brittle, as there are several paths needed to find the commonly used utilities) or a path environment variable which can be set when the shell starts (fairly involved for what is usually a one-week project in a sophomore-to-junior level Systems Programming course).

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

There are a few different options, actually. Generally, what you download from the Ubuntu website is an ISO which you would then burn to a CD. Once you did that, you could either run Ubuntu from the CD, or install it permanently on the system.

If you install it, it can overwrite Windows, replacing it completely. If you don't want to do that, you can try re-partitioning the drive so that you can set up a separate Linux partition which will let you dual boot; the problem is that there's a risk of damaging the Windows partition doing that, so if you wanted to try that you should make sure to back everything up before trying, and be prepared to re-install Windows if you need to.

If you have a free drive bay, and can afford a new drive, you might want to get a separate drive to install into the system, and install Linux on that. That's probably the best solution if you can do it.

There are also ways to install Ubuntu inside of Windows, but I can't give too many details about that offhand.

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

The problem lies in the while() loop in inventoryValue(); the index variable, i, is never getting incremented, so it loops indefinitely on the zeroth element of the array. I would recommend changing it to a for() loop to make the intent clearer, in any case:

int inventoryValue(carType cars[], int currentCarCounter)
{
    int sum=0;
    for(int i = 0; i<currentCarCounter; i++)
    {
        sum+=cars[i].cost*cars[i].numberOnHand;
    }
    return sum;
}