• Hey, guest user. Hope you're enjoying NeoGAF! Have you considered registering for an account? Come join us and add your take to the daily discourse.

Programming |OT| C is better than C++! No, C++ is better than C

Rapstah

Member
Str is always 256 (257?) characters long, but the read line could be shorter since you never look for the end null chatacter. You're also only zeroing the first element of the vowel count array.
 

leroidys

Member
Need some more C++ help.

I'm trying to make a program that takes in a user input, passes it into an array, counts the frequency of a given vowel within the string and then outputs that amount:

Code:
#include <iostream>
#include <string>

using namespace std;

int countVowels(int [], char []);

int main()
{
  char str[257];
  int vowelCnt[5];
  cout << "Enter a character string (max 256): ";
  cin.getline (str,257);
  countVowels(vowelCnt, str);
  cout << vowelCnt[0] << endl;
  cout << vowelCnt[1] << endl;
  cout << vowelCnt[2] << endl;
  cout << vowelCnt[3] << endl;
  cout << vowelCnt[4] << endl;

}

int countVowels(int counts[], char str[])
{
    int vowelCnt[5] = {0};

    for (int i = 0; i < 257; i++) {

        if (str[i] == 'a' || str[i] == 'A') {
            vowelCnt[0]++;
        }
        else if (str[i] == 'e' || str[i] == 'E') {
            vowelCnt[1]++;
        }
        else if (str[i] == 'i' || str[i] == 'I') {
            vowelCnt[2]++;
        }
        else if (str[i] == 'o' || str[i] == 'O') {
            vowelCnt[3]++;
        }
        else if (str[i] == 'u' || str[i] == 'U') {
            vowelCnt[4]++;
        }
    }
    return *vowelCnt;
}

Debugging shows that str is holding some pretty funky characters outside the user input, and vowelCnt is holding some pretty funky numbers.

Any ideas?
You need to stop counting when you hit a null. A good way to do this is:

i=0;
While (string)...


And initialize your count variables.


EDIT:
C does not do anything with memory before serving it to you (unless you use some specific data types or functions.) When you have a pointer, it just points to a random spot in memory that contains some value. If you want an int to start at 0, you have to explicitly set it equal to zero. If you want an empty string of length 257, you have to overwrite the garbage data that started there. C knows that a string ends when it encounters a null char, which you can write as '\0'. If you have

str char[16] = "hi\0blahblah"

and you try to print str, it will only print "hi"
 

harSon

Banned
Something like this?
Code:
#include <iostream>
#include <string>

using namespace std;

int countVowels(int [], char []);

int main()
{
  char str[257];
  int vowelCnt[5] = {0, 0, 0, 0, 0};
  cout << "Enter a character string (max 256): ";
  cin.getline (str,257);
  countVowels(vowelCnt, str);
  cout << vowelCnt[0] << endl;
  cout << vowelCnt[1] << endl;
  cout << vowelCnt[2] << endl;
  cout << vowelCnt[3] << endl;
  cout << vowelCnt[4] << endl;

}

int countVowels(int counts[], char str[])
{
    int vowelCnt[5];

    for (int i = 0; str[i] != '\0'; i++) {

        if (str[i] == 'a' || str[i] == 'A') {
            vowelCnt[0]++;
        }
        else if (str[i] == 'e' || str[i] == 'E') {
            vowelCnt[1]++;
        }
        else if (str[i] == 'i' || str[i] == 'I') {
            vowelCnt[2]++;
        }
        else if (str[i] == 'o' || str[i] == 'O') {
            vowelCnt[3]++;
        }
        else if (str[i] == 'u' || str[i] == 'U') {
            vowelCnt[4]++;
        }
    return *vowelCnt;
    }
}
 

oxrock

Gravity is a myth, the Earth SUCKS!
Well I've been staring at my jank code for ours now and haven't made any progress, so I'm hoping maybe some kind soul will give me an idea as to what's going wrong.

The code is for a challenge on a website I found, just silly stuff to give you practice, etc. Here's the link to the specific challenge.

and my jank python code:
Code:
def find_closest(botx,boty,board):
	current = 0
	bestxy=0
	difference = 0
	best = 500
	for i in board:
		if "d" in i:
			for x in i:
				if x == "d":
					current = [i.index(x),board.index(i)] 
					
					difference =abs(current[0]-botx) + abs(current[1]-boty)
                	if difference < best:
						best = difference
						bestxy = [i.index(x),board.index(i)]
						
	return bestxy

def next_move(posr, posc, board):
    target = find_closest(posr,posc,board) #bestxy
    if board[posr][posc]== "d":
        print "CLEAN"
        return
    if posr < target[0]:
        print "RIGHT"
        return
    if posc > target[1]:
        print "UP"
        return
    if posr > target[0]:
        print "LEFT"
        return
    if posc < target[1]:
        print "DOWN"
        return

Edit: solved, I mixed up row/column's x and y values
 

iapetus

