• 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

Tristam

Member
Anyone have experience with Apache's mod_rewrite for clean URLs? It strikes me as sort of...backwards, in a way. Perhaps not backwards, but more like a one-way street when you really want it to be two-way. For example, if you want it to map http://www.example.com/users.php?userid=324 to http://www.example.com/users/testuser, it's all well and good if someone clicks the latter as a hyperlink--the mapping performs as intended, and the user sees a clean URL. But say you passed in a query string to the URL via a form, in which case your URL is already (and unavoidably) going to be in the 'ugly' form. In this case, I want the clean URL to be displayed to the user. Can this be done using mod_rewrite? It seems to me that I have no choice but to implement (in conjunction with mod_rewrite) a redirect using regex in server-side code (PHP in my case), which will then produce the clean URL.

If I'm missing something in mod_rewrite (which I'm very new to), please let me know. I'd like to implement this functionality just in Apache if possible without touching the application layer.
 

Orrichio

Member
I am in a intro to CS course and we are learning JAVA.

At the moment we are doing arrays and we were tasked with completing methods that will implement algorithms we develop for a game of UNO.

Our book is awful (imo), it's some online textbook from some other university and my Professor doesn't really fulfill my teaching needs...

Is there a text you could recommend online or hardcopy that would be good? Arrays are giving me a tough time and I believe a lot has to do with my text/professor.

Here is my text: http://math.hws.edu/javanotes/c7/s5.html


Code:
import java.util.List;

public class *****_UnoPlayer implements UnoPlayer {

