sepp2k 378 Practically a Master Poster

A variable can be referred to as either $VARNAME or ${VARNAME}. The latter form is useful if the variable name is followed by something that's not supposed to be part of the variable name. For example say you have a variable FOO and you want to print the contents of the variable followed by the string "_BAR". If you write echo $FOO_BAR it will look for a variable named FOO_BAR. So you write echo ${FOO}_BAR instead.

In this case there's a space directly after the ${0} so the braces aren't actually necessary. So in this case there is no difference between the two.

sepp2k 378 Practically a Master Poster

Answer rephrased: You can use the same va_list twice.

If you mean why can't you use the same va_list twice without resetting it with va_end and va_start: How would that work? You have to rewind it somehow - otherwise how could it possibly know that you want to start from the beginning and not just read more arguments?

nitin1 commented: hehe :p +2
sepp2k 378 Practically a Master Poster

The as keyword is practically the same as a cast.

The difference being that if the given object doesn't have the right type, a cast will throw an exception while as will just return null instead.

In this case however, there's no need to cast at all since A is a supertype of B. So the line in question should really just be A a = b;.

ddanbe commented: Good addition +14
sepp2k 378 Practically a Master Poster

data[1:2] is a list splice. It returns the sublist of data that goes from index 1 (inclusive) to index 2 (exclusive). So basically it returns a list that contains the element at index 1 and nothing else. If all you want is the element at index 1 without a list wrapped around it, just use normal indexing:

withdrawal = data[1]

It also seems strange to me that you use a list comprehension on a 1-element list to get the balance. I would just do balance = int(data[0]) if I were you. If there's a good reason why balance should be a 1-element list, you could also do balance = [ int(data[0]) ], but I don't see what that reason could be.

sepp2k 378 Practically a Master Poster

Make alert virtual and override it in class b.

sepp2k 378 Practically a Master Poster

Instead of defining a new variable with the same name, you could just assign a different value to the same variable, like this:

public class a
{
    protected string text = "class a";
    public void alert()
    {
        MessageBox.Show(text);
    }
}

public class b : a
{
    public b() {
        text = "class b";
    }
}

This way a b object will only have one variable named text, which will be the one inherited from a (and thus also the one accessed by a methods). And the value of that variable will be "class b" for b objects and "class a" for a objects.

TheApex commented: you explained it better +0
sepp2k 378 Practically a Master Poster

If num starts at 0, then the assignment should be num = 0 then num should increment during the postfix incrementation of num!?

The increment happens before the assignment. Postfix increment does not mean that the increment happens after the current statement. It only means that the result of the expression will be the value of the variable before incrementing (as you can see in the quote of the specification posted by James).

Basically if you have foo(x++) that's equivalent to oldX = x; x += 1; foo(oldX), not foo(x); x += 1;. So x = x++; is the same as oldX = x; x += 1; x = oldX, not x = x; x += 1.

I still feel like, you may have just copied someone elses work, posed as a professor, and want us to explain their code.

He already knows that replacing num = num++ with just num++ will fix the problem, so how would explaining why num = num++ doesn't work, help him take advantage of someone else's work?

When I write this in C++ I get 1

The C++ code invokes undefined behaviour. You might very well get different results on other implementations. If the behaviour were defined (i.e. if = introduced a sequence point), you'd get 0 just like in Java.

sepp2k 378 Practically a Master Poster

You set ehealth to 15 on line 26, which is inside the loop. Then you subtract a random amount of damage between 5 and 9. So ehealth is now somewehere between 6 and 10. That's still above zero, so the loop repeats, jumping back to line 23. So line 26 will execute again, and ehealth becomes 15 again. So the loop will continue forever without ehealth ever becoming zero (or less) because you always set it back to 15 before subtracting damage.

To avoid this problem, you should set ehealth to 15 once before the loop and then never again. Same thing with thealth.

sepp2k 378 Practically a Master Poster

The only way to make println not call the default toString method is to define your own toString method. If you want the contents of the variables to be printed, you'll need to define a toString method that returns a string containing the contents of those variables.

sepp2k 378 Practically a Master Poster

If you're using a boolean variable as your while condition and that while loop never exits, that means that either the variable is never set to False (because the part that's supposed to set it to False is never reached for some reason) or the body of the while loop contains an infinite loop itself.

Either way we won't be able to tell you what the problem is without seeing the code.

PS: Without having seen the code, it seems to me that using a boolean variable as the condition for the while loop is not the most straight-forward way to solve your problem. Something like while enemy.health > 0: should be perfectly sufficient.

sepp2k 378 Practically a Master Poster