Scary Euro Man
How long did it take most of you to understand Java? I'm taking a beginner's course, but it's still not clicking to me. I'm having a hard time doing assignments that consist of either constructors or loops.

It's less about understanding Java and more about understanding some programming basics; loops are very much the same in most languages that support them, as are constructors, though the syntax and responsibilities might be subtly difference.

Some people will tell you that Java is not the best language to learn these things, for a number of reasons. You *might* benefit from finding a simple tutorial that covers these in a structurally simpler language so you can focus on them more closely without the surrounding structure imposed by Java - once you get the basics, it'll be easy to transfer that understanding to Java.
 

Water

Member
Need some more C++ help.

I'm trying to make a program that takes in a user input, passes it into an array, counts the frequency of a given vowel within the string and then outputs that amount:
C++ has perfectly good strings, so just sticking to them instead of the C-style char arrays would make your life a ton easier. Also, using the std::map data structure would get rid of pretty much all the repetitive code. Below is a working C++11 solution; needs small changes if you have to use C++98.
Code:
string s;
getline(cin, s);
// <- cut string size down to 256 here, if you actually wanted to do that
auto m = map<char, unsigned>();
// count chars into the map
for (char c : s) {
  m[c] += 1;
}
auto vowels = {'a', 'e', 'i', 'o', 'u'};
// print the vowel counts
for (char c : vowels) {
  cout << c << ": " << (m[c] + m[(char)toupper(c)]) << endl;
}
Even if you don't use a map, you can iterate the characters this way. Another way to get the character counts would be to use the std::count or std::count_if algorithms, but it's slightly more work than this.
 

harSon

Banned
C++ has perfectly good strings, so just sticking to them instead of the C-style char arrays would make your life a ton easier. Also, using the std::map data structure would get rid of pretty much all the repetitive code. Below is a working C++11 solution; needs small changes if you have to use C++98.
Code:
string s;
getline(cin, s);
// <- cut string size down to 256 here, if you actually wanted to do that
auto m = map<char, unsigned>();
// count chars into the map
for (char c : s) {
  m[c] += 1;
}
auto vowels = {'a', 'e', 'i', 'o', 'u'};
// print the vowel counts
for (char c : vowels) {
  cout << c << ": " << (m[c] + m[(char)toupper(c)]) << endl;
}
Even if you don't use a map, you can iterate the characters this way. Another way to get the character counts would be to use the std::count or std::count_if algorithms, but it's slightly more work than this.

Trust me, I wish I could use strings. For whatever reason, my professor is super specific with what he wants with a program. The assignment is never just "using what you've learned with arrays and functions, make a program that asks the user for an input and then outputs the frequency count for each vowel." It's always "using this exact main, and these exact function definitions, make blah blah." It makes things infinitely more difficult. To make matters worst, he doesn't tailor the program to stuff we've learned from the book (I'd say from lecture, but the man simply reads off the power point that came with the textbook, providing no further examples), and often times in his specifics, asks for stuff where we're basically forced to learn outside the text. To make matters worst, he was out sick this last week, and is sticking to his policy of not answering questions on homework or labs (what kind of policy is that?). So we're basically left with our dicks in our hands, learning the language on our own efforts Lol.

I'm definitely listening to Ratemyprofessor next quarter....

Having said all that, I'm stuck solving this thing with Chars :| I appreciate the help though, it's always good to know multiple ways to attack an issue.
 
Something like this?
Code:
#include <iostream>
#include <string>

using namespace std;

int countVowels(int [], char []);

int main()
{
  char str[257];
  int vowelCnt[5] = {0, 0, 0, 0, 0};
  cout << "Enter a character string (max 256): ";
  cin.getline (str,257);
  countVowels(vowelCnt, str);
  cout << vowelCnt[0] << endl;
  cout << vowelCnt[1] << endl;
  cout << vowelCnt[2] << endl;
  cout << vowelCnt[3] << endl;
  cout << vowelCnt[4] << endl;

}

int countVowels(int counts[], char str[])
{
    int vowelCnt[5];

    for (int i = 0; str[i] != '\0'; i++) {

        if (str[i] == 'a' || str[i] == 'A') {
            vowelCnt[0]++;
        }
        else if (str[i] == 'e' || str[i] == 'E') {
            vowelCnt[1]++;
        }
        else if (str[i] == 'i' || str[i] == 'I') {
            vowelCnt[2]++;
        }
        else if (str[i] == 'o' || str[i] == 'O') {
            vowelCnt[3]++;
        }
        else if (str[i] == 'u' || str[i] == 'U') {
            vowelCnt[4]++;
        }
    return *vowelCnt;
    }
}

You're passing vowelCnt into the function countVowels and then not using it at all, instead opting to use another declaration of vowelCnt that has nothing in it.

In countVowels change vowelCnt to count and see what you get.
 

oxrock

