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

While I don't know much about shellcoding in general, I did find this FAQ Illuminating fnord. Questions 6, 7 and 10 seem particularly relevant to your problems. After the FAQ portion, he includes a tutorial that has it's own version of the 'Hello' program, which seems to be written to avoid the NULL byte problem.

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

There is also an Objective-C front-end for GCC that is available on any platform that support GCC, so it is certainly available for Windows.

The interesting thing is, Objective-C actually predates C++ by about a year, at least as a publicly available language ('C with Classes' was in development as early as 1979, but wasn't released as C++ until 1983). Both languages began as preprocessors on C, with C++ being derived from Simula, and Objective-C from Smalltalk. Indeed, it is safe to say that Objective-C began as little more than embedded Smalltalk statements in a C language context.

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

You mention that it is running under Linux, but you don't mention for what processor. I'll assume that it is meant to be 32-bit x86 code for now, but if it is for, say, a Raspberry Pi (which uses an ARM chip), or even just the AMD64 mode of an x86 processor, then my comments may not be correct.

If I am disassembling this code correctly, it comes out to the following (hex on the left, AT&T mnemonics in the middle, Intel mnemonics on the right):

ba : 0e 00 00 00   mov.l 0x0e, %edx       :  MOV EDX, 0Eh
b9 : 04 90 04 08   mov.l 0x08049004, %ecx :  MOV ECX, 08049004h
bb : 01 00 00 00   mov.l 0x01, %ebx       :  MOV EBX, 01h
b8 : 04 00 00 00   mov.l 0x04, %eax       :  MOV EAX, 04h
cd : 80            int  0x80              :  INT 80h
bb : 00 00 00 00   mov.l 0x00, %ebx       :  MOV EBX, 0
b8 : 01 00 00 00   mov.l 0x01, %eax       :  MOV EAX, 1          
cd : 80            int  0x80              :  INT 80h

It looks like all this is doing is passing a string to the screen print syscall, followed by the system exit syscall. Nothing exactly fancy, except... where is the char pointer in ECX actually pointing? The memory location it is referencing is hardcoded, but you don't actually have anything at that location, at least not in the current process. That by itself is likely to cause a segfault, even if the code were in an executable page.

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

As Rubberman alluded to, on modern processors, memory is not unitary. Most CPUs today break memory up into pages - blocks that can be manipulated my the hardware memory mangaement system - and mark the individual pages as to whether their contents can be modifed or not, and whether they can be executed or not. Generally speaking, any variables are going to be in memory marked as non-executable, and attempting to execute code within them will indeed cause a memory protection violation. The same is true of constants, in which case the page is also marked as non-writeable.

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

No, Rubberman has a point (pun intended). While the client-programmer cannot use pointers in Java itself, the language does use references, and most if not all of the various implementations do use pointers internally to implement references. The Oracle reference implementation (which is closed-source, but known to be written in C last I checked) certainly does. The Java language shields Java programmers from this, and it would in principle be possible to write a Java interpreter without pointers, but as a rule references are implemented using pointers.

As for security, well, as with garbage collection, you are trading off thousands of possible points of failure - the individual references - for a single large point of failure - the underlying implementation. In a language which does not have 'safe' references, there is a risk of error every time a pointer is altered. In a language like Java, that risk is taken in only a few key places, but an error in any one of those could cascade throughout every program written with the flawed implementation. The advantage of Java's approach is that the debugging is done once for all Java programs, rather than by the individual client-programmers. The disadvantage is that a mistake is more costly overall. It is a tradeoff, and for most application programmers, a good one - it allows them to focus on the stucture of the program rather than the needs of the memory system. I have my issues with Java - it carries a lot …

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

The code as given won't work; the indentation is all off. Here is the program with what I presume is the correct indentation:`

import getopt
import sys
import hmac
import hashlib
import base64
import urllib


def formattedCmd(api, cmd):
    s = 'apiKey=' + api + '&' + cmd
    return s


def encypt(string, key):
    h = hmac.new(key, string, hashlib.sha1)
    #  print '\n' + h.digest()
    return base64.b64encode(h.digest())


def formattedUrl(baseUrl, api, cmd, signature):
    url = baseUrl + '?' + formattedCmd(api, cmd) + '&' + urllib.urlencode({'signature': signature})
    return url


def main():
    print 'ffffffffffffffffffffffffff'
    try:
        print getopt.getopt(sys.argv[1:], 'u:a:s:', ['help', 'output='])
        opts, args = getopt.getopt(sys.argv[1:], 'u:a:s:', ['help', 'output='])
        print opts, args,'print'
    except getopt.GetoptError, err:
        print str(err)
        sys.exit(2)

    baseUrl = 'http://10.176.14.26:8080/client/api'

    cmd = 'command=listTemplates'   
    temf= 'templatefilter=featured'
    api = 'Qo9Qwfatwz9ARB328Btn9PftzL2Cf5LOWd8OFyJmiM513tpTIm-zKxJoWkWqf353Df397xcLdKXGk8_JO8nM3Q'
    secret = '-kgkBuBUrGFeIC4gUvngSK_3Ypmi7fuF8XdVXIusnyyiEP2YUcG3FnPUGJGy3rp3Bw5ZNnqgS-9tIfyV1QnK1g'

    for o, a in opts:
        if o == '-u':
            cmd = a
        elif o == '-a':
            api = a
        elif o == '-s':
            secret = a
        else:
            assert False, 'unhandled option'

    newCmd = formattedCmd(api, cmd).lower()
    signature = encypt(newCmd, secret)
    url = formattedUrl(baseUrl, api, cmd, signature)

    print '\n' + url

if __name__ == '__main__':
    main()

This code runs, but doesn't do anything notable other than generate and print a URL.

Can you give us the exact error and the traceback on the code you were trying to run when you got the problem you mentioned?

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

It goes without saying that some sort of software is needed for programming; at minimum, you need an editor and a program trnaslator of some type. As Matt1998x points out, there is some software for programming installed already on just about any computer you might have. Windows includes Notepad and Visual Basic for Scripting, while MacOS and Linux often have several different editors and interpreters pre-installed.

The real question is, what sort of programming do you want to do? Most programming tools are available for free, or at least have a free edition for newcomers to work with. You simply have to choose which of them you want to try learning first.

My recommendation is to start with Python, and a nice Pythonic Integrated Development Environment such as Eric or PyCharm (though PyCharm is only free for the first 30 days, after that you would have to buy it). Python is one of the easier languages to start with, for most people anyway, and is fairly powerful. That having been said, not everyone prefers the same languages, so you will want to try out several different ones over time to figure out which you are most comfortable with.

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

Assuming that you are running the Javascript in a browser rather than as a stand-alone program, then the answer is 'no'. The example code above reads a set of arguments from the shell, something which Javascript cannot do - the closest equivalent would be reading data from the web page's POST or GET.

Mind you, there is no reason to convert this to Javascript, as it only reads from the command line and echos back the options. It is a more or less pointless program, or more likely, a fragment of a program taken out of context.

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

Consider all the things that go into representing a given locale. Here are some of the basic ones:
* A full description of the locale itself, to be used the first time the player enters it. At the player's request, this should be repeated, as well.
* An abridged description, for repeated entries.
* A description of each manipulable item in the area.
* A set of links or pointers to other areas, one for each of the cardinal points (north, west, south, east), as well as up and down. This includes handling the cases where there is no path in a given direction.

Number three brings up another issue which hasn't come up yet: representing the items that player can pick up, drop, change, etc. that are in the rooms. That will also require a class, possibly more than one.

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

I know that you are only a beginner and may not be comfortable with such things, but I would recommend that you a) come up with a class that holds the area descriptions, rather than hard-coding each one in, and b) storing the data for each of the areas in a file or files, which the program could load to memory as needed. This would avoid having a lot of long if/else if/else combinations like the one you have here.

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