    /**
     * play - This method is called when it's your turn and you need to
     * choose what card to play.
     *
     * The hand parameter tells you what's in your hand. You can call
     * getColor(), getRank(), and getNumber() on each of the cards it
     * contains to see what it is. The color will be the color of the card,
     * or "Color.NONE" if the card is a wild card. The rank will be
     * "Rank.NUMBER" for all numbered cards, and another value (e.g.,
     * "Rank.SKIP," "Rank.REVERSE," etc.) for special cards. The value of
     * a card's "number" only has meaning if it is a number card. 
     * (Otherwise, it will be -1.)
     *
     * The upCard parameter works the same way, and tells you what the 
     * up card (in the middle of the table) is.
     *
     * The calledColor parameter only has meaning if the up card is a wild,
     * and tells you what color the player who played that wild card called.
     *
     * Finally, the state parameter is a GameState object on which you can 
     * invoke methods if you choose to access certain detailed information
     * about the game (like who is currently ahead, what colors each player
     * has recently called, etc.)
     *
     * You must return a value from this method indicating which card you
     * wish to play. If you return a number 0 or greater, that means you
     * want to play the card at that index. If you return -1, that means
     * that you cannot play any of your cards (none of them are legal plays)
     * in which case you will be forced to draw a card (this will happen
     * automatically for you.)
     */
    public int play(List<Card> hand, Card upCard, Color calledColor,
        GameState state) {
        for(int x = 0;x<hand.length();x++){
            if(hand.get(x).getColor == upCard.getColor()){
                return x;
                break;
            }
            else if(hand.get(x).getNumber() == upCard.getNumber()){
                return x;
                break;
            }
            else if(hand.get(x).getRank() == upCard.getRank()){
                return x;
                break;
            }
            else 
                return -1;
        }
    
       
    }

Above is a snippet of code that I am supposed to tease out the rank,color and number of the card faced up and crawl through each item in the list to see which index has a playable card. I doubt this is enough to really help, but , maybe it could give an idea of how incorrect I am and how to adjust recommendations....

Thanks!
 
I am in a intro to CS course and we are learning JAVA.

At the moment we are doing arrays and we were tasked with completing methods that will implement algorithms we develop for a game of UNO.

Our book is awful (imo), it's some online textbook from some other university and my Professor doesn't really fulfill my teaching needs...

Is there a text you could recommend online or hardcopy that would be good? Arrays are giving me a tough time and I believe a lot has to do with my text/professor.

Here is my text: http://math.hws.edu/javanotes/c7/s5.html


Code:
import java.util.List;

public class *****_UnoPlayer implements UnoPlayer {
    public int play(List<Card> hand, Card upCard, Color calledColor,
        GameState state) {
        for(int x = 0;x<hand.length();x++){
            if(hand.get(x).getColor == upCard.getColor()){
                return x;
                break;
            }
            else if(hand.get(x).getNumber() == upCard.getNumber()){
                return x;
                break;
            }
            else if(hand.get(x).getRank() == upCard.getRank()){
                return x;
                break;
            }
            else 
                return -1;
        }
    }

Above is a snippet of code that I am supposed to tease out the rank,color and number of the card faced up and crawl through each item in the list to see which index has a playable card. I doubt this is enough to really help, but , maybe it could give an idea of how incorrect I am and how to adjust recommendations....

Thanks!
First thing, you don't need a break statement after a return (it is unreachable since the method stops executing once it arrives at a return statement). Second, your code is almost right. What helps me a ton when I program and I'm stuck is writing down the problem on paper and trying to visualize it, or if that doesn't work, write an exact specification of the problem you're trying to solve. A problem well stated is a problem half solved. As a hint, try looking at when exactly your return statements return. Hope that helps.
 
So I have my first internship interview tomorrow Not sure what to expect as far as programming (if there will be any at all) :/ I've done interview questions quite a bit these last few months and I am fairly set on my basic algorithms. I am just super burnt out from the hackathon I was at this weekend.

Any resources anyone would recommend for some last minute interview practice? I already had the one with STAR questions so only programming stuff really.
 

Orrichio

Member
First thing, you don't need a break statement after a return (it is unreachable since the method stops executing once it arrives at a return statement). Second, your code is almost right. What helps me a ton when I program and I'm stuck is writing down the problem on paper and trying to visualize it, or if that doesn't work, write an exact specification of the problem you're trying to solve. A problem well stated is a problem half solved. As a hint, try looking at when exactly your return statements return. Hope that helps.


Yes, my code was almost right. Sublime wasn't saving my changes I was editing because I accidentally out the file in the wrong directory.... haha!

Thank you for your input, though!
 

Shearie

Member
Can someone help me out. I'm doing the "Learn Python the hard way" book and I can't figure something out.

How come when I put anything that's not a number into this...

print "This room is full of gold. How much do you take?"

next = raw_input("> ")

if next < '50':
print "Nice, you're not greedy, you win!"
exit(0)
elif next >= '50':
dead("You greedy bastard!")
else:
dead("Man, learn to type a number.")

...it doesn't run "else"? It just runs the "elif" for anything other than a number. This is driving me MAD.

EDIT: For some reason it's not showing the code as tabbed right but it is in my text editor.
 

Tamanon

Banned
Can someone help me out. I'm doing the "Learn Python the hard way" book and I can't figure something out.

How come when I put anything that's not a number into this...



...it doesn't run "else"? It just runs the "elif" for anything other than a number. This is driving me MAD.

EDIT: For some reason it's not showing the code as tabbed right but it is in my text editor.

You need it to be input instead of raw_input.

Raw_input grabs a string, when you need an integer to do comparisons like that.
 

Shearie

Member
You need it to be input instead of raw_input.

Raw_input grabs a string, when you need an integer to do comparisons like that.

When I do that it gives me a "NameError" and says whatever I typed in is not defined when I put anything other than a number in the Terminal. What I want it to do is use the "if" or "elif" when entering a number and for it to use the "else" when it's anything other than a number.
 

Tamanon

Banned
When I do that it gives me a "NameError" and says whatever I put in is not defined when I put anything other than a number in the Terminal. What I want it to do is use the "if" or "elif" when entering a number and for it to use the "else" when it's anything other than a number.

That's going to be tough. You'll have to take a string and try to convert it to an int. Then if it succeeds, do your compare, and if it throws an exception, do your "numbers only please".
 
It's not recommended to use input(). It's not safe, as it tries to evaluate the input. You should almost always use raw_input(). (Unless you're using Python 3, because raw_input() was renamed to input(), and the input() from Python 2 is gone. But since you're using raw_input(), you must be using Python 2, so don't worry about that for now.)

Your current code just takes the number as a string, and is comparing them lexicographically to the string '50'. You definitely want to convert them to integers before you do an integer comparison. Your current code is never going to get to the "else" condition, because the string is always either going to be greater then or equal to '50' or less than '50', since it's all just strings.

The best way (in my opinion) is to accept the input with raw_input(), check to see if it's a digit, and if it's not then return or handle it however you want. Then finish the rest of your code.

Code:
print "This room is full of gold. How much do you take?"
next = raw_input("> ")

try:
    next = int(next)
except ValueError:
    print "Man, learn to type a number."
    return

if next < 50:
    print "Nice, you're not greedy, you win!"
else:
    print "You greedy bastard!"
 

usea

Member
Programming GAF I need extra practice with 2D arrays in C++. Where could I go find more practice outside of my regular class work?
You could make up something.

Make a version of the game connect four, except two computers play each other and they just place pieces randomly. It should print the board every turn, and detect when somebody has placed 4 pieces in a row (horizontally, vertically, or diagonally).
 

Shearie

Member
It's not recommended to use input(). It's not safe, as it tries to evaluate the input. You should almost always use raw_input(). (Unless you're using Python 3, because raw_input() was renamed to input(), and the input() from Python 2 is gone. But since you're using raw_input(), you must be using Python 2, so don't worry about that for now.)

Your current code just takes the number as a string, and is comparing them lexicographically to the string '50'. You definitely want to convert them to integers before you do an integer comparison. Your current code is never going to get to the "else" condition, because the string is always either going to be greater then or equal to '50' or less than '50', since it's all just strings.

The best way (in my opinion) is to accept the input with raw_input(), check to see if it's a digit, and if it's not then return or handle it however you want. Then finish the rest of your code.

Code:
print "This room is full of gold. How much do you take?"
next = raw_input("> ")

try:
    next = int(next)
except ValueError:
    print "Man, learn to type a number."
    return

if next < 50:
    print "Nice, you're not greedy, you win!"
else:
    print "You greedy bastard!"

Thanks! With only a slight modification to that code it now works exactly how I want it to. I would have never thought of using "try" and "except" since I haven't gotten to that in my lessons yet.
 

Dr_Swales

Member
Programming GAF I need extra practice with 2D arrays in C++. Where could I go find more practice outside of my regular class work?

That's a great program to try and implement yourself, to familiarise yourself with arrays. Look in the article Water linked to and focus on the four rules:

  1. Any live cell with fewer than two live neighbours dies, as if caused by under-population.
  2. Any live cell with two or three live neighbours lives on to the next generation.
  3. Any live cell with more than three live neighbours dies, as if by overcrowding.
  4. Any dead cell with exactly three live neighbours becomes a live cell, as if by reproduction.

Try and implement a program that displays the population and runs in the console which updates to display each generation.
 

Water

Member
Programming GAF I need extra practice with 2D arrays in C++. Where could I go find more practice outside of my regular class work?
BTW, I'm presuming you mean raw "C-style" arrays. The vast majority of the time you should be using std::vector and std::array instead - do you know how to use those yet? If not, I recommend getting comfortable with them first. The C array/pointer stuff doesn't really help you except in rare circumstances, and it becomes much easier to learn later once you are comfortable with using vector, array and some other stuff like unique_ptr.
 

maeh2k

Member
I'm working on a C# program and need some help with threads.

Right now the program is entirely event-based. I'm getting some data from a library by listening to events from that library. After the data is processed another event is triggered and the data is passed on to other parts of the program.
The issue is, that basically the entire program runs on the thread from that library, since all event handlers are executed on the thread that triggered the first event.

I'd like to decouple the rest of the program from that library and let the library threads do their own thing. However, I'm not sure how to do it.
So I would still listen to the events of that library and the listeners would still run on the thread of the library, but then I want another thread to take care of the following events.

What's the best way to accomplish that?
 
Guys I have no where else to go, I am in a 2nd year java course (first time programming in java) and I am getting a NullPointer Error when reading data from a file into a hashmap. It appears to be after it has read all the lines in the file as my output is
Code:
run:
callnumber   QA76.73.J38S265
Exception in thread "main" java.lang.NullPointerException
authors   Walter Savitch, Kenrich Mock 
title   Absolute Java 
publisher   Addison-Wesley 
year   2009
	at librarysearch.FileIO.readDataFromFile(callnumber   P98.C6116
FileIO.java:160)
	at librarysearch.FileIO.main(FileIO.java:405)
title   Computational Linguistics
organization  Association for Computational Linguistics
year   2008
Java Result: 1
BUILD SUCCESSFUL (total time: 1 second)

I am guessing it is a simple error but I have spent 10 hours trying to figure it out.
The data file it is reading is something like this.

[type = book]
callnumber = 5454asdsda
authors = Peter Pan
title = dog and cat

[type = book]
.....
here is the function.
Code:
 public ArrayList<HashMap<String, String>> readDataFromFile(){
        this.openFileForReading();
        ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
        try{
            String line;
            
            while ((line = this.reader.readLine()) != null){ 
            
                while (!(line.equals(""))){
                    
                    if (line.equals("[type = book]")){
                        HashMap<String, String> data= new HashMap<String, String>();
                        line = this.reader.readLine();
                        
                        while (!(line.equals(""))){
          
                            String tokens[] = line.split("=");
                            data.put(tokens[0], tokens[1]);
                            System.out.println(tokens[0] + " " + tokens[1]);
                            line = this.reader.readLine();
                            
                        }
                       list.add(data);
                    }
 
                }
                
            }
        }
        catch (IOException exception) {
            list = null;
            System.err.println("(FileIO): " + exception);            
        }
        // Close the file when we have finished reading or if an error occurs
        finally {
            try {
                this.reader.close();                
            } catch (IOException exception) {
                System.err.println("(FileIO): " + exception);
            }
        }
                
        return list;
    }
 

usea

Member
I'm working on a C# program and need some help with threads.

Right now the program is entirely event-based. I'm getting some data from a library by listening to events from that library. After the data is processed another event is triggered and the data is passed on to other parts of the program.
The issue is, that basically the entire program runs on the thread from that library, since all event handlers are executed on the thread that triggered the first event.

I'd like to decouple the rest of the program from that library and let the library threads do their own thing. However, I'm not sure how to do it.
So I would still listen to the events of that library and the listeners would still run on the thread of the library, but then I want another thread to take care of the following events.

What's the best way to accomplish that?
Well, it depends on the structure of the rest of your program.

1) Do you want it to be sitting there asleep, and some work gets triggered by these events firing? And when multiple events fire, the new events have to wait for the previous events' work to finish before they get a chance?

2) Or do you want it to just run some code when an event fires, but not block the library's thread? If multiple events fire quickly, there will be concurrent work going on in your code.

2 is much simpler than 1 if you're not sharing data. If you want to do 2, basically just throw your code inside of a Task. Something like this:
Code:
public void LibraryEventFired()
{
  Task.Factory.StartNew(() =>
  {
    CallMyCode();
  }).ContinueWith((t) =>
  {
    HandleErrors(t.Exception);
  }, TaskContinuationOptions.OnlyOnFaulted);
}

public void HandleErrors(Exception ex)
{
  //handle any exceptions that occur inside of CallMyCode
}

But that won't work if running multiple copies of CallMyCode() at the same time will cause problems. For example if it's an instance of an object that has some private list or dictionary that it mutates. That will blow up. Concurrency is a tricky thing.

If you want to use the code above, but you want to just prevent the code from executing simultaneously, you can put a lock around CallMyCode(). Like this:
Code:
private object myLock = new object();

public void LibraryEventFired()
{
  Task.Factory.StartNew(() =>
  {
    lock(myLock)
    {
      CallMyCode();
    }
  }).ContinueWith((t) =>
  {
    HandleErrors(t.Exception);
  }, TaskContinuationOptions.OnlyOnFaulted);
}

But if the rate at which events fire is faster than the rate at which your code completes, then you'll have a bunch of tasks that are all contesting the lock. Over time they'll build up and things will get slow and dumb.

Option 1 is the more robust solution. Basically requires you to set up a thread or task when the program starts, but then sleep on a signal (ManualResetEventSlim). Then when your library event fires, set the signal, which wakes up your main thread to do some work. Then you need a stop method which will stop the thread. You probably need a cancellation token to abort any work when stop is called. You might need another signal, too. It gets a little complicated. If you need this I could help you, but it's not trivial.

btw this is the best page ever on threading in C#: Threading in C#
 

AngryMoth

Member
Ugh, absolutely bricking it over an assessment I've been given this week. Basically we have 3 weeks to design and implement an online magazine from scratch. So layout, user accounts system, search, comments, contents management/peer review system for editors, etc. very intimidating considering most of us (including me!) have not done any web before stuff apart from the self study we were told to do over the last month.

So I might be popping in here with questions once I figure out how to get started :p
 
Ugh, absolutely bricking it over an assessment I've been given this week. Basically we have 3 weeks to design and implement an online magazine from scratch. So layout, user accounts system, search, comments, contents management/peer review system for editors, etc. very intimidating considering most of us (including me!) have not done any web before stuff apart from the self study we were told to do over the last month.

So I might be popping in here with questions once I figure out how to get started :p

OUCH. 0_0 Best of luck.
 

phoenixyz

Member
Ugh, absolutely bricking it over an assessment I've been given this week. Basically we have 3 weeks to design and implement an online magazine from scratch. So layout, user accounts system, search, comments, contents management/peer review system for editors, etc. very intimidating considering most of us (including me!) have not done any web before stuff apart from the self study we were told to do over the last month.

So I might be popping in here with questions once I figure out how to get started :p
Wat.

You are supposed to do that alone without prior knowledge?
 

maeh2k

Member
Well, it depends on the structure of the rest of your program.

1) Do you want it to be sitting there asleep, and some work gets triggered by these events firing? And when multiple events fire, the new events have to wait for the previous events' work to finish before they get a chance?

2) Or do you want it to just run some code when an event fires, but not block the library's thread? If multiple events fire quickly, there will be concurrent work going on in your code.