Gravity is a myth, the Earth SUCKS!
Trust me, I wish I could use strings. For whatever reason, my professor is super specific with what he wants with a program. The assignment is never just "using what you've learned with arrays and functions, make a program that asks the user for an input and then outputs the frequency count for each vowel." It's always "using this exact main, and these exact function definitions, make blah blah." It makes things infinitely more difficult. To make matters worst, he doesn't tailor the program to stuff we've learned from the book (I'd say from lecture, but the man simply reads off the power point that came with the textbook, providing no further examples), and often times in his specifics, asks for stuff where we're basically forced to learn outside the text. To make matters worst, he was out sick this last week, and is sticking to his policy of not answering questions on homework or labs (what kind of policy is that?). So we're basically left with our dicks in our hands, learning the language on our own efforts Lol.

I'm definitely listening to Ratemyprofessor next quarter....

Having said all that, I'm stuck solving this thing with Chars :| I appreciate the help though, it's always good to know multiple ways to attack an issue.
so status quo? :p
 

poweld

Member
Trust me, I wish I could use strings. For whatever reason, my professor is super specific with what he wants with a program. The assignment is never just "using what you've learned with arrays and functions, make a program that asks the user for an input and then outputs the frequency count for each vowel." It's always "using this exact main, and these exact function definitions, make blah blah." It makes things infinitely more difficult. To make matters worst, he doesn't tailor the program to stuff we've learned from the book (I'd say from lecture, but the man simply reads off the power point that came with the textbook, providing no further examples), and often times in his specifics, asks for stuff where we're basically forced to learn outside the text. To make matters worst, he was out sick this last week, and is sticking to his policy of not answering questions on homework or labs (what kind of policy is that?). So we're basically left with our dicks in our hands, learning the language on our own efforts Lol.

I'm definitely listening to Ratemyprofessor next quarter....

Having said all that, I'm stuck solving this thing with Chars :| I appreciate the help though, it's always good to know multiple ways to attack an issue.

i don't know how far along you are in your studies, but as painful as working with c character arrays are, i think it's worth feeling that pain at least once. it's a hassle, but like calvin's father says: "it builds character". but really, it does give you a deeper understanding into the etymology of strings and a greater appreciation for their modern implementations.

on the other hand, if you're forced to do this as a senior after already becoming intimately familiar with c strings, you are in the right for being pissed. either way, get a good grade and then never use them again. make a dartboard with your prof's face in the center.
 
i don't know how far along you are in your studies, but as painful as working with c character arrays are, i think it's worth feeling that pain at least once. it's a hassle, but like calvin's father says: "it builds character". but really, it does give you a deeper understanding into the etymology of strings and a greater appreciation for their modern implementations.

Learning c strings and arrays at the same time as my assembly class really put everything (including pointers) into perspective for me for one of the biggest "holy shit" moments of my education.
 
i don't know how far along you are in your studies, but as painful as working with c character arrays are, i think it's worth feeling that pain at least once. it's a hassle, but like calvin's father says: "it builds character". but really, it does give you a deeper understanding into the etymology of strings and a greater appreciation for their modern implementations.

on the other hand, if you're forced to do this as a senior after already becoming intimately familiar with c strings, you are in the right for being pissed. either way, get a good grade and then never use them again. make a dartboard with your prof's face in the center.

You should definitely use C strings a few times, but IMO, you should learn about them in a dedicated course on C. The worst part about C++ is people programming in some awful abormination that combines the worst parts of C and C++.
 

leroidys

Member
You're passing vowelCnt into the function countVowels and then not using it at all, instead opting to use another declaration of vowelCnt that has nothing in it.

In countVowels change vowelCnt to count and see what you get.
Also the return statement is not being used at all, but in fact makes the function end after the first iteration of the for loop.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
Guys I was wondering if you could give me some insight on my most recent homework assignment. It has to do with abstract classes in Java.
The assignment requires a basic "Vehicle" abstract class to be made, and then a "Car" class be made extending the Vehicle class. Then I need to create a Car
or is it Vehicle?
object which sets the parameters. After that I utilize the abstract methods from Vehicle to print out a description of the car.

I've been have a really hard time wrapping my head around these abstract classes and interfaces, and I'm not quite sure if I understand them fully yet.
Would you mind looking over the code I have come up with so far and letting me know if I'm actually using the classes the way they are meant to be used? I'm getting the right output, but I don't know if it's the correct way to get it.

Beyond my textbook I have been looking at this website and this answer on StackOverflow.

abstract Vehicle class
Code:
public abstract class Vehicle {

    private int wheels;
    private String extColor;
    private String name;
    private int year;

    protected Vehicle() {
    }

    protected Vehicle(int vehWheels, String extColor, String vehName, int vehYear) {
        this.wheels = vehWheels;
        this.extColor = extColor;
        this.name = vehName;
        this.year = vehYear;
    }

    public abstract void getColor();

    public abstract void getDesc();

    public int getWheels() {
        return wheels;
    }

    public String getExtColor() {
        return extColor;
    }

    public String getName() {
        return name;
    }