Let's not drag up old, dead threads, shall we? Please, check the dates on the threads before you post.

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

Seriously? That can't be right - the project as described can't be done without some sort of data structures. It simply is isn't realistic to do it that way - you would need to hard-code each item as a separate variable, then hardcode its price as another set of separate variables, its barcode as yet another set, and so on. No programmer in their right mind would do it like that.

Walk out of this class; your instructor doesn't know how to program, and you'll be better off finding another instructor.

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

What, you mean the code I posted earlier? That was just an example. You'll need to write your own code for your project.

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

Could you please post the error message and the traceback?

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

Actually, the way you accept the input should be seperate from the way you add the user record, if only for modularity's sake. You want to break adding a user record down into five steps:
* input - get the username and password.
* encryption - converting the password into a different form using a hashing function.
* qualification - checking to see if there is already a user with the same name. If there is, disallow the new user account.
* insertion - adding the user account to the binary tree.
* storage - saving the new user record into the password file.

Each of these is itself a seperate operation, and should be at least one seperate function each.

We'll set aside input for now, as that is going to be operating-system dependent (assuming you are going to mask out the characters as they are being typed, at least). Realistically, you want to go at these in reverse order anyway, starting with the code to insert a record into the password file and working back to the data entry. So, you will want to start with by figuring out how you want to store the passwords in the password file.