2 is much simpler than 1 if you're not sharing data. If you want to do 2, basically just throw your code inside of a Task. Something like this:
Code:
public void LibraryEventFired()
{
  Task.Factory.StartNew(() =>
  {
    CallMyCode();
  }).ContinueWith((t) =>
  {
    HandleErrors(t.Exception);
  }, TaskContinuationOptions.OnlyOnFaulted);
}

public void HandleErrors(Exception ex)
{
  //handle any exceptions that occur inside of CallMyCode
}

But that won't work if running multiple copies of CallMyCode() at the same time will cause problems. For example if it's an instance of an object that has some private list or dictionary that it mutates. That will blow up. Concurrency is a tricky thing.

If you want to use the code above, but you want to just prevent the code from executing simultaneously, you can put a lock around CallMyCode(). Like this:
Code:
private object myLock = new object();

public void LibraryEventFired()
{
  Task.Factory.StartNew(() =>
  {
    lock(myLock)
    {
      CallMyCode();
    }
  }).ContinueWith((t) =>
  {
    HandleErrors(t.Exception);
  }, TaskContinuationOptions.OnlyOnFaulted);
}

But if the rate at which events fire is faster than the rate at which your code completes, then you'll have a bunch of tasks that are all contesting the lock. Over time they'll build up and things will get slow and dumb.