AND you need to implement all of the methods specified in the Serializable class.

Yes, all zero of them.

sepp2k 378 Practically a Master Poster
while enemy.hp > 0:
  attack = raw_input("Which kind of attack do you want to perform against the enemy")
  enemy.hp -= damage_for(attack)

print "The enemy is dead!"
sepp2k 378 Practically a Master Poster

You need to move Count1 is Count + 1 after the recursive call to countvowels. Otherwise Count doesn't have a value yet at that point.

sepp2k 378 Practically a Master Poster

It doesn't. The accessibility of a class's constructors and destructor only affects whether and under what conditions you can create instances of the class (specifically you can only directly create instances of the class if at least one of the constructors is accessible to you and you can only create instances on the stack (or delete instances on the heap) if the destructor is accessible). It does not affect whether or under what conditions you can refer to the class at all (e.g. changing the constructors' or destructor's accessibility won't ever change whether or not you're allowed to access a static member of a class or whether you're allowed to use the class name as an argument to sizeof).

sepp2k 378 Practically a Master Poster

Prolog lists are linked lists - not arrays. However like arrays they are used to store an arbitrary amounts of data, so they're used for many of the situations where you'd use arrays in imperative langauges. Does that answer your question?

sepp2k 378 Practically a Master Poster

[S|H] is a pattern that says "this argument must be a list with at least one element. The first element shall be called S and H shall be a list containing all the other elements". You use [e, t, th] for this argument, so S becomes e and H becomes the list [t, th]. Then you call trans(H, Ta). So now prolog searches through the rules of trans to find one that matches the first argument [t, th]. However there is no rule for trans that accepts any kind of list, so no rule is found. Therefore you get false.

So there are basically two things wrong with your rule: 1. You call trans with a list as its first argument when it should be a symbol. 2. You never do anything with S.

trans should be called once for each symbol in the list with that symbol as its first argument. To accomplish that you'd either maplist or recursion. Note that when implementing recursion, you should add a rule for the case where the list you're trying to translate is empty.

ddanbe commented: Very clear answer +14
sepp2k 378 Practically a Master Poster

[you] first need to convert Array into an ArrayList<Student>

No, he doesn't. Arrays can be sorted using Arrays.sort, which works just like Collections.sort, but for arrays.

sepp2k 378 Practically a Master Poster

I think I've answered this in my first post in this thread (for C99 at least):

In C99 sizeof is not a compile-time operator when used on variable-length arrays. It's still a compile-time operator when used on anything else though.

If we're talking about C89, the same thing as for C++ applies: Barring compiler-specific extensions that allow non-standard code to compile, sizeof is always a compile-time operator in C89.

If we're talking about C11, it's basically the same as for C99, but with the caveat that variable-length array are an optional feature in C11. So: in C11, if __STDC_NO_VLA__ is set, sizeof is always a compile-time operator - otherwise it is only a compile-time operator when not used with variable-length arrays.

sepp2k 378 Practically a Master Poster

If you have that code in C++ and you're not using any extensions, it will simply not compile. So if you were asked in a test about standard C++, what the output of that code is, the answer would be "Nothing - it does not compile". And if that's not one of the options the test is either not about standard C++ or it's simply wrong.

sepp2k 378 Practically a Master Poster

In C99 sizeof is not a compile-time operator when used on variable-length arrays. It's still a compile-time operator when used on anything else though.

In C++ your code is not legal. If your compiler accepts it, that means it supports variable-length arrays for C++ as a non-standard extension. gcc will accept VLAs in C++ when in GNU mode (-std=gnu++03 or -std=gnu++11), but will reject them when in standard-compliant mode (-std=c++03 or std=c++11). In C++ as it is defined by the standards, sizeof is purely a compile-time operator. In C++ extended with VLAs it is not a compile time operator when used on VLAs - just like in C99.

rubberman commented: Good explanation! +12
sepp2k 378 Practically a Master Poster

one step back of the first element of the array

I think that's undefined. As far as I know, the only exception is one past the end of the array. In any other case, any pointer arithmetic invokes undefined behavior if the resulting pointer does not point inside the object that the original pointer pointed into.

3 step back from the first element of array and then taking it back to the 1st or 2nd element

Definitely undefined.

then in my example, what's the difference between order of precedence and order of evaluation ?

If || had higher precedence than &&, we'd get int m = ((i++ || ++j) && k--);. This behaves differently from int m = (i++ || (++j && k--)) in the following way:

In the first case k-- gets evaluated if i++ is true or if ++j is true. In the second case, k++ only gets evaluated if i++ is false and j++ is true. This also means that in the first case it is possible for k-- to be evaluated when ++j was not evaluated, but in the second case k-- can only be evaluated if both i++ and ++j have been evaluated.

So you see: the meaning (and thus the result) of the expression changes with different precedence rules, but the order in which the operations happen stays the same. That is i++ will always happen before ++j (assuming ++j happens at all) and ++j will always happen …

nitin1 commented: awesome !! +2
sepp2k 378 Practically a Master Poster

If you just write int sum or int sub, you'd be using those variables uninitialized in your loop, which would invoke undefined behavior. So don't do that.

Your while loop will run until value is either equal to 'q' or 'Q'. This will only happen if the user enters 113 or 81 as the input because value is an int, not a char. If the user entered q or Q, that would simply be discarded as invalid input and value would not change.

sepp2k 378 Practically a Master Poster

== is an operator that takes two operands and produces the value true if the operands are equal and false if they're not. The boolean values produced by == aren't any different than the boolean values stored in your variables. There is no context in which using == would be okay, but using a boolean variable would not be (assuming there isn't some stupid operator== overload in play that returns something other than a boolean). A boolean expression is a boolean expression.

Same goes for !: you can use it anywhere you can use any other boolean expression.

sepp2k 378 Practically a Master Poster

don't like the whites pace rule.does ruby has it?

Ruby does not have significant indentation. However it does have a couple of instances where spaces between tokens matter (like a[b] meaning "access the bth element of the variable or nullary method a" while a [b] means call the method a with the array [b] as its argument).

sepp2k 378 Practically a Master Poster

It will not import both. When you import a module it searches through the available modules and imports the first one it finds with the given name. The order in which it goes through the modules is explained in this section of the docs:

When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

  • the directory containing the input script (or the current directory).
  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
  • the installation-dependent default.

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.

So since sys is a built-in module, it will always be found before your sys.py.

sepp2k 378 Practically a Master Poster

I would assume that input() has a similar problem as you'd see with scanf() in C. Something gets left in the input stream that a subsequent call to input() will terminate successfully on without blocking for the user.

input reads a whole line. Nothing can get left in the input stream.

Ok, now I get... [an error about 'Christopher' not being defined]

According to that error message, you must be using Python 2, not Python 3. In Python 2 input will try to evaluate the input as a Python expression, so if you enter Christian, it thinks that that's a variable and complains about it not being defined. Use raw_input to read a string without evaluating it. In Python 3, input acts like Python 2's raw_input, so this wouldn't happen in Python 3.

sepp2k 378 Practically a Master Poster
u_char * newdata[raw_len]

C++ does not allow variable length arrays, that is when declaring an array like this, the length must be a constant. So raw_len is not allowed as the length. There is no standard way to create arrays of unknown size on the stack. However some C++ compilers do allow variable length arrays as an extension and many libcs also contain an alloca function that allocates memory on the stack instead of the heap.

PS: If the above code did work, it would declare an array of u_char pointers, not an array of u_chars. It should be u_char newdata[raw_len] to create an array of u_chars.

sepp2k 378 Practically a Master Poster

so the if statement isn't required?

You only need the if statement if you want your code to act differently depending on whether it's imported or run as a program.

what is the __name__ by default?

If the Python file is run as a program (i.e. using python bla.py, a double click in the file manager (assuming you have set it up, so that that actually runs the program rather than opening it in an editor), using ./my_file.py in combination with chmod +x and a shebang line -- whichever), __name__ will be "__main__". If it is imported from another Python file or from the Python shell by writing import my_module, __name__ will be "my_module" where my_module is the name of your file without the .py extension.

I don't understand what you mean when you say "if the Python file is invoked directly" does that mean double clicking on a .py file

See above.

or can I run a .py file using python?

That too.

Basically running it directly refers to any means of running your Python code other than using it from other Python code.

I think import can be used to access functions from another .py file

Yes.

sepp2k 378 Practically a Master Poster

You can name your function anything you want, but the name has to be "__main__". That's not about the function being called. "__main__" is simply the value that __name__ gets if the Python file is invoked directly instead of being imported.

PS: Calling your function both inside and outside of the if means that your function will be called once if the file is imported and twice if the file is run directly. That doesn't seem like what you'd want.

sepp2k 378 Practically a Master Poster

The error message is saying that you specified the default value for find_words both in the declaration and the definition of the function. You're only supposed to do it in the declaration.

sepp2k 378 Practically a Master Poster

A Python file can either be run as a program or it can be imported by another Python file as a library. if __name__ == "__main__": means "only run the following code, if this file was run as a program - not imported as a library".

This is useful if you want other program's to be able to import this program's functions without actually running the program.

sepp2k 378 Practically a Master Poster

That's not true. item is every element from the list of dictionaries p so item is a dictionary.

Right, my mistake, the error was that you called sum on the result of get_average. get_average returns a float, but sum expects an iterable.

sepp2k 378 Practically a Master Poster

Maybe it would be more fruitful to attempt to learn Python rather than hoping that someone will do your homework for you (spoiler alert: noone will).

PS: Please don't post the same question on multiple sites on the internet at the same time. It's against the rules here and it's rude.

sepp2k 378 Practically a Master Poster

You're invoking undefined behavior, the output could be anything (notably gcc will produce different output with -O1 than with -O2). It is highly unlikely that your compiler writes a specific byte sequence into bytes used for padding. Rather I'd expect it simply leaves them untouched, so they will just have whatever value previously resided in that memory location. If you move your code into a function, you'll probably notice that the value of b will change depending on whether or not you call other functions before calling your function.

For example the following code, compiled with gcc without optimizations, will produce different results on my system depending on whether or not I comment out the call to g():

#include <stdio.h>

void f()
{       
    union u
    {   
        struct s{int a;int b}n;
        struct ss{int c;long d}ni;
    } uu;
    uu.ni.c=42;
    uu.ni.d=23;
    printf("%d %d",(uu.n.a),(uu.n.b));
}

void g() {
    int x=1, y=2, z=3, a=4;
    printf("%d %d %d %d\n", x, y, z, a);
}

int main() {
    g();
    f();
    return 0;
}

When I compile without optimizations and call g, b will have the same value that z had in g -- changing z will change the value of b. When compiled with optimizations, b will always be 0 -- whether I call g or not.

sepp2k 378 Practically a Master Poster

It means "Text means a character array of size 80", yes. There's no such thing as an array of typedefs because typedefs are a compile-time concept only - they're not something that can be stored in arrays.

The syntax of a typedef is basically the same as that of a variable definition (except for the keyword typedef in front obviously). The name of the typedef goes where the variable name would usually go and the type that that variable would have is the type that's being aliased. So since char Text[80]; would define a variable named Text that stores a character array of size 80, typedef char Text[80]; defines a typedef named Text that describes character arrays of size 80.

sepp2k 378 Practically a Master Poster

What do you mean by "oops"? I assume the oop part stands for Object Oriented Programming. What does the s stand for?

Anyway object oriented programming in Ruby isn't fundamentally different than in other languages, though obviously the fact that Ruby is dynamically typed and otherwise also very dynamic makes it quite a bit different from C# and Java in general. It's object orientation is also much more inspired by small talk than the languages you mentioned, but that affects the terminology more than anything else. It's also different from Java that every value (including integers) is an object with methods.

The exact semantics of private and protected methods also differ from those in C# and Java. Specifically private in Ruby means that a method can only be called on the current object (and not on other objects of the same class) and protected means that the method can also be called on other objects of the same class (or a subclass). You can always access superclass methods from a subclass even if they're private.

sepp2k 378 Practically a Master Poster

So why does the foll code doesnot give any exception although e points to object of same class??

Your original code created a new Animal object every time that an Animal object was created. Your new code only creates a new Animal object if you call the foo method. You call the foo method on the first Animal that you create, but you don't call foo on the second Animal (the one that you create inside foo). So it stops there and no infinite recursion happens. If you added the line e.foo() inside your foo method, you would get infinite recursion again.

sepp2k 378 Practically a Master Poster

Each Animal object has an instance variable named a. Every time a new Animal object is created, its e variable is initialized to new Animal(), which creates a new Animal object. So every time you create a new Animal object, you create another Animal object. So if you create one Animal object, you create an infinite amount of Animal objects. This leads to a stack overflow.

sepp2k 378 Practically a Master Poster

In Python (and many other languages) there is a difference between changing variables and changing objects. A statement of the form myvar = new_value will change the variable myvar. Most other things that you can do with myvar (like myvar[i] = foo or myvar.append(bar)) will change the object, not the variable.

If you execute a statement of the form myvar = my_other_var, then the two variables will now refer to the same object. If you change that object, the change will be visible through both variables. However if you change one of the variables to refer to a different object, that change will not be visible to the other variable and the variables will no longer be connected in any way.

So names = deque(...) does not affect nmls because it's changing the variable, not the object.

sepp2k 378 Practically a Master Poster

No, these are not equivalent at all. If you try to compile and link the second piece of code, you'll get a linker error telling you that a has not been defined.

It is true that the default linkage is external, but extern does more than just saying that a variable's linkage is external. It also says that this is only a declaration - not a definition - and the corresponding definition can be found elsewhere (generally in a different compilation unit).

sepp2k 378 Practically a Master Poster

Then you should fix those, too.

It's not uncommon that fixing one error will produce multiple other errors that were previously unreported. That does not mean that you're going in the wrong direction (even if intuitively one might think that few error messages are better than many error messages).

sepp2k 378 Practically a Master Poster

The compiler doesn't recognize Node until after the typedef has been fully parsed. So you can't use the typedef inside the struct. In order to write a recursive struct, you'll need to name your struct without typedef and use that name in the struct.

struct node {
    struct node* next;
};

You can still typedef it if you want, but you'll only be able to use the typedefed name outside of the struct - inside the struct you need to use the struct name.

sepp2k 378 Practically a Master Poster

Do you want to know how to concatenate a string and an integer using +? If so: by converting the integer to a string first. That might look like this:

s = "foo"
x = 42
foo42 = s + str(x)

That said using format might be better than using + here:

"foo{}".format(x)
sepp2k 378 Practically a Master Poster

The + operator associates left to right, so when you write "A+B= "+a+b that's parsed as ("A+B= "+a)+b. "A+B= "+5 is "A+B= 5" and "A+B= 5"+7 is "A+B= 57", so that's the result. You need to add 5 to 7 first and then add the result to the string. To do that put 5+7 in parentheses.

sepp2k 378 Practically a Master Poster

In Python 2 the / operator returns an integer if both operands are integers - rounding the result down if necessary. So 3/2 would be 1 in Python 2. In Python 3 this behavior has been changed, so that / always returns a float even if both operands are integers. So 3/2 would be 1.5 and 4/2 would be 2.0.

The code you've posted was apparently written for Python 2 where image_width/width would result in an integer. Presumably you're using Python 3 where it results in a float and that's why you get that error. To fix this you can replace the / operator with the // operator, which performs integer division (in both Python 2 and Python 3).

sepp2k 378 Practically a Master Poster

You seem to think that if the end of file is reached, fscanf will store EOF in the given variable. It won't - it will simply keep the variable unchanged. The only way to tell whether fscanf successfully read a value is to check the return value of fscanf - you can't tell by looking at the variable.

The easiest way to make your code work would be to simply have two loops after each other: One that goes through the first file and one that goes through the second. To avoid code duplication, you should define a function that takes a file as an argument and then sums that file. Then you can simply call that function once with the first file as the argument and once with the second.

SoreComet commented: Never thought of this! thank you +0
sepp2k 378 Practically a Master Poster

Yes, you can use class files from different directories by adding all the directories to your classpath. If you're using an IDE, you can do so in your project's settings. If you're compiling from the command line, you can use the -classpath switch or the CLASSPATH environment variable to set the class path. On Windows multiple directories are separated by a semicolon.

So if you have p1.abc in d:\stuff\p1\abc.class and p2.pqr in e:\otherstuff\p2\pqr.class, you can compile a class that uses both those classes from the command line like this:

javac -classpath d:\stuff;e:\otherstuff MyClass.java
sepp2k 378 Practically a Master Poster

What happens when you add an element to a vector that is already at capacity?

The capacity is increased (often doubled, but that's up to the implementation), new storage is allocated with the given capacity and the contents of the vector are copied to the new storage.

Does std::vector have a "capacity"?

Yes. You can query it with the capacity method and manually increase it with the reserve method.

sepp2k 378 Practically a Master Poster

Variables that are declared inside a method will always go out of scope at the end of that method. You don't need to do anything special to make it that way.

Aaron_JY commented: Never knew this. Thank you. +0
sepp2k 378 Practically a Master Poster

The distinction between O, Theta and Omega isn't about best- versus worst-case. You can use any of these notations to analyze any case you want. That is, the statements "QuickSort's worst case is in Theta(n^2)" and "QuickSort's best case is in Theta(n log n)" are both valid usages of Theta.

Instead the distinction is that O specifies an upper bound, Omega a lower bound and Theta both. What this means is that "Foo is in O(n^2)" means that Foo is quadratic or less (that is when something is linear, it's also in O(n^2) because linear is less than quadratic). Similarly Omega(n^2) means quadratic or more (that is something qubic or even exponential will also be in Omega(n^2)). Theta(n^2) means it's exactly quadratic. That is when something is quadratic, it's in Theta(n^2), but something that's linear, cubic or exponential is not. Something is in Theta(f(n)) if it is both in O(f(n)) and Omega(f(n)).