    public int getYear() {
        return year;
    }

    public void setWheels(int wheels) {
        this.wheels = wheels;
    }

    public void setExtColor(String extColor) {
        this.extColor = extColor;
    }

    public void setName(String name) {
        this.name = name;
    }

    public void setYear(int year) {
        this.year = year;
    }
}
Car class
Code:
public class Car extends Vehicle {

    private int maxMPH;
    private String intColor;

    public void getColor() {
        System.out.println("This car is " + getExtColor() + " with " + intColor + " interior.");
    }

    public void getDesc() {
        System.out.println("The full description of this car is as follows:\n" + getYear() + " " + getName() + ".\n"
            + getExtColor() + " exterior with " + intColor + " interior.\n" + "Max speed of " + maxMPH + "mph on "
                + getWheels() + " wheels");
    }

    public Car(int vehWheels, String extColor, String vehName, int vehYear, int vehMPH, String vehIntColor) {
        setWheels(vehWheels);
        setExtColor(extColor);
        setName(vehName);
        setYear(vehYear);
        maxMPH = vehMPH;
        intColor = vehIntColor;
    }

    public static void main(String[] args) {
        Vehicle car1 = new Car(4, "Black", "Volkswagen", 2001, 135, "Tan");
        car1.getColor();
        car1.getDesc();
    }
}

Thanks in advance.
 

Rapstah

Member
That looks pretty much right, although the assignment would make more sense if the print function was part of the abstract class and the implementations of the information functions were up to the extending classes.

The beauty of abstract classes is that you could run that program for ten years, and then realise that bikes exist, add a Bike class that extends Vehicle, and stick it in an array of Vehicles together with Cars and your program would still work. There's really no deeper realisation about what abstract classes are if you get everything you're doing in the code you've posted.

Another nice thing that courses tend to miss is that you can absolutely extend non-abstract (concrete?) classes too for basically the same benefit. The abstract methods are the only difference.
 

tokkun

Member
You probably shouldn't have "Wheels" as a part of an abstract vehicle class, given that some vehicles do not have wheels - e.g. a boat, a snowmobile, a hanglider, or a tank.

Some people might say "well, just create those as vehicles with zero wheels", but personally I think abstract classes work better when they describe only what is essential to them, rather than trying to anticipate all of the possible child classes and adding methods that are only meant for a subset of children.

An alternative would be to create another abstract class, WheeledVehicle, that inherits from Vehicle, then have Car inherit from that. Of course you also don't want to go overboard with abstraction since it can hurt performance, but then again this is Java so who cares.
 

Granadier

Is currently on Stage 1: Denial regarding the service game future
That looks pretty much right, although the assignment would make more sense if the print function was part of the abstract class and the implementations of the information functions were up to the extending classes.

The beauty of abstract classes is that you could run that program for ten years, and then realise that bikes exist, add a Bike class that extends Vehicle, and stick it in an array of Vehicles together with Cars and your program would still work. There's really no deeper realisation about what abstract classes are if you get everything you're doing in the code you've posted.

Another nice thing that courses tend to miss is that you can absolutely extend non-abstract (concrete?) classes too for basically the same benefit. The abstract methods are the only difference.

Thanks for the help. I think I was trying to look for something deeper with them that there actually was, but your second paragraph finally made things click. I'll go back and modify the classes before turning it in.

You probably shouldn't have "Wheels" as a part of an abstract vehicle class, given that some vehicles do not have wheels - e.g. a boat, a snowmobile, a hanglider, or a tank.

Some people might say "well, just create those as vehicles with zero wheels", but personally I think abstract classes work better when they describe only what is essential to them, rather than trying to anticipate all of the possible child classes and adding methods that are only meant for a subset of children.

An alternative would be to create another abstract class, WheeledVehicle, that inherits from Vehicle, then have Car inherit from that. Of course you also don't want to go overboard with abstraction since it can hurt performance, but then again this is Java so who cares.

The wheels part is a required parameter from the assignment itself. Otherwise I can understand your point about separating it in order to keep it to the basics that are shared.
 
Guys, I'm trying to set up a java bug fixing challenge to test my new Eclipse Code Search tool.

The tool in question is the ability to search using synonyms of a search term.

Basically I want to give a few fellow developers a 5 minute test to see if they can solve the problem or find/fix the bug with the tool (and do a follow up interview).
But I'm not sure what the do about the challenge, how to put it together or where to find a good but easy enough piece of code to use as the challenge.

It doesn't have to be super serious, but it'd be nice to have something worthwhile.
Anyone know of a good example, or website with ready to fix bugs examples?
 

poweld

Member
anyone here been working with scala? i took a new job in january where i'm using it as my primary language. i would say i'm borderline obsessed with it.

my background has been focused in c++ and perl primarily for the last 10 or so years; no java other than some tinkering just to have some basic understanding. scala feels like the marriage of two languages - one being strongly typed and compiled, the other an easy to write scripting language, with some functional programming spiciness on top (immutability is starting to feel really good).