Option 1 is the more robust solution. Basically requires you to set up a thread or task when the program starts, but then sleep on a signal (ManualResetEventSlim). Then when your library event fires, set the signal, which wakes up your main thread to do some work. Then you need a stop method which will stop the thread. You probably need a cancellation token to abort any work when stop is called. You might need another signal, too. It gets a little complicated. If you need this I could help you, but it's not trivial.

btw this is the best page ever on threading in C#: Threading in C#

Thanks. Works. I had read a bit about the different ways to work with threads in C#, but I really wasn't sure which one to use.
 
so in java, how do insure that the user has to select from the three letter choices provided? I'm trying to insure that user selects from Y for yes, N for no or O for other.

I tried

if(input!= "Y" || input != "N"|| input!= "O")

{
return false;
}

but that does not work because it won't let the user move on becuase despite making the right choice the comp still counts it as invalid. could someone give me a hint at what I did wrong? do I have to code in stacked if statements?
 

AngryMoth

Member
Wat.

You are supposed to do that alone without prior knowledge?
Alone yes but not without prior knowledge, just with very little experience. I've been learning html/css/javascript/php in my spare time the last month as we were told to do in preparation for this assessment. But I've only been writing small programs so this project is something of a step up.
 
assuming input is a string:

!input.equalsIgnoreCase("Y")

