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

OK, perhaps we need to start over from scratch. What you need to understand is that an object is a model of something. It can be something real, like a car or a person, or something conceptual, like a list or a dictionary (I use those examples because, as it happens, lists and dictionaries are objects in Python). The point is that the object captures or encapsulates the properties of the thing it is modeling, its current state, and its potential behavior. The properties and state are described by variables that are part of the object, called instance variables, and the behavior is described by functions which are bound to the object, called instance methods.

A class is a description of an object, a sort of template or mold for making new objects. It defines both the instance variables of the object, and the methods the object can perform. It works by providing a way of creating a new object - the __init__() method, also known as the constructor or c'tor. The c'tor primary job is to set the initial values of the object's instance variables. It can do anything that you can do in any other method, but it should initialize the instance variables in some way.

In Python the first argument of any instance method is the object itself, which by convention is named self. This is true of the __init__() method as well, even though it is actually not an instance method per se (it is a …

Necrozze commented: Thanks man! This was exactly what I was looking for +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, you have to understand that no one here is going to write the program for you. This forum is for assisting programmers with projects, but we do not provide free homework solutions of the sort you seem to be looking for. In the forum rules, it states specifically:

Do provide evidence of having done some work yourself if posting questions from school or work assignments.

This means that, unless and until you show us the code you've already written, we cannot do much to help.

Second off, is the program supposed to be in C, or in C++? These are two different languages, even though they are closely related, and writing the program for one of them is different from writing it for the other.

Third, if you don't know how to write the program, can you tell us what is holding you back, specifically? We may be able to give general advice, even if we can't solve it for you directly.

Fourth, you need to realize that this forum is not like chat or IM; there may be a lag of hours or even days before you get a response. Conversely, the size of the message does not have to be limited; thus you can and should write out full setneces, without resorting to SMS-type abbreviatations.

ddanbe commented: Your English and comment are better! +14
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

As PyTony points out, the code as given does not use the zipfile module, but rather calls on a separate program named 'zip' to perform the file operations. That is both unnecessary and non-portable. This is how it would work using the zipfile module:

import zipfile

zip = zipfile.ZipFile(target, 'w')

Now, to get the desired effect of zipping up a whole directory tree, you'd have to recurse through the whole directory tree and add each file in turn. However, if you have Python 2.7 or later, you can use the make_archive method of the shutil module instead:

import shutil

# where we are running in the root directory of the archive,
# and source is the archive's base directory 
make_archive(target, 'zip', '.', source)
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

The answer to that is going to be entirely implementation-dependent, and the difference is probably negligible. Only by profiling can you get a definitive answer. The main cause of the difference probably will not be from the return per se, but from the need to pack and unpack the struct with the data.

If you don't mind me asking, why is this a significant concern? Worrying about this seems like premature optimization to me. It is generally more profitable to get the program working first, then look into the efficency of the different parts - and only to optimize those areas which can be empirically shown (via profiling) to be bottlenecks or hot-spots. Otherwise, you risk creating what Michael Abrash referred to as a 'fast slow program' - on which is nominally 'optimized', but doesn't run any better than the unoptimized version, because the worng parts of the code were tightened up at the expense of overall performance.

From a design and maintainability standpoint, it would probably be more fruitful to look at what you are doing with the data both before and after the function. If you find yourself using the structure anyway, or if the data is being passed around as a unit to more than one function, then by all means you would be better off with the struct. OTOH, if this is the only place where you use the structure, and it is used solely to pass back multiple values and not used in …

mike_2000_17 commented: Agreed +14
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Valid point. Looking again at the page I'd linked to, I see I was clearly mistaken. I think I was jumping to a conclusion that the mridul.ahuja was talking about Turbo C, and went off half-cocked as a result. Also, it is so common to see 32-bit ints these days that is is easy to forget that they are non-portable.

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

Basically, you would need to call the interrupt twice, once for each string you are printing.

SECTION .text
            global _start
_start:
            mov eax, 4          ;sys_write
            mov ebx, 1          ;output to screen
            mov ecx, string     ;creates address for my string variable
            mov edx, length     ;creates address for my length variable
            int 80h             ;call the kernel
            mov eax, 4          ;sys_write
            mov ebx, 1          ;output to screen           
            mov ecx, string2    ;creates address for another string
            mov edx, length2    ;creates address for another length
            int 80h             ;call the kernel
            mov eax, 1          ;sys_exit
            mov ebx, 0          ;no error exit
            int 80h             ;call the kernel

SECTION .data
string: db 'Howdy Folks!', 0Ah  ;output string
length: equ 13                      ;length of string
string2: db 'Another line!', 0Ah    ;output another string
length2: equ 14                 ;length of string2

Note that the code as given had a number of problems with it; for example, the entry point should have been _start, not START (otherwise the standard Linux linker, ld, won't find it), and the lengths of the strings should have included the newlines.

As for what int 80h does, it signals a software interrupt, a low-level mechanism used to send requests to the kernel. When an interrupt occurs, whether from the hardware or from a program, the current program is halted and the system goes into a kernel routine mapped out to handle the interrupt. The interrupt mapped for hex 80 (decimal 128) happend to be mapped to a set of operating system services which get selected from a …

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

It would depend on just what you are doing, but generally speaking, you would have them in separate files. Keep in mind that you can only have a single public class in a file.

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

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

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

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

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

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

You will need to you double indirection, i.e., a pointer to a pointer.

#include<stdio.h>

void swap(char **a,char **b);

int main()
{
    char *p[2]={"hello","good morning"};
    swap(&p[0],&p[1]);
    printf("%s %s",p[0],p[1]);
    return 0;
}

void swap(char **a,char **b)
{
    char *t;
    t = *a;
    *a = *b;
    *b = t;
}

Not entirely obvious, but simple enough once you see it.

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

What have you got so far?

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

Try this tutorial on the subject; while the references to specific architectures is a bit dated, it is nonetheless generally accurate.

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

First off, you should know general Java programming, as Android is based on Java. I would start with Oracle's Java Documentation, and a good book on the topic such as Thinking In Java (if you can't afford the e-book, the previous edition is available for free). You will also want to pick up the Eclipse IDE and learn how to use it, as it is the best suited for Android development.

Once you've got a decent grasp of the basics of Java programming, then you'd want to pick up the Android SDK, for developing your apps, and set up the Android emulator, for testing them. I would also recommend reading Learning Android as aan introductory textbook, followed by Programming Android in the same series.

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

The main issue is actually with your format string; for month, you should use capitalized letter M. Similarly, for 24-hour time going from 00 to 23, you need to use capital H. To get the time zone in the format you want, use the capital letter Z twice.

"MM.dd.yyyy HH:mm:ss ZZ"
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

More importantly, what newline() function? Python doesn't have one, AFAIK. To print a newline, you use print() with no arguments.

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

One thing I would recommend also: you don't need to read the image files each time you want to change the image or BLIT it; you can save the images in variables and simply copy it to the current variable when you need to. In my version, I have it initialize the master cpoies at the time when the class is built, and then simply pass a reference to it to each of the individual objects, The relevant part of the Enemy class, for example, is

class Enemy(GameObject):
    front_src = "Boss.png"

    def __init__(self, screen):
        try:
            front = pygame.image.load(Enemy.front_src)
        except:
            print("Could not load enemy image")
            exit(-1)

The object in front is passed to the c'tor of the parent GameObject class, which stores it for later use. It uses a little more memory, but cuts down on the disk accesses, making the game more efficient. The Player class extends this with image_right and image_left members:

    def __init__(self, screen):
        try:
            front = pygame.image.load(Player.front_src)
        except:
            print("Could not load player front image")
            exit(-1)
        try:
            self.image_left = pygame.image.load(Player.left_src)
        except:
            print("Could not load player left image")
            exit(-1)
        try:
            self.image_right = pygame.image.load(Player.right_src)
        except:
            print("Could not load player right image")
            exit(-1)

        new_y = screen.get_rect().bottom - front.get_rect().top

        GameObject.__init__(self, screen, front, 0, new_y, 0, 0, False)

Even without using classes, you can simply have (for example) Player_front_img, Player_right_img and Player_left_img variables holding the image data, without having to read the file every time.

Necrozze commented: That's a really great tip actually, will deffinetly use it! Didn't think of it that way +0
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Rather than the standard Python time methods, I would recommend using a PyGame Clock object, as the Clock.tick() method is specifically designed for this sort of thing.

I would also take the time out to re-write the code with classes. My own version of this now has a GameObject class and a Player class; I haven't gotten around to the Boss and Bullet classes, yet.

(Is it wrong of me to have completely refactored this program for my own edification?)

chris.stout commented: Clock.tick() is perfect for what's needed here. +2
Necrozze commented: I changed to Clock.tick and now it doesent crash, thanks man +0
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 ours (not …

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

Perhaps you could use some additional expalantions on variables, objects, functions, methods and classes.

An object is a set of properties and the set of actions which can be applied to those properties. For example, 17 is an object, representing the number seventeen. The string 'hello, world!' is also an object. The list [23] is an object that contains another object, and has the properties of length (one) and contents (23). A TkInter Label is an object with several properties, such as it's text, it's size, and it's position on the Frame. The properties of compound objects such as a Label are themselves objects.

A variable is a reference to (that is to say, a name for) an object. All variables in Python refer to objects. A variable can be changed so that it refers to a different object; for example, you could assign fnord to have a value of 5, then reassign it to a value of 17. The object 5 is still in memory though, and will remain in memory until all references to it are gone.

A function is a special kind of variable that represents a series of actions. A function can take a series of parameters, which are variables which, when the function is called, or run, are bound to the actual arguments of the function. A function can also return a value. An example of a function would be:

def foo(a, b):
    return a * b

which is then called like so:

Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster
  • Develop an extension of the ELF object format and the Unix ld linker that allows for C++ template functions to be separately compiled. Kudos if you can fit the extension into the existing format without changing the underlying structures, such that existing linkers can still use the extended format when the extensions aren't being applied.

  • Make up a toy language of some sort with some feature you've always found missing in other languages. Write a simple compiler or interpreter for the language. Defend the addition of the new feature with example code and statistical analysis of its performance and impact on the length of programs.

  • Develop a modified Clipboard/kill-ring with multiple levels of undo, such that users can visually choose which changes to recall from a history of previous alterations.

  • Develop a Linux or FreeBSD variant with system-wide garbage collection, integrated into the paging system. Provide analysis of the impact on both performance and security.

  • Develop a workable model of persistence and objects in untyped lambda calculus.

  • Develop a proof (or disproof) for the Church-Turing Thesis.

Evil minded, you say? Why, thank you.

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

If want you want is to have the cursor change to the hand cursor when you mouse over the label, then the following should work:

from tkinter import Tk, Frame, Label


def label1_lclick(event):
    print ("clicked at {},{}".format(event.x, event.y))

def label1_mouseover(event):
    master.config(cursor="hand2")

def label1_mouseexit(event):
    master.config(cursor='')


if __name__ == "__main__":
    master = Tk()


    mainFrame = Frame(master, height=500, width=300)

    label1dep = Label(mainFrame, text="Departement Informatique" ,bg = "blue" ,font=("times",12, "bold"),  fg = "white" )
    label1dep.place (x=40 , y=220)

    label1dep.bind("<Button-1>", label1_lclick)
    label1dep.bind("<Enter>", label1_mouseover)
    label1dep.bind("<Leave>", label1_mouseexit)

    mainFrame.pack()

    master.mainloop()

Let me know if that's what you wanted or not.

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

What sepp2k says is correct, but I suspect that there is more to this that may be relevant. What is the script supposed to do, and how many different codes are there? If there are more than two or three different ones, you may want to use a dictionary to hold the possible key-value pairs, and do a lookup rather than having an extended if/elif/else block. For example:

from sys import exit, argv

if len(argv) < 4:
   print("You must provide exactly three arguments for this program.")
   exit(-1)

code = argv[1]
phone = argv[2]
message = argv[3]

lookup = {'949': '62000001760', '947': '62000001840'}

try:
    servId = lookup[code]
except KeyError:
    servId='90928'

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

Let's try this again, shall we?

def temperature():
    temp = None
    coldPoint = 21
    hotPoint = 24

    while temp is None:
        try:
            temp = int(raw_input("Enter temperature: "))
        except ValueError:
            print("Ooops! Enter number Please !")

    print "The temperature is",

    if temp <= coldPoint:
        print "too cold."
    elif temp >= hotPoint:
        print "too hot."
    else:
        print "acceptable."

if __name__ == "__main__":
    temperature()
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Using the input() function in Python 2.x is generally considered a bad idea, as it will actually evaluate the statement as if it were a line of Python code. This leaves a large security hole that anyone could exploit - if,instead of just a number, the user were to enter something like;

os.chdir('/')

they could play merry hell with the program and/or the operating system. Using raw_input() and then casting to int is generally the safest way to read an integer value in.

In Python 3.x, the input() function has been changed to behave like raw_input() did in Python 2.x; i.e., it reads in a string of text without processing it.

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

I have to agree with Terminator1337 on this, the code for the main() function in particular is wretched (not to mention incorrect - in C++, main() should always return an int, with no exceptions to the rule). The fact that it appears to have been given to you by the instructor makes this even less acceptable.

As for the ReduceFraction() function, simply think through how you would do it manually: you first find the greatest common divisor of the numerator and the denominator, then divide them each by said divisor. Simple, no?

Getting the common denominator of two ratios is almost as easy: you multiply the denominators, then multiply num1 by den2 for the new num1, and num2 by den1 for the new num2.

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

There are quite a few problems with this program as it is written, but all of them can be fixed with some patience. The biggest issue I see is that you are reading in the name of the animal to be found, then overwriting that name repeatedly in the condition of the loop. You want something more like this:

            cout << "Please enter the name of the animal you are searching for: ";
            string petName;
            cin >> petName;

            while (inputFile >> name)
            {
                if (name == petName)
                {
                // get the file data here

Note the comment there, because that brings to light the second problem: you are reading the animal information only for the first animal, exactly once, and then printing out the data repeatedly. What you seem to want is to read the data only once the animal's name has been found, and then print out the results outside of the loop. This would make the code above look like:

            cout << "Please enter the name of the animal you are searching for: ";
            string petName;
            cin >> petName;

            while (inputFile >> name)
            {
                if (name == petName)
                {
                    inputFile >> visited;
                    inputFile >> cost;
                    average = cost / visited;
                    break;
                }
                else
                {
                    inputFile.ignore(1024, '\n');
                }
            }

            if (!inputFile)
            {
                cout << "Animal not found.";
            }
            else
            {
                //Display the animal name, times visited, and cost.
                cout << "The animal " << name << " was checked into the clinic " << …
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

First off, you need to recall that Java is case-sensitive. which means that PackageData and packageData are two different things. The former is the class name, the latter is an instance of the class declared in the main() method of PackageDataTest.

Second, the toString() method is something of an exceptional case in Java, as it is used implicitly whenever an object is coerced to a String value. So what is happening here is that the object packageData (not the class named PackageData) is being passed to printf() as its String representation, so packageData.toString() is automagically called.

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

Thank you pyTony , but i can't use Classes , i try to define a cliquable area in my close to my label.

If you don't mind me asking, why can't you use a class? Is it a case where you can't (i.e., you aren't familiar with developing them), or where you aren't permitted to? It seems like a strange requirement, which is why I am asking about it.

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

Perhaps it would make more sense to start with a parent class, Profession, which would have the various attributes in common to all the subclasses:

class Profession(object):
    def __init__(self, name, strength, pilot, intel, stamina):
        self.strength = strength
        self.pilot = pilot
        self.intel = intell
        slef.stamina = stamina

    # other methods common to all the subclasses would go here

class Starfighter(Profession):
    def __init__(self, name, strength = 20, pilot = 55, intel = 40, stamina = 35):  # defaults - can be overridden
        Profession.init__(self, name, strength, pilot, intel, stamina)

    # methods specific to Starfighters

class Diplomat(Profession):
    def __init__(self, name strength = 45, pilot = 20, intel = 50, stamina = 35):  # defaults - can be overridden
        Profession.init__(self, name, strength, pilot, intel, stamina)

    # methods specific to Diplomats

# etc. - classes for other professions here

You then could simply declare your characters as being of the given class:

defaultPilot = Starfighter("John Doe")
betterPilot = Starfighter("Luke Skywalker", pilot = 75)  # using custom values for the attributes

Hopefully, this will get you going. Let us know if you need more help on this.

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

I assume you are referring to and GCC-based IDE such as Code::Blocks or something similar here, correct? Basically, they are two different options for generating the executable, which some IDEs provide as a shortcut. They allow you to have two different sets of compiler options to be set up, one for use in development and the other for the final, optimized stand-alone version.

Debug mode by default simply means that it generates code with optimizations disabled (the -O0 option in GCC) and all debugging symbols included (the -g option). This makes it possible to debug the code with the GDB debugger, without having to deal with the various complexities of highly optimized code.

Conversely, Release mode by default has a high level of optimizations in place (-O2 or even -O3, though the latter option includes 'unstable' optimizations and is best avoided), and discards the debugging symbols. It is intended to produce a smaller, faster executable for distribution, at the expense of being able to debug it. Generally speaking, you would only switch to Release mode after you have finished testing and debugging the program, and are ready to ship it to users in binary form.

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

When I think of the state of CS education around the world - and yes, especially in India - I am reminded strongly of what Dick Feynman said about Brazilian physics work in the 1950s: that there are a lot of people 'learning' computer programming by rote, without actually understanding the meaning of what they are doing. This isn't to say that there aren't brilliant Indian programmers - I've known several - but they are, for the most part, the one's who went out of their way to learn the subject, which means that despite the public efforts to educate people on the subject, the number of competent programmers is virtually unaffected.

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

Anyone who says that the current generation of programmers is in some way inferior to those of the past, is clearly unfamiliar with the programmers of the past. You must recall that until very recently the vast majority - 90% or more - of programmers were COBOL coders, often with only a few weeks of training before being set loose on the computer world. If you truly think that they were any more inclined to delve deep into the details of the field, you are deluded.

So why do the current coders seem so much worse? It's simple: numbers. The sheer number of newly minted programmers, and the considerable monetary gains to be made by working in this field, mean that the overwhelming majority of newcomers will be people with little actual interest in computing and are looking only for a quick paycheck. This last part has always been true, or at least has been since the early 1970s, but the sheer volume of would-be coders means that the education system in place is being swamped. This is especially true in places like India, Brazil and the former Iron Curtain countries, where the disparity in incomes is even more dramatic and where there have been strong pushes by the national governments to encourage people to enter the field, but little infrastructure added to facilitate them.

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

While what mike_2000_17 said is all correct, the real reason is actually a lot simpler: C++ has no concept of console I/O because C++ - and many of the operating systems it operates under, including Unices - has no concept of a console. More importantly, C++'s standard libraries operates primarily on abstract streams rather than devices, and has no way of knowing if a given stream is a dumb terminal, a file, a network socket, or a window in a windowing environment. These are all system-dependent definitions. Not all systems have consoles, just as nt all systems have files, or network connections - again, consider the case of an embedded controller.

Moreover, the capabilities of a console vary from system to system, and not in trivial ways. You have to recall that the original Unix system worked primarily with TTYs, literal teletypes that printed output to a roll of paper. Even when more advanced consoles were available - which they were, even in 1967 - there was no standardization as to what operations they could perform. How do you handle the case of 'move the cursor to screen location (x, y)' when you don't know if the terminal in question is even capable of doing so, or even if it has a screen at all? While libraries like termcap and curses were eventually developed to work with different kinds of terminals in a uniform fashion, they couldn't be made part of the language because it would require thousands of different …

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

To give a perfectly serious and not at all snarky answer, the first question I have is: why Turbo C? Does the course you are taking require that particular compiler/IDE (I can't imagine any other reason for using such an antique, but I know that many schools in India and Pakistan among other places have standardized on it), and if so, how did you get to your 4th semester without using it before?

OK, maybe that was a little bit snarky. But to continue: what version of Windows are you running under? This is quite relevant, as versions of Windows from Vista on will not run Turbo C (or Turbo C++, for that matter) without using a virtual machine to emulate an older edition of the operating system. It will complicate the process of installing Turbo C, but it will still be possible (sort of).

Next, do you have an actual copy of Turbo C to install? It shouldn't take more than a simple Google search to find a downloadable copy, so I'll leave it to you to get it. The installation process should be self-evident.

Assuming that you have a suitable installation of Turbo C on hand, the solution is to... run Turbo C. That's really all you need do, as it will automatically create an editing window for you. Write your program and save it, then compile. Simple.

I have one final question, however: didn't your professor explain all of this to the class?

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

OK, now that the necessary roughness is out of the way, we can actually begin helping you.

I do have to admit that this is terrible code, and most likely cannot be remediated; but it would be remiss of me not to point out why it is bad, or else the OP won't learn from the experience.

Aside from the formatting issues, the main problem is repetitiveness; you have cut and pasted the same basic code, with only a trivial addition made to it at each step, roughly 20 times, jut in one section of the code alone. This entirely black of code could be replaced with a single for() loop about five lines long. Such repetition is found throughout the code, making it larger and harder to read across the baord.

Similarly, you have (as Phorce points out) created 20 variables with the name in the form x{nth} for what would normally be a 20 element array. Not only is this an exceedly bad naming convention, it limits how you can use the values compared to the equivalent array. Equally atrocious is the use of the n{letter} for what would again be a single 20-element array normally. In fact, the naming conventions use in the program are uniformly awful.

Still, as Deceptikon says, it is the completely lack of indentation that is really doing you in here, as it makes it well-nigh impossible to be certain how the braces match to each other. Even if one is disinclined to …

Nick Evan commented: I've gotta give you credtis for trying to wade through this.. +14
phorce commented: Was there any need to re-post the whole code again? Even if you did fix it! Sorry but, from the previous posts and the fact the o/p hasn't replied to any comments, I think you just might have wasted your time. +6
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

With the exceptions of inline functions and templates, you do not want to have function implementations inside of a header file. You generally need to separate then out of the header and into a code file that will be compiled. Also, you want to use #include guards around the header files themselves, to prevent multiple inclusions in the same compilation unit. This should give you two files that look like this:

story.h

#ifndef STORY_H
$define STORY_H

class Story{

public:
    Story();
    ~Story();
    void mainMenu();
    void start();

private:
    void levelOne();
    void judgement();
};

#endif

and

story.cpp

#include "story.h"



Story::Story(){

}

Story::~Story(){

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

OK, I tried out my own suggestion, and found that it didn't solve the problem. However, I did determine that putting double-quotes around the text does get it to work:

subprocess.call('echo "{0}" | festival --tts'.format(line), shell=True)

I'd still recommend using PyTTSx, though, if it is an option for you..

Gribouillis commented: I didn't know pyttsx +13
Schol-R-LEA 1,446 Commie Mutant Traitor Featured Poster

Actually, there is a free version of Qt available from the Qt Project site; the commercial version is only if you are intending to write commercial software using the Qt libraries, IIUC. The opern source version does lag behind the commercial version by a few revisions, but the differences are not usually that significant.

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

This is a difficult thing to really give any advice on, as everyone has a different 'feel' for their favorite tools. I can only tell you my own impressions, and hope yours may be similar.

Of the handful of Python editors and IDEs I have tried, the best I personally have found are Eric, and the PyDev extensions for Eclipse. Both have the advantage of working with either Python 2.x or 3.x if you have both installed at the same time.

However, I have not tried the any of the commercial IDEs to date (such as WingWare or PyCharm), and cannot give any advice on them.

The question of the version of Python to use is mostly a pragmatic one, in that many 3rd party libraries for Python have not yet been updated to work with Python 3. I would recommend learning Python 3, unless you had reason to use a major Python 2.x package such as Django.

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

This approach won't work on C++ string objects, at least not consistently. The string class does not use zero-delimiters to check the length of a string, but rather keeps a private size variable that is updated automagically as the string gets manipulated.

In any case, the string class has a built-in size() method. If you need the length of a string, use that.