in a day i find myself being able to write more quality code than ever before. writing with OO, concurrency, and safety has never been easier. the language just seems to stay out of my way, and that is such a wonderful feeling.

/blog post
 

Water

Member
Trust me, I wish I could use strings. For whatever reason, my professor is super specific with what he wants with a program. The assignment is never just "using what you've learned with arrays and functions, make a program that asks the user for an input and then outputs the frequency count for each vowel." It's always "using this exact main, and these exact function definitions, make blah blah."
...
Having said all that, I'm stuck solving this thing with Chars :| I appreciate the help though, it's always good to know multiple ways to attack an issue.
The function prototype only constrains what is supposed to go in and out. If you haven't been given additional constraints, you can always convert the data inside the function to a form that's easier to process. The core of the function could be written almost exactly like I showed earlier.

I want to ask whether the function prototype you show is exactly the one mandated by the exercise, and if so, what the int return value is supposed to contain.
 

0xCA2

Member
I benefited greatly by going through a pseudocode-based programming logic and design book with very understandable (and concise) explanations when I first started programming. My first language was Python but this didn't matter in the grand scheme of things. I suppose because I read this book, I didn't have a problem going over to Java ( in fact, the book came with language companion documents for java, which I used). I read this book because of a class I took that didn't count toward my major and wasn't required.

Maybe it should be. This was years ago and I haven't even taken Programming 1 yet (due to Calculus), but I couldn't imagine going into it cold and having to learn all of that stuff within 3 1/2 months.
 

upandaway

Member
Well okay, I thought I got it, but I don't get it after all. Unit tests are just weird. I pretty much have to create constructors or factories that take every single variable, or have setters for every variable, so I can mock them out and have precise tests. But that's silly (especially for immutable objects), I'd rather just stick some print line somewhere to confirm things work. I don't think my normal thinking process is that different from doing unit tests first either because I'm already doing it internally for almost everything.

From what I've read I could really use integration tests but eh.
 
Well okay, I thought I got it, but I don't get it after all. Unit tests are just weird. I pretty much have to create constructors or factories that take every single variable, or have setters for every variable, so I can mock them out and have precise tests. But that's silly (especially for immutable objects), I'd rather just stick some print line somewhere to confirm things work. I don't think my normal thinking process is that different from doing unit tests first either because I'm already doing it internally for almost everything.

Unit tests are pretty much a necessity for automatic builds. As it would happen, most build tools have support for the common unit testing frameworks. By putting in unit tests, you can pretty much know if a change broke the build.
 

tokkun

Member
Well okay, I thought I got it, but I don't get it after all. Unit tests are just weird. I pretty much have to create constructors or factories that take every single variable, or have setters for every variable, so I can mock them out and have precise tests. But that's silly (especially for immutable objects), I'd rather just stick some print line somewhere to confirm things work. I don't think my normal thinking process is that different from doing unit tests first either because I'm already doing it internally for almost everything.

From what I've read I could really use integration tests but eh.

Why do you need to mock every variable?

Ideally, the only things you should be mocking in a unit test are
1. External resources that aren't available in the test environment (e.g., a remote server, a hardware device, a database)
2. Pieces of code that have really large memory or CPU requirements, such that they would make the unit test unbearably slow
3. Pieces of code that have an inordinately high number of external dependencies, such that they make it too difficult to isolate the behavior of the unit under test

You should do both unit and integration tests. The problem with only relying on integration tests, though is that the test coverage is usually smaller, it is harder to test error cases, and it is more difficult to pinpoint the point of failure.
 

Remyzero

Member
I benefited greatly by going through a pseudocode-based programming logic and design book with very understandable (and concise) explanations when I first started programming. My first language was Python but this didn't matter in the grand scheme of things. I suppose because I read this book, I didn't have a problem going over to Java ( in fact, the book came with language companion documents for java, which I used). I read this book because of a class I took that didn't count toward my major and wasn't required.

Maybe it should be. This was years ago and I haven't even taken Programming 1 yet (due to Calculus), but I couldn't imagine going into it cold and having to learn all of that stuff within 3 1/2 months.

What is the name or author of the book?
 

upandaway

Member
Not every variable, but the variables that load data from files all need to be mocked (even if I wanted to, trying to load files through JUnit in LibGDX just gives a null error). And I don't know if I designed things wrong or something, but those variables are referenced almost everywhere in the project, and most of them are created inside the objects and not passed through constructors because it would be a huge mess otherwise.

There are some things I can test pretty cleanly but they're kinda scarce, and they're mostly things that would be easily wrong on screen if they ever broke in the future refactoring.

Unit tests are pretty much a necessity for automatic builds. As it would happen, most build tools have support for the common unit testing frameworks. By putting in unit tests, you can pretty much know if a change broke the build.
I can understand that, but only if it's a big project with a big team.. even with an automatic build, if it's a personal project, it's still not worth the effort I think. The build changelog should be enough, dunno.
 