so, if(!input.equalsIgnoreCase("Y")||!input.equalsIgnoreCase("N")||!input.equalsIgnoreCase("O")) correct? i'll try it out now.

fake edit: later, after dinner.

real edit: didn't work :(. I also tried nested if statements but that did not work as well.
 

poweld

Member
so, if(!input.equalsIgnoreCase("Y")||!input.equalsIgnoreCase("N")||!input.equalsIgnoreCase("O")) correct? i'll try it out now.

fake edit: later, after dinner.

real edit: didn't work :(. I also tried nested if statements but that did not work as well.

I think your logic is a little mixed up. You want to make sure they select 'y', 'n', or 'o', right?

Currently the code checks to see if the input equals 'Y' or 'y'. If it does not, we return false. But what I think you want is to only return false if the input does not equal 'Y' or 'y' and the other characters...
 
I think your logic is a little mixed up. You want to make sure they select 'y', 'n', or 'o', right?

Currently the code checks to see if the input equals 'Y' or 'y'. If it does not, we return false. But what I think you want is to only return false if the input does not equal 'Y' or 'y' and the other characters...

you're right. This is giving me a headache. I'll try tackling this tomorrow.

@fallingedge I'm assuming you mean system.out.println right? If so, it comes out to what I type in(y or n or o)
 
I have a codelab question that I'm stuck on.

I'm supposed to write a loop that reverses the elements of an array.
I don't know where to start.

I'm not sure what Codelab is, but that's a pretty standard problem. You can do it in a for loop easily enough.

An easy way is to initialize it with two counter variables (i and j maybe), one starting at the beginning of the array and one at the end. At each step, swap array and array[j]. Then increment i and decrement j. The loop should stop when i and j are the same (which happens if the array has an odd number of elements), or i is greater than j (happens when there are an even number of elements). The main tricky part is making sure you don't get an off by one error there.
 

hateradio

The Most Dangerous Yes Man
I just spent most of the day reading about demultiplexers thanks to that Scala reactive programing course. My brain was friend after looking at this image that someone made, but then . . . it made sense. It was the weirdest sensation, being confused and understanding.

As with the other course, I wish certain things were explained a little better or at least given external resources to research.
 
:D

I'd like to look at the pic but the link doesn't work.
Really wish I had the time to take that course, first one was pretty great.

BTW, anyone know of any online courses using Haskell...?

I haven't heard of any online Haskell courses...have you read Learn You a Haskel for Great Good? I just started reading it the other day (wanted to learn a functional language) and it's pretty great.

Speaking of online courses, Udacity has has started some new stuff. You can still access all of their materiel free as "free courseware", but they now have paid versions of the classes. Sounds like the major difference is that you get a "coach" you can get help from, and who actually evaluate your projects. Or something like that. And the price looks to be around $100-$200 a month per course.

Can't say I'm particularly interested in that. But at least they are keeping their "free courseware" the same -- I'm just worried that the free part of their future courses may suffer as a result of them wanting you to enroll.

Either way, I do love me some Udacity. It's kind of sad -- the quality of the courses I've taken on Udacity and Coursera for free have been, for the most part, much MUCH better then the classes I'm paying a good chunk of money to take in college.
 

Water

Member
I haven't heard of any online Haskell courses...have you read Learn You a Haskel for Great Good? I just started reading it the other day (wanted to learn a functional language) and it's pretty great.
I'm definitely planning to work through that, and possibly Haskell Road to Logic and Math, but if there was an online course using Haskell it might give me some more drive.

Can't jump into the whole Haskell business yet, though. I'm currently learning C# and Unity3D from scratch. There's a game proto that has to be done in a month, and a whole team is counting on me to do a lot of the coding... :-o

Speaking of online courses, Udacity has has started some new stuff. You can still access all of their materiel free as "free courseware", but they now have paid versions of the classes. Sounds like the major difference is that you get a "coach" you can get help from, and who actually evaluate your projects. Or something like that. And the price looks to be around $100-$200 a month per course.
That's actually super cheap compared to any commercial training I've heard of. Could work out really well for them.
 

explodet

Member
Hey Programming GAF, medium time lurker, first time poster.

I've been a web programmer my entire career, jumping from backend to frontend. my most recent work has been on backend stuff (PHP MVC frameworks, MySQL databases) and I've let my frontend skills slip. I've got a interview next week for a mobile/desktop frontend developer and man have I got some cramming to do. HTML5 is pretty neat, and how is it I've never come across Web Storage before? Sure they sound like beefed up sessions/cookies but hey, storage is storage.

Any other frontend-GAF people here?
 

Korosenai

Member
Need some help with c++ classes. So this is an excerpt from the assignment:

"Your book and DVD classes must both include a public function named print_info() that will output the name of the class to the console, then call the parent class (product) function called print_info(), and finally print the specific variable information from the child class to the console."