There are a few different ways of doing this, each with their own advantages and disadvantages. The simplest solution is to just have a text file containing the usernames and password as a line of text separated by a marker such as a …

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

Odd, I have that code running flawlessly on my system. What version of Python are you using?

Can you check the code again, to make sure you didn't drop anything? I am specifically thinking that you might not have included the first line (hit = None), which is important in that it resets hit after the bullet is removed from the list.

Also, try changing bullets[index] to bullets[hit]. It may be that index is going out of scope, though I would expect that it would give a different error were that the case.

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

The simplest solution here is just to remove said bullet from the list bullets.

    hit = None

    for index, bullet in enumerate(bullets):
        crect = pygame.Rect(bullet[0] - 3, bullet[1] - 3,3*2,3*2)
        shoot = pygame.draw.circle(screen,(255,255,255),(crect.center),3)
        if crect.colliderect(Boss):
            print('hit')
            hit = index

    if hit is not None:
        del bullets[index]
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As for your question about heap memory, this post should help clarify how memory is allocated and used. It is written from a C/C++ perspective, however, so there is more to be added about it.

The first thing you need to know is that objects in C# are always in dynamically allocated memory. This makes it possible to add or remove objects freely, without having to worry about the space involved. But what happens when you run out of memory? Well, I'm going to get to that in a bit, but there are a few things to explain before I get to that.

The next thing is that there is a difference between a variable and an object. In C# (and many modern languages), a variable of an object type is not an object itself, but rather a reference to an object. This is in contrast to a variable of one of the primitive types (int, char, float, etc.), or of a struct type, where the value of the variable is the actual value being worked on. The value of a object type variable is a reference to where the object is in dynamic memory. A variable can itself be part of an object, or be part of a class; the former are called instance variables, while the latter are static variables or class variables. When you invoke the constructor of a class, you are actually allocating memory for the new object, after which the c'tor itself is …

ddanbe commented: Good explanation. +14
silvercats commented: Exactly the answers I am looking for. +2
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Simple: use the function localtime() instead of gmtime().

aVar++ commented: Worked great, thanks :) +2
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, well, I wouldn't put a lot of weight on the specific inventory items; in fact, if you do this correctly, they shouldn't even come up in the program itself. Why not? Because you'll almost certainly want to store them in a data file of some sort so that they persist even between runs of the program, or better still, in an actual database of some kind. Even if that proves too much to deal with, you can still have them in a separate file from the body of the program, which could be imported into the code proper at run time. The looser you couple the data and the code - that is to say, the more you can seperate the actual data from the data structures and the code that work on it - the better off you'll be.

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

First off, The reason that it is showing the title bar of the window is because you asked for the title bar of the window. If you are opening a MS Word window, and haven't saved the document yet, then it will show the default document name - which in this case is 'Document 4' - followed by the name of the program.

As for logging the keystrokes, this would depend on a) what version of Python you are using, and b) whether you want to use the standard Logging API or not. The Logging API is pretty poweful, but not, I suspect, quite what you want; it is aimed mainly at event logging for debugging and troubleshooting programs. In this case, a simpler approach is probably called for, in which case just using the print command (or print function, in Python 3.x) should work.

for Python 2.x, you would write,

print "\n\nWindow: [%s]" % self.windowname >> f

while in Python 3.x (or Python 2.5 and later with the module import directive from __future__ import print_function), it would be