I can understand that, but only if it's a big project with a big team.. even with an automatic build, if it's a personal project, it's still not worth the effort I think. The build changelog should be enough, dunno.

Err, the purpose of automatic building is to catch errors early. Even on personal projects, it's best to solve bugs as close to when they are introduced as possible.

Edit:

Read through the first part of this reply. The purpose of unit testing is to test the public api. You should not be checking individual values unless they are return results from a public function. You should never be checking internal state of a method or class.
 

upandaway

Member
You mean that the automatic building builds the unit tests automatically too? Because I was weighting in the effort it takes to write those.
 
You mean that the automatic building builds the unit tests automatically too? Because I was weighting in the effort it takes to write those.

If you set up the ant build file or mavens build file correctly, it should always be running the unit tests every time a package is built automatically or not.
 

upandaway

Member
Read through the first part of this reply. The purpose of unit testing is to test the public api. You should not be checking individual values unless they are return results from a public function. You should never be checking internal state of a method or class.
Man, I understand you, and I think that's what I've been trying to do, but I still can't wrap my head around it. I think it comes down to these things appearing a lot more useful with a long term POV, which I super don't have, so I might not see the point until it screws me over not doing it.
 

samueeL

Banned
Hey! First timer on this topic and I really need simple javascript help, hope someone can help me!


So we were given this simple HTML code
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link rel="StyleSheet" href="style.css" type="text/css" />
<script type="text/javascript" src="javascript.js"></script>
<title>Random</title>
</head>
<body>

<h1>Random</h1>

<p>Write tables width and length.</p>

<form action="">
<fieldset>
<p><label>Width <input type="text" name="width" /></label></p>
<p><label>Length <input type="text" name="height" /></label></p>
</fieldset>
<p><input type="submit" value="Make randomized table" /></p>
</form>

</body>
</html>

And what our task is:

1. Can't touch HTML code, everything has to be done in javascript and css files
2. Have to be able to give tables height and width and then then when button is pressed it will make table with those width and height.
3. Table should get filled with random numbers
4. no INNER.html stuff... Every example online uses that

I'll really need to get this task done, need the course points badly. Thanks so much if someone can shed even tiny bit of light into this, our teacher really sucks and his lectures are terrible...

Any tips on how to get control of the button for example and make it to do something in javascript?
 

Slavik81

Member
Read through the first part of this reply. The purpose of unit testing is to test the public api. You should not be checking individual values unless they are return results from a public function. You should never be checking internal state of a method or class.
I wouldn't say always. Mocks are primarily used during unit testing to verify things that are not really a part of the public interface of a class. They're used to test the interactions between the class under test and it's dependencies.

Not every variable, but the variables that load data from files all need to be mocked (even if I wanted to, trying to load files through JUnit in LibGDX just gives a null error). And I don't know if I designed things wrong or something, but those variables are referenced almost everywhere in the project, and most of them are created inside the objects and not passed through constructors because it would be a huge mess otherwise.

There are some things I can test pretty cleanly but they're kinda scarce, and they're mostly things that would be easily wrong on screen if they ever broke in the future refactoring.


I can understand that, but only if it's a big project with a big team.. even with an automatic build, if it's a personal project, it's still not worth the effort I think. The build changelog should be enough, dunno.
That sounds a bit messy. Testing as you go ensures that every bit of code has at least two users: the original reason why you wrote it, and the test. In that way, testing helps prod you towards more modular, reusable designs.

I'm not a TDD true believer. But there's definitely value in testing even on fairly small projects. If you start early, it doesn't have to be difficult. Bolting tests on afterwards is twice the work for half the reward.
 

Exuro

Member
Could someone that is familiar with page tables explain to me what to do if a page table has more entries than there are frames in physical memory? I'm trying to just work this example out for this single page table sim I'm working on and its been a rather busy week and my brain is fried.

I take in 32 bit addresses and am given that the frame size is 1KB and physical memory is 1GB. The number of frames is 1GB/1KB = 1MB and the number of page table entries is 2^(32-offset) = 4MB. How do I deal with the page table having more entries than there are frames of memory? Do I limit the page entries to 1MB?
 

Rapstah

Member
Could someone that is familiar with page tables explain to me what to do if a page table has more entries than there are frames in physical memory? I'm trying to just work this example out for this single page table sim I'm working on and its been a rather busy week and my brain is fried.

I take in 32 bit addresses and am given that the frame size is 1KB and physical memory is 1GB. The number of frames is 1GB/1KB = 1MB and the number of page table entries is 2^(32-offset) = 4MB. How do I deal with the page table having more entries than there are frames of memory? Do I limit the page entries to 1MB?

I think I understand what you're asking for and you're looking at the solution for virtual memory. You shift pages into physical memory from storage to pretend like you have 4 GB of physical memory.

Also, I'm pretty sure you have 100000 (a hundred thousand) and 4000000 (four hundred thousand) frames and page table entries respectively and not "one megabyte frames" because you're dividing two numbers of the same unit.
 