So basically, the parent class Product will have a void function named print_info that will display four files: ID, Name, Price, and Stock. Then the two child classes will each have their own print_info functions that will display three files each: For Book class, it will display Publisher, Author, and ISBN and for DVD Class, it will display Studio, Male lead, and Female lead.

Here are some specific parts from my program that I have so far:

Main cpp
Code:
int main()
{
dvd my_dvd(1234, "Walking Dead", 33.99, 4, "AMC", "Andrew Lincoln", "Sarah Wayne Callies");
my_dvd.print_info();
book my_book(4321, "Slaughterhouse Five", 9.99, 6, "Dial Press", "Kurt Vonnegut", 123456);
my_book.print_info();
}

From product.h and product.cpp:
Code:
product::product(int i, string n, double p, int s)
{
    id = i;
    name = n;
    price = p;
    stock = s;
}

void product::print_info()
{
	cout << getId() << endl;
	cout << getName() << endl;
	cout << getPrice() << endl;
	cout << getStock() << endl;
}
from dvd.h and dvd.cpp (and i'll only post dvd.h, because book.h looks the exact same):
Code:
dvd(int i, string n, double p, int s, string dvdS, string dvdM, string dvdF) : product(i, n, p, s)
{
	studio = dvdS;
	male = dvdM;
	female = dvdF;
}

void dvd::print_info()
{
	cout << "This is the DVD Class.\n";
	cout << "We are now in the parent class: " << getName() << endl; //getName() is defined in product .h
	cout << "The Studio is: " << getStudio() << endl; //getStudio() is defined in dvd.h
	cout << "The Male Lead is: " << getMale() << endl; //getMale() is defined in dvd.h
	cout << "The Female Lead is: " << getFemale() << endl; //getFemale() is defined in dvd.h
}

This part of code works:
Code:
cout << "We are now in the parent class: " << getName() << endl; //getName() is defined in product .h
so I know it's properly reading from the parent class, I just don't know how to include the print_info function (in place of getName()) into the print_info function of the child class that way it prints everything instead of just the name. I could just do this:
Code:
void dvd::print_info()
{
	cout << "This is the DVD Class.\n";
	cout << "The id is: " << getId() << endl;
        cout << "The name is: " << getName() << endl;
        cout << "The price is: " << getPrice() << endl;
        cout << "The stock is: " << getStock() << endl;
	cout << "The Studio is: " << getStudio() << endl; //getStudio() is defined in dvd.h
	cout << "The Male Lead is: " << getMale() << endl; //getMale() is defined in dvd.h
	cout << "The Female Lead is: " << getFemale() << endl; //getFemale() is defined in dvd.h
}

But he wants us to do something like this:
Code:
void dvd::print_info()
{
	cout << "This is the DVD Class.\n";
	cout << product print_info() << endl;
	cout << "The Studio is: " << getStudio() << endl; //getStudio() is defined in dvd.h
	cout << "The Male Lead is: " << getMale() << endl; //getMale() is defined in dvd.h
	cout << "The Female Lead is: " << getFemale() << endl; //getFemale() is defined in dvd.h
}
 

maeh2k

Member
Need some help with c++ classes. So this is an excerpt from the assignment:

"Your book and DVD classes must both include a public function named print_info() that will output the name of the class to the console, then call the parent class (product) function called print_info(), and finally print the specific variable information from the child class to the console."

So basically, the parent class Product will have a void function named print_info that will display four files: ID, Name, Price, and Stock. Then the two child classes will each have their own print_info functions that will display three files each: For Book class, it will display Publisher, Author, and ISBN and for DVD Class, it will display Studio, Male lead, and Female lead.

Here are some specific parts from my program that I have so far:

Main cpp
Code:
int main()
{
dvd my_dvd(1234, "Walking Dead", 33.99, 4, "AMC", "Andrew Lincoln", "Sarah Wayne Callies");
my_dvd.print_info();
book my_book(4321, "Slaughterhouse Five", 9.99, 6, "Dial Press", "Kurt Vonnegut", 123456);
my_book.print_info();
}

From product.h and product.cpp:
Code:
product::product(int i, string n, double p, int s)
{
    id = i;
    name = n;
    price = p;
    stock = s;
}

void product::print_info()
{
	cout << getId() << endl;
	cout << getName() << endl;
	cout << getPrice() << endl;
	cout << getStock() << endl;
}
from dvd.h and dvd.cpp (and i'll only post dvd.h, because book.h looks the exact same):
Code:
dvd(int i, string n, double p, int s, string dvdS, string dvdM, string dvdF) : product(i, n, p, s)
{
	studio = dvdS;
	male = dvdM;
	female = dvdF;
}

void dvd::print_info()
{
	cout << "This is the DVD Class.\n";
	cout << "We are now in the parent class: " << getName() << endl; //getName() is defined in product .h
	cout << "The Studio is: " << getStudio() << endl; //getStudio() is defined in dvd.h
	cout << "The Male Lead is: " << getMale() << endl; //getMale() is defined in dvd.h
	cout << "The Female Lead is: " << getFemale() << endl; //getFemale() is defined in dvd.h
}

This part of code works:
Code:
cout << "We are now in the parent class: " << getName() << endl; //getName() is defined in product .h
so I know it's properly reading from the parent class, I just don't know how to include the print_info function (in place of getName()) into the print_info function of the child class that way it prints everything instead of just the name. I could just do this:
Code:
void dvd::print_info()
{
	cout << "This is the DVD Class.\n";
	cout << "The id is: " << getId() << endl;
        cout << "The name is: " << getName() << endl;
        cout << "The price is: " << getPrice() << endl;
        cout << "The stock is: " << getStock() << endl;
	cout << "The Studio is: " << getStudio() << endl; //getStudio() is defined in dvd.h
	cout << "The Male Lead is: " << getMale() << endl; //getMale() is defined in dvd.h
	cout << "The Female Lead is: " << getFemale() << endl; //getFemale() is defined in dvd.h
}

But he wants us to do something like this:
Code:
void dvd::print_info()
{
	cout << "This is the DVD Class.\n";
	cout << product print_info() << endl;
	cout << "The Studio is: " << getStudio() << endl; //getStudio() is defined in dvd.h
	cout << "The Male Lead is: " << getMale() << endl; //getMale() is defined in dvd.h
	cout << "The Female Lead is: " << getFemale() << endl; //getFemale() is defined in dvd.h
}

I think in C++ you call product::pint_info(), much like you call product() in the constructor of the subclass.
When you inherit from a class you basically get an anonymous object of that class inside an object from the subclass.

Maybe someone can point you to a good tutorial.
 

Korosenai

Member
I think in C++ you call product::pint_info(), much like you call product() in the constructor of the subclass.
When you inherit from a class you basically get an anonymous object of that class inside an object from the subclass.

Maybe someone can point you to a good tutorial.

This worked, and I found out what I was doing wrong. I was trying to write the code like this:

Code:
cout << product::print_info();

when I didn't need the cout.
 

doodle

Member
so in java, how do insure that the user has to select from the three letter choices provided? I'm trying to insure that user selects from Y for yes, N for no or O for other.

I tried

if(input!= "Y" || input != "N"|| input!= "O")

{
return false;
}

but that does not work because it won't let the user move on becuase despite making the right choice the comp still counts it as invalid. could someone give me a hint at what I did wrong? do I have to code in stacked if statements?

The way you have it setup now, your logic says that "If any of these are not true...". This would be a problem since input can only equal one thing, not three!
 

GK86

Homeland Security Fail
Does anyone here program using a web based IDE?

I'm starting intro to CS next year and would like to have a laptop. Being a college student, I'm naturally broke. I was thinking about getting a Chromebook when I read about the web IDE's. Is that a viable option? Or should I try to spring for a laptop?

I should say that I have a desktop at home, and the Chromebook/laptop would be used around school to program on my break/whenever.

Thanks.
 

Dr_Swales

Member
Need some help with c++ classes. *snip*

I think in C++ you call product::pint_info(), much like you call product() in the constructor of the subclass.

...

Maybe someone can point you to a good tutorial.

I will add to maeh2k's answer seeing as he suggested someone should add some more information.

You are having trouble calling methods from base classes in your derived classes... there are several ways to change your style of writing that will help with implementing classes and increasing readability of your code.

Firstly, if you have come from a Java or C# background for example you may be familiar with the keyword super or base. This keyword is not implemented in C++ because C++ supports multiple inheritance so there can be more than one base class. To implement this keyword for use in your classes use a typedef.

Code:
class Product
{
    void print_info(void);
};

void Product::print_info(void)
{
    // ...
}

Code:
class Dvd : public Product
{
    private:
        typedef Product super;

    public:
        void print_info(void);
};

void Dvd::print_info(void)
{
    super::print_info();
    // ...
}

Code:
class Book : public Product
{
    private:
        typedef Product super;

    public:
        void print_info(void);
};

void Book::print_info(void)
{
    super::print_info();
    // ..
}

In these examples you can call the code from the base class which in your case is product by using the type super followed by the scope operator :):), to specify a method from the base class.