print("\n\nWindow: [{0}]".format(self.windowname), file = f) 

This all is fairly simple, I would think; I suspect that there's more to your question than is evident.

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

Can you gives us at least some idea of what you need? Aside from code, that is - no one here is going to give you a working program, gratis, without you providing the majority of the work. DaniWeb is not a homework-completion service, and if that is what you are looking for, I suggest going somewhere else.

What I can do, for now, in the absence of more information, is point out several problems with the code as given:
* The code is completely lacking in indentation. While different indent styles are acceptable, so long as they are used consistently, a lack of indentation is never acceptable in C++.
* You dropped the semi-colon after the using namespace std directive, which is a syntax error.
* You used parentheses in declaring arrays, where you should have used square brackets.
* You declared the main() function as void, which is unequivocally wrong in C++. I don't care if the compiler accepts it, it violates the C++ standard and should never be used. Always declare main() as type int, and return a value at the end (usually zero, which indicates a successful run of the program to the shell).
* You used the older style of header names. In C++ after 1998, all C++ standard library headers drop the '.h' extension, and the libraries inherited from C should all begin with the letter 'c'. For example, <iostream.h> is now just <iostream>, while <stdlib.h> is …

Stuugie commented: He/she's going to find another forum to do all his/her work from him/her +2
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

OK, sounds fine. What problems are you having with it? Can you show us what you've done so far, if anything?

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

Hmmn, OK. Let's start with the data structure for the items. Has your instructor covered classes yet? If so, I would recommend a class which would have the name, price and stock count as the instance variables, and the have a dictionary using the barcode as the key and the Item objects as the value.

If you haven't covered classes yet, you can still do the same sort of thing with nested dictionaries. You can have each item represented by a dictionary, and then use that dictionary as the value for another dictionary with the barcode as it's key. You'd have one inner dictionary for each item. You can then wrap that up in a functions to create the dictionaries for you, and handle setting and getting the values:

def makeitem(name, price, stock_level):
    return {"name": name, "price": price, "stock level": stock_level};

def subtractFromStock(inventory, barcode, amount):
    if barcode in inventory.keys():
        item = inventory[barcode]
        item["stock level"] -= amount
        if item["stock level"] < 0:
            item["stock level"] = 0
        return True     # there was an item to update
    return False        # there was no match on the barcode

.. and so on.

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

A few questions:
* Is this a Point of Sale system for an actual shop, or a school project?
* When you say that you need to input a barcode, do you mean you would type in an SKU number by hand, or do you actually need to scan barcodes? If it really is reading a scanner, what kind of scanner, and what operating system are you using? Do you have a driver for the scanner which comes with an accessible API?
* Do you intend for this to be a GUI application, or a console application? If the former, are you going to use TkInter (the one that comes with Python, which is good enough for something like this but not necessarily the best) or a 3rd party toolkit such as PyQt4 or wxPython?
* When you say that you don't know how to make the loop, do you mean you aren't familiar with the syntax of while: loops, or that you aren't sure how to determine the end condition?
* When you say you were looking to use a Dictionary, do you mean for the inventory items?
* For a practical system, a database of some sort is pretty much a necessity. Do you know what sort of database you intend to use, and how to connect to it using Python?

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

You presumably would use get_rect(), the same as with the other sprites.

I'm in a bit of a quandary about how to help you, as I've more or less completely re-written the program for my own amusement, and I'm not sure if what I've done would apply to your code in any meaningful way. My code really does depned on using classes, and specifically, inheritance. My current version has a base class, GameObject, that itself is derived from pygame.DirtySprite (which in turn inherits from pygame.Sprite), and is the parent class of the Player, Enemy, and Bullet classes. I relies on the pygame.sprite.RenderUpdates collection class to draw the sprites, and uses the collision detection in the parent pygame.Sprite class for determining of the bullets hit their target. Unrolling all this to procedural code is not a viable option.

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

You might want to look into using the PyGame Sprite class for the bullets, as it includes built-in colission detection. For that matter the regular Rect class has several collision detection methods which could be of use, though they aren't as fine-grained as the Sprite methods are.

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

Actually, the correct type for 'wide' characters is wchar_t, as of the 1998 C++ standard. The C++ 11 standard expands on this, but it still has wchar_t for most Unicode and other non-AsSCII encodings.

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