Kad5

Member
Hey guys I decided to finally do some programming assignments at home. I put eclipse on an external hard drive. I seem to be having some issues with my includes? I'm trying to make a priority queue.

Code:
#ifndef QUEUE_H_
#define QUEUE_H_

using namespace std;
#include <cstdlib>
#include <iostream>
#include <queue>
#include <list>
#include<string>


//priority_queue<int> p1;                      // a priority queue of integers
                                           // a priority queue of points with left-to-right order

struct patient{
	string name;
	int time;
	bool islifeThreat;
};


class PriorityQueue {                    // priority-queue interface
public:
	PriorityQueue();
	int size();                       // number of elements
	bool empty();                      // is the queue empty?
	void insert(patient p);                 // insert element
    patient min();                    // minimum element
	void removeMin();                        // remove minimum
	virtual ~PriorityQueue();                // deconstructor
private:
	list<patient> patientList;                          // priority queue contents
	//C isLess;                                // less-than comparator
};




#endif /* QUEUE_H_ */

I'm using a mac right now if that helps any.
 
Could someone that is familiar with page tables explain to me what to do if a page table has more entries than there are frames in physical memory? I'm trying to just work this example out for this single page table sim I'm working on and its been a rather busy week and my brain is fried.

I take in 32 bit addresses and am given that the frame size is 1KB and physical memory is 1GB. The number of frames is 1GB/1KB = 1MB and the number of page table entries is 2^(32-offset) = 4MB. How do I deal with the page table having more entries than there are frames of memory? Do I limit the page entries to 1MB?

Oh god, this gives me flashbacks to Operating Systems class.

I actually found the assignment description:

The third phase of Nachos is to investigate the use of caching. In this assignment we use caching for two purposes. First, we use a software-managed translation lookaside buffer (TLB) as a cache for page tables to provide the illusion of fast access to virtual page translation over a large address address space. Second, we use memory as a cache for disk, to provide the abstraction of an (almost) unlimited virtual memory size, with performance close to that provided by physical memory. We provide no new code for this assignment (the only change is that you need to compile with the '-DVM -DUSE_TLB' flags - which is already set if you compile from the vm directory); your job is to write the code to manage the TLB and to implement virtual memory. You can edit files in the userprog directory, but you must compile and run Nachos from the vm directory.

Page tables were used in assignment 2 to simplify memory allocation and to isolate failures from one address space from affecting other programs. For this assignment, the hardware knows nothing about page tables. Instead it only deals with a software-loaded cache of page table entries, called the TLB. On almost all modern processor architectures, a TLB is used to speed address translation. Given a memory address (an instruction to fetch, or data to load or store), the processor first looks in the TLB to determine if the mapping of virtual page to physical page is already known. If so (a TLB 'hit'), the translation can be done quickly. But if the mapping is not in the TLB (a TLB 'miss'), page tables and/or segment tables are used to determine the correct translation. On several architectures, including Nachos, the DEC MIPS and the HP Snakes, a 'TLB miss' simply causes a trap to the OS kernel, which does the translation, loads the mapping into the TLB and re-starts the program. This allows the OS kernel to choose whatever combination of page table, segment table, inverted page table, etc., it needs to do the translation (which is what you get to do). On systems without software-managed TLB's, the hardware does the same thing as the software, but in this case, the hardware must specify the exact format for page and segment tables. Thus, software managed TLB's are more flexible, at a cost of being somewhat slower for handling TLB misses. If TLB misses are very infrequent, the performance impact of software managed TLB's can be minimal.

The illusion of unlimited memory is provided by the operating system by using main memory as a cache for the disk. For this assignment, page translation allows us the flexibility to get pages from disk as they are needed. Each entry in the TLB has a valid bit: if the valid bit is set, the virtual page is in memory. If the valid bit is clear or if the virtual page is not found in the TLB, a software page table is needed to tell whether the page is in memory (with the TLB to be loaded with the translation), or the page must be brought in from disk. In addition, the hardware sets the use bit in the TLB entry whenever a page is referenced and the dirty bit whenever the page is modified.

When a program references a page that is not in the TLB, the hardware generates a TLB exception, trapping to the kernel (eventually reaching the exceptionHandler() function). The operating system kernel then checks its own page table. If the page is not in memory, it reads the page in from disk, sets the page table entry to point to the new page, sets the TLB correctly, and then resumes the execution of the user program. Of course, the kernel must first find space in memory for the incoming page, potentially writing some other page back to disk, if it has been modified.

As with any caching system, performance depends on the policy used to decide which things are kept in memory and which are only stored on disk. On a page fault, the kernel must decide which page to replace; ideally, it will throw out a page that will not be referenced for a long time, keeping pages in memory those that are soon to be referenced

This assignment was the longest one in that class and it was expected that 2 of the 3 group members would work on it (the third guy had to implement networking). When I took the class this assignment was due slightly after spring break, so the guy who was supposed to help me went to Cabo while I spent my spring break trying to code this (and not going home to see my dog before he passed away).