A second method if you are using Microsoft compiler is to use the __super keyword. The keyword __super works the same way as using the typedef Base super. Just you don't have to define it for every class you implement.

Code:
class Product
{
    void print_info(void);
};

void Product::print_info(void)
{
    // ...
}

Code:
class Dvd : public Product
{
    public:
        void print_info(void);
};

void Dvd::print_info(void)
{
    __super::print_info();
    // ...
}

Code:
class Book : public Product
{
    public:
        void print_info(void);
};

void Book::print_info(void)
{
    __super::print_info();
    // ..
}

In these examples you call methods from the base class by using the keyword __super followed by the scope :):) operator.

One final thing that some people do to increase the readability of their code is to always specify when they are calling a method that is part of the current class. This is done using the this keyword. The this keyword is a pointer to the current instance (object) of the class you are inside.

Using your Dvd classes print_info as an example.

Code:
void Dvd::print_info(void)
{
	cout << "This is the DVD Class.\n";
	cout << "We are now in the parent class: " << super::getName() << endl; //getName() is defined in product .h
	cout << "The Studio is: " << this->getStudio() << endl; //getStudio() is defined in dvd.h
	cout << "The Male Lead is: " << this->getMale() << endl; //getMale() is defined in dvd.h
	cout << "The Female Lead is: " << this->getFemale() << endl; //getFemale() is defined in dvd.h
}