Captain119: Actually, in C++ you can overload the names of functions; the issue is that you have to give each of the different functions sharing their name a different signature. The real issue is that the OP made a mistake in the second function's declaration; it should be something like this:

void bubblesort( char ch[], int size); 

This passes a character array to the function, which is what it is supposed to be sorting.

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

I know it doesn't address the problem you are having (directly, anyway), but I would recommend creating an auxiliary class GradeBookEntry, which would hold the actual details of the student records, rather than having a series of parallel arrays which need to be synchronized manually.

class GradeBookEntry {

    final static int EXAMS = 4;
    String name;
    double[] scores;
    char letterGrade;

    public GradeBookEntry(String student) {
        name = student;
        scores = new double[EXAMS];
    }

    public void setName(int studentNumber, String student) 
    { 
        name = student; 
    } 

    public void setScores(double[] scores) 
    { 
            scores = copyArray(scores); 
    } 

    public static double[] copyArray(double[] from) 
    { 

        double[] to = new double[from.length]; 
        for (int i = 0; i <from.length; i++) 
            to[i]=from[i]; 
        return to; 
    } 

    public String getName()  
    { 
        return name; 
    } 

    public double getAverage()  
    { 
        double total = 0.0; 
        double average = 0.0;  

        for (int row = 0; row < EXAMS; row++) {
            total += scores[row]; 
        }
        average = total / EXAMS; 

        return average;
    } 

    public static void getLetterGrade(int i)  
    { 
        double grade; 
        double average = 0; 
        if (average > 90) 
            grade = 'A'; 
        else if (average > 80) 
            grade = 'B'; 
        else if (average > 70) 
            grade = 'C'; 
        else if (average > 60) 
            grade = 'D'; 
        else grade = 'F'; 
    }  
}

You can see how unloading the details of the GardeBook into GradeBookEntry simplifies much of the code; the GradeBook class itself becomes just:

public class GradeBook {
    finalstatic int STUDENTS = 5;

    public GradeBook() {
        GradeBookEntry[] students = new GradeBookEntry[STUDENTS];
    }

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

I'll assume from a previous related thread that you are using Turbo C++, which is unfortunate but I know there's nothing to be done about it (except protest to the government University Standards board, which I understand is probably futile). Therefore I'll limit my comments about the headers to a reminder that you don't actually need several of the ones you have included.

In fact, I am dismayed at how little you actually followed my earlier advice, in general. I do see a lot of improvements, but the code is still pretty much a disaster. However, if the bhpeqns() equations function now works, then that is what is most important, I suppose.

As for the ktt_optimize() function, what exactly is it doing, and where is it going wrong?

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

Unfortunately, I don't have any site to try telnetting into, so I can't reproduce your problem. If I knew where you were trying to get to (the address you are using is a local one, not a global Intenet address), I could try telnetting into the same site, but unfortunately that probably isn't possible to do from outside of your local network.

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

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 a grave breach of academic ethics on your part, and actually doing so would be an even bigger breach on …

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

Basically, what it comes down to is that you have both of the return clauses inside of an if/else statement, and the compiler does not have the ability to determine for certain that at least one of the options is guaranteed to run.

The solution in this case is simple: get rid of the else clause, and move the second return clause to the end, after the last of the for loops exits.

    public boolean isFine(){
        for( int i = 0; i < myarray.length; i++ ){
            for(int j = 0; j < myarray[i].length; j++ ){
                if( myarray[i][j] == myEnumeration.FRIDAY ){
                    return false;
                }
            }//end of column array
        }//end of row array 
        return true;
    }//end of isFine()

This is actually necessary anyway; with the original version, the function would have exited on the first pass of the inner loop one way or the other, when what you presumably wanted was for it to return true if no cases proved to equal myEnumeration.FRIDAY.

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

In the first set of declarations, the variables are local to main(); they only exist inside main(), and only for the time that the program is running. You can print the variables from main() just as you have them now.

In the second set of declarations, the variables are instance variables; they would exist within the scope of an object declared as that type, and each object would have their own versions of the variables. They would not be visible in main() as written, as main() is a static function and can only see variables that are local to it, or have been declared static as part of the class. To access the instance variables, you would need to instantiate a variable of the class, and access them from that object:

public class myclass{
    boolean variable1 = false;
    boolean variable2 = false;