Fun times!
 

Slavik81

Member
Hey guys I decided to finally do some programming assignments at home. I put eclipse on an external hard drive. I seem to be having some issues with my includes? I'm trying to make a priority queue.

...

I'm using a mac right now if that helps any.
You need a space before <string>
 

hateradio

The Most Dangerous Yes Man
Hey! First timer on this topic and I really need simple javascript help, hope someone can help me!


So we were given this simple HTML code
And what our task is:

1. Can't touch HTML code, everything has to be done in javascript and css files
2. Have to be able to give tables height and width and then then when button is pressed it will make table with those width and height.
3. Table should get filled with random numbers
4. no INNER.html stuff... Every example online uses that

I'll really need to get this task done, need the course points badly. Thanks so much if someone can shed even tiny bit of light into this, our teacher really sucks and his lectures are terrible...

Any tips on how to get control of the button for example and make it to do something in javascript?
If you're really new to JavaScript, it's going to be quite difficult. If you have to create a table, you use document.createElement('table') and use the same method to make TRs and TDs -- if you need to actually add that. To set text on an element you can use myElement.appendChild(document.createTextNode('some text')). I don't know if you can use textContent or innerText or innerHTML just to set text, which would make it a bit easier.

To attach an element to another element you use myElement.appendChild(otherElement).

You can select elements with JavaScript using document.getElementsByTagName() (this finds all the elements of a particular tag type) or document.getElementsByName (this uses the name property on some elements). (I don't know if you can use some of the newer methods like document.querySelector.) Note that it returns a node list (like an array) of elements, so you'll have to select the right one using an index, eg: elements[0] or elements[1] if elements is a node list. You may be able to use document.forms which returns a list of form elements on the page. If you use this, you can reference a form's elements using their name attribute, eg: document.forms[0].elementName.

Note that you can use other elements and use getElement* methods on them, eg: myElement.getElementById('someElement').

Once you find the input, then you add a click event, which is a function.

Code:
// create a table
var table = ???;

// set the values to random numbers
???

// find the submit button
var submitButton = ???;

submitButton.onclick = function () {
    // set table's height and width to the values in the inputs
    table.height = ???; // find the height input and get its value
    table.width = ???; // similar situation

    // you really only need to do this once
    // wrap it in an if to test if the table is already on the page, if you want
    document.body.appendChild(table);
};
 

tokkun

Member
Fixed that. the 'std' in namespace is showing an error and all of my includes are showinf errors. any reason why that might be?

As a side note, it is usually considered bad practice to have a using directive in a header file. I would suggest that you remove it and use fully qualifed declarations.

That is
Code:
string a;

becomes
Code:
std::string a;

I don't know if that will fix your problem, but it's a good idea to do it either way.

Since you mention that all of your include statements are showing errors, the most likely issue is that you probably do not have the path to your standard libraries set in Eclipse.
 
Guys, I need good programming music. What do you all listen to when in the zone?

I find video game soundtracks are often really good for me. Probably because they're generally meant to be background music, so they aren't too distracting for me. I can't program to anything with lyrics...

Speaking of, I find that regardless of what music I'm listening to there are times where I have to mute everything. Generally when I'm focusing on a really tricky or complicated problem. Anybody else experience this, or are you able to tune out the music when you need 100% concentration?
 

skynidas

Banned
I find video game soundtracks are often really good for me. Probably because they're generally meant to be background music, so they aren't too distracting for me. I can't program to anything with lyrics...

Speaking of, I find that regardless of what music I'm listening to there are times where I have to mute everything. Generally when I'm focusing on a really tricky or complicated problem. Anybody else experience this, or are you able to tune out the music when you need 100% concentration?

muting absolutely everything makes me feel weird. i like the background sound and it actually helps me concentrate 100%. but that depends on each individual
 
As a side note, it is usually considered bad practice to have a using directive in a header file. I would suggest that you remove it and use fully qualifed declarations.

That is
Code:
string a;

becomes
Code:
std::string a;

I don't know if that will fix your problem, but it's a good idea to do it either way.

Since you mention that all of your include statements are showing errors, the most likely issue is that you probably do not have the path to your standard libraries set in Eclipse.
Additional commentary:

tbh there's probably not any harm in doing a using std::string or using std::vector. If somebody is calling their class string or vector they're asking for pain anyway. ;p

But don't ever (ever) do using namespace std, or anything of the sort, in a header file. You will be sad.
 

Linkhero1

Member
I'm working on a Lisp Expression Evaluator and everything seems to be working fine, but for some reason it ignores extra parenthesis and doesn't throw a LispExprException.

For example, if I have the following expression: (- 10 2 (/ 12 2)))

it will evaluate to 2 rather than throw an exception. I don't want to post my code for personal reasons but I was wondering if anyone could give me some insight or ideas. This is in Java.
 
Top Bottom