As I said before, the this keyword is a pointer to the current class so it needs to be deferenced using either by this-> or (*this).. Also, if you haven't covered pointers yet in class ignore this bit for now.

Hope this helps =)
 

Slavik81

Member
I can hardly describe how much I hate AccuRev. I used it for years without a care, but now I realize how many problems I had that were caused by its awfulness. Until I started seriously trying other tools, I didn't realise my problems were just bad tooling, not fundamental issues.

The worst is that you can't pick what version of your depot you're based on. You can only update to go forward in time. If you update your workspace and discover the build is broken, you cannot just go back to the last known-good transaction. Accurev update does let you specify what transaction you want to update to, but it can only be a transaction ahead of your current transaction.

The tool is a complete piece of junk. I wrote an angry blog post about it.
 

maeh2k

Member
Does anyone here program using a web based IDE?

I'm starting intro to CS next year and would like to have a laptop. Being a college student, I'm naturally broke. I was thinking about getting a Chromebook when I read about the web IDE's. Is that a viable option? Or should I try to spring for a laptop?

I should say that I have a desktop at home, and the Chromebook/laptop would be used around school to program on my break/whenever.

Thanks.

I'm not quite sure. I don't think a web-based IDE is a viable option, but with a Chromebook it might be possible to get rid of ChromeOS and install Linux instead.
With a traditional OS you are prepared for any programming language and you can use the best IDEs, and most importantly, you can actually run the stuff you program, For Intro to CS you might want something that can execute Java programs and run Eclipse.

But even with Linux, I'm not sure a Chromebook is the way to go. There are lots of affordable Windows options or you could get something like a used ThinkPad from a couple of years ago.

If you want something small competing with an 11" Chromebook, you could get the 11" Vivobook for $280: http://www.amazon.com/VivoBook-X200CA-DB01T-11-6-Inch-Touchscreen-Laptop/dp/B00CPIF4G0 or a Dell Inspiron 11 for $350 or maybe the Asus T100 (which comes with Office): http://www.amazon.com/Transformer-T100TA-C1-GR-10-1-Inch-Convertible-Touchscreen/dp/B00FFJ0HUE.
Of course at the ~$400 pricepoint you have tons of options. E.g. this 15" Dell: http://www.amazon.com/Dell-Inspiron-i15RV-6144BLK-15-6-Inch-Touchscreen/dp/B00CRGJKT2.

For studying CS really any traditional notebook seems more useful than a Chromebook.
 
I hate browsers and JavaScript and especially ALL THE FUCKING BROWSERS ALL OF THEM EQUALLY. First I spent 3 hours trying to get IE11 to install on a W7 machine (turns out that Windows Update hadn't installed some tiny update correctly which is why the IE11 always failed. At the same time I am trying to figure out why a W8 IE11 doesn't have other document modes than "Edge mode", turns out that it was a preview version (even on W8.1) and you couldn't update the program from anywhere else than Windows Update (instead of Store for example) (in retrospect reinstalling from Windows site could have worked too)).

The fix was ultra trivial, but then I noticed that the certain part of the site failed to load with Chrome (DOMHierarchyError). 4 hours later I finally figured out it was yepnope pulling out loading out of it's ass because window.load() is unreliable but needed for the Adobe Edge framework POS. So once again, the fix was trivial (quite literally putting things in different order) but there went my workday without getting anything significant done and it should have been the day I take some of my overwork hours back.

/rant
 

GK86

Homeland Security Fail
I'm not quite sure. I don't think a web-based IDE is a viable option, but with a Chromebook it might be possible to get rid of ChromeOS and install Linux instead.
With a traditional OS you are prepared for any programming language and you can use the best IDEs, and most importantly, you can actually run the stuff you program, For Intro to CS you might want something that can execute Java programs and run Eclipse.

But even with Linux, I'm not sure a Chromebook is the way to go. There are lots of affordable Windows options or you could get something like a used ThinkPad from a couple of years ago.

If you want something small competing with an 11" Chromebook, you could get the 11" Vivobook for $280: http://www.amazon.com/VivoBook-X200CA-DB01T-11-6-Inch-Touchscreen-Laptop/dp/B00CPIF4G0 or a Dell Inspiron 11 for $350 or maybe the Asus T100 (which comes with Office): http://www.amazon.com/Transformer-T100TA-C1-GR-10-1-Inch-Convertible-Touchscreen/dp/B00FFJ0HUE.
Of course at the ~$400 pricepoint you have tons of options. E.g. this 15" Dell: http://www.amazon.com/Dell-Inspiron-i15RV-6144BLK-15-6-Inch-Touchscreen/dp/B00CRGJKT2.

For studying CS really any traditional notebook seems more useful than a Chromebook.

That you for the input! I would rather not get a cheap/lower end windows notebook. Bad experiences in the past. I would spend $700+ on a laptop if the Chromebook route isn't ideal. Of course, I would have to save up and wouldn't buy it until early next year. Thanks again for your help!
 
Top Bottom