    public static void main( String args[] ){
        myclass myobject = new myclass();
        System.out.print(myobject.variable1 + " and " + myobject.variable2);
    }
}

(Note the way I indented the lines inside of main(), BTW; as a rule, you want to indent every level of nesting, and dedent when the nested scope ends.)

To declare the variables as class variables, you would need to use the keyword static in their declarations, just as you do with class methods.

    public class myclass{
        static boolean variable1 = false;
        static boolean variable2 = false;

        public static void main( String args[] ){
            System.out.print(myclass.variable1 + " and " + myclass.variable2);
        }
    } …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

We generally prefer to conduct our answers in public, and in any case, no one here is likely to publish their e-mail address on a public forum. Thank you, but I get enough spam as it is, and while I know you wish only to make things easier, there are plenty of vultures around the net who will grab any e-mail address they stumble upon. Perhaps I would send it to you by PM, not on the site itself, certainly.

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

Hmmn, here's an old trick that may be appropriate here: drop the first letter of the words you are matching against, such that you are waiting for 'ogin:' and 'assword:'. The reason this may work is because the first letters may or may not be capitalized; if you assume capitalization when there is none, or vice versa, you may end up waiting indefinitely.

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

COuld you please give us some more information about the way the program is failing, e.g., error messages, the stack trace, and similar information? Also, what version of Python are you using? The code you posted is for Python 2.x; if you are running Python 3.x, it would fail, because several things have been changed or removed since the older version.

Also, are you certain that the host you areconnecting to has a Telnet service running? Most desktop or workstation systems have Telnet disabled by default.

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

Yes. C++ is partly based on C, but it is a completely different language.

As for the Sleep() function, I am asuming that th text is referring to the Windows API function of that name. While the details of how it works are proprietary to Microsoft, the way you use it is simple: you call it with an int argument indicate the minimum number of milliseconds the program should pause. For example,

Sleep(33);

will cause the program to stop running for at least 33 milliseconds (I say 'at least' because the Windows scheduler may not pass control to the program immediately, so the delay may be longer depending on how heavily loaded the system is). That happens to be 1/30th of a second, which is about how fast you would want a video game's frame rate to be to ensure smooth animation. With a game like the one you are describing, you would probably wait something more like 250 milliseconds (1/4 of a second).

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

Not such that you could use them by that name, no. In C, all variables must be declared at compile time. You can allocate memory at runtime, using malloc(), but you would still need a declared pointer to refer to such memory.

Could you give more detalis as to why you want to do this? I suspect that what you really want is going to be something along the lines of a dynamically allocated structure such as a linked list.

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

Actually, the problem statement very clearly says to use C and assembly, not C++. I think you are confused about what language you are supposed to be using.

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

tingwong: You say it doesn't work on smaller files? How small are we talking? Keep in mind that with Huffman encoding, there is a minimum size overhead in the form of the encoding table. Adaptive Huffman encoding doesn't have this limitation, but isn't as efficient overall (because you may be changing the encoding of a given character over time).

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

BTW, where is the BinaryNode generic class defined? This seems to be a crucial omission.

I think that the crux of the matter is that you have misunderstood what theString class's getBytes() method does. What it returns is an array of bytes containing the raw representation of the chracters themselves in the default chracter set, which is UTF-8. This means that when you write out the String "1111000101", it actually is writing two bytes per character of each digit.

What you actually want is something that takes the encoded String and converts it to the bits in single byte or a pair of bytes. The following should do the trick:

byte[] packEncodedChars(String[] bitStrings) {
    ArrayList<Byte> bits = new ArrayList<Byte>();
    byte target;
    int bitCount = 0;

    for (String s : bitStrings) {
        for (char bit : s.toCharArray()) {
            if (bit.equals("1") {
                target |= 1 << bitCount;
            }
            bitCount++;
            if (bitCount >= 8) {
                bitCount = 0;
                bits.append(target);
                target = 0;
            }
        }
    }
    byte[] bitstring = new byte[bits.Length()];

    for (int i = 0; i < bits.Length(); i++) {
        bitstring[i] = bits.get(i);
    }

    return bitstring;
}
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Hmmn. Can you go into more detail about what you are trying to do? It is very unusual to need (or even want) pixel per pixel access to the a bitmap, and the particualr goal is important. Are you trying to alter the image as it is loaded into video memory, or the file, and if the former, do you need to save it back to the file again later? Put another way, is this a matter of editing the file, or of modifying the image as it is shown, or both?

I'll assume that this is under Windows; I know you don't use Macs, and under Linux you would use libbmp, as previously mentioned.

If you need pixel access to an image being displayed, then it doesn't matter what sort of file it came from; you would use GetDIBits() and SetDIBits() if you are working with the GDI library directly, or else you could use the Bitmap class of the GDI+ class library, which has the methods GetPixel() and SetPixel() for this purpose. (I am assuming you want to avoid C++/CLI.)

Even with Windows, libbmp is an option, if you are using MinGW and GCC. That may be the easier solution, as the library is platform-independent and avoids a lot of the details of Windows image handling that you would otherwise be facing. Note that it only works with uncompressed files, AFAIK. The …

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

If it helps any, here is what I've come up with so far in implementing your class:

bitmap.h

#ifndef BITMAP_H
#define BITMAP_H 1

#include <exception>
#include <iostream>
#include <iomanip>
#include <fstream>


const unsigned short BMP_MAGIC = 0x4D42;

class bmp_format_exception : public std::exception
{
public:
    virtual const char* what() const throw()
    {
        return "Bitmap format not valid.";
    }
};


class file_write_exception : public std::exception
{
public:
    virtual const char* what() const throw()
    {
        return "Unable to write to file.";
    }
};


class BitmapImage
{
    struct
    {
        unsigned short headerField;
        unsigned int fileSize;
        unsigned short reserved1;
        unsigned short reserved2;
        unsigned int startAddress;
    } BitmapFileHeader;
    struct
    {
        //probably a union of the different possible header structs???
    } DIBHeader;
    struct
    {

    } ExtraBitMasks;
    struct
    {

    } ColourTable;
    unsigned int gap1,gap2;
    struct
    {

    } PixelArray;
    struct
    {

    } ICCColourProfile;
public:

    friend std::istream& operator>>(std::istream& is, BitmapImage& bmp)  throw(bmp_format_exception);
    friend std::ostream& operator<<(std::ostream& os, BitmapImage& bmp)  throw(file_write_exception);
    void printHeaders();    // used mainly for debugging purposes
    int width();
    int height();
    unsigned int &operator()(int x, int y);//pixel access
    unsigned int alphaMask();
    unsigned int redMask();
    unsigned int greenMask();
    unsigned int blueMask();
    unsigned int bpp();
};

std::istream& operator>>(std::istream& is, BitmapImage& bmp)  throw(bmp_format_exception);
std::ostream& operator<<(std::ostream& os, BitmapImage& bmp)  throw(file_write_exception);
#endif

bitmap.cpp

#include <iostream>
#include <iomanip>
#include "bitmap.h"

unsigned short char2short(unsigned char upper, unsigned  char lower);
unsigned int char2word(unsigned char upper, unsigned char middle, unsigned char lower, unsigned char lowest);

inline unsigned short char2short(unsigned char upper, unsigned char lower)
{
    return (static_cast<unsigned short>(lower) << 8) | static_cast<unsigned short>(upper);
}


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

Oops, I forgot to say, while you certainly can use the C-style file functions, I don't think there is any reason why you can't use the C++ iostreams as well. While the C++ I/O may require some additional effort to get it to do what you want, it actually is more flexible than the C functions are. Either way, just remember to open the file as binary rather than the default text mode.

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

veducator: Please use the modern C++ headers in the future. The C++98 standard removed the .h extensions from all standard headers, such that <iostream.h> (for example) is now just <iostream>. Similarly, the standard headers for the C standard libraries to be prepended with a c, for example, <stdio.h> is now <cstdio>. Do not use the old style headers anymore, and do not use any compilers that don't support the new headers. The standard is now 15 years old, and there is no reason to use anything older than that.

On a related note, the <conio.h> header isn't standard, it is strictly a DOS library and has long since been phased out. DO NOT USE IT, ever, for any purposes at all.

If you're in a course that requires the use of older compilers (Turbo C++ being the usual suspect), leave the course, as you are being taught useless information. I know that there are several countries where the national education system has standardized on Turbo C++, but the only way it will get modernized is if the students get involved and demand a better education. The students of India and Pakistan are getting a raw deal enough as it is, with a system more interested in test scores and rote 'learning' than actual teaching; they don't need archaic systems rammed down their throats.

(Not that C++ is a good choice for a first language, anyway, but that's another debate entirely.)

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

There really isn't any formal definition of the format, unfortunately, at least not one that Microsoft has seen fit to share with anyone. Their own recommendation is to always use their library functions to manipulate BMPs, and any other approach is likely to be incomplete, as they deliberately keep the full details from other programmers - and a full implementation might be in violation of one or more patents, either Microsoft's own or ones they have licensed. Who knows? MS isn't telling...

My recommendation is to look into the code for libbmp. It's probably the best resource available on the format outside of Microsoft themselves.

I'm guessing you've seen these links already, but in case you haven't, here are some resources to follow up on:

The libbmp repository (probably the closest thing to a complete 3rd party implementation):
https://code.google.com/p/libbmp/

Official MS documentation:
http://msdn.microsoft.com/en-us/library/dd183391.aspx
http://msdn.microsoft.com/en-us/library/dd183386.aspx
http://msdn.microsoft.com/en-us/library/dd183383.aspx

DDJ article on the format:
http://www.drdobbs.com/architecture-and-design/the-bmp-file-format-part-1/184409517
http://www.drdobbs.com/the-bmp-file-format-part-2/184409533?pgno=5

Other links:
http://www.fileformat.info/format/bmp/egff.htm
http://www.faqs.org/faqs/graphics/fileformats-faq/part3/section-18.html

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

While I doubt that HappyGeek's answer is quite what you were looking for, the truth is that we can't give much more of an answer without a lot more information from you. What, if anything, do you already know? WHat would you like to learn about? Computer programming is a very broad topic, and one which tends to be very ideosyncratic to the person learning it; you really would need to narrow down the question.

If you really want to start learning about computer programming in general, and don't mind doing it the hard way, my best recommendation is to read Structure and Interpretation of Computer Programs by Abelson and Sussman, and view the view the lecture videos that go with it. It is a very intensive course, and rather unusual, but it really does give you an overview of computer programming, from one point of view.

A rather simpler approach for most people would be to start learning the language Python. Most people find it a very simple language to learn, and it lets you cover a lot of ground with a minimum of intellectual clutter. There are several good books and tutorials on Python around; I'm sure you'll get plenty of recommendations, with Think Python being a good one to start with IMO.

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

I've tested the following version of your class, and it cmpiles and links flawlessly under Visual Studio Express 2010:

class personType
{
public:
    void print();
    std::string firstname;
    std::string lastname;
};

This may, however, be in part because you don't actually use the c'tor in question explicitly (or the print() method for that matter).

BTW, who the hell tought you to use goto for writing loops? One piece of advice? DON'T. EVER. DO. THAT.

Seriously, goto presents grave problems for writing understandable code, and unless you are in a situation where there is absolutely no alternative, it should be avoided at all costs. The entire lop could be far more comprehensibly written as the following:

    bool exit = false;

    while (!exit)
    {
        cout<<"Please input a corresponding number to perform the listed action to the address book: 0 to exit\n";
        cout<<"Type 1 to print the address book.\n";
        cout<<"Type 2 to search for a person by last name.\n";
        cout<<"Type 3 to print the address, phone, and DOB of a person.\n";
        cout<<"Type 4 to print the names of people whose birth are in a given month.\n";
        cout<<"Type 5 to print the names of all people having the same status.\n";
        cout<<"Type 6 to print all names between two given last names.\n";
        cout<<"Type 7 to find all people with a birthdate between 2 given dates.\n";
        cin>>choice;
        cout<<endl;

        switch(choice)
        {
        case 0:
            exit = true;
            break;
        case 1:
            for(int i=0;i<b;i++){
                arrayObj.list[i].printperson();}
            break;
        case 2:
            cout<<"Please enter the last name to search for.\n";
            cin>>last; …