jeudi 31 mars 2016

How to access instance method using "self" in singleton class?

I am accessing instance method in a class method by using self in singleton class it shows error, but if I try to access instance method with parameter using self then its perfectly working, so basically i want to know the reason, why i am not able to access this.

like

-(void)someMethodA:(NSString *)paramA withParamB:(NSString *)paramB;

-(void)someMethodB;

if i try to use "someMethodA" with self then it works perfectly fine, but accessing "someMethodB" using self it gives error

+(void)someMethod

{

[self someMethodA:@"string" withParamB:@"string"]; works fine

[self someMethodB]; gives error

}




Passing variables in the same class between methods?

I havent touched java in awhile. I need some help, what I am trying to do with this program is get the car class to calculate the carbonfootprint inside of the getcarbonfootprint() method. HOWEVER, like all the videos that I have been going through, I DON'T want to pass it back to the main class through a return value. Instead, I want to use the same variables in the class car through methods. I tried using the this value, however, that doesn't work either. If you can link me to the right location on this question, that will work as well.

MAIN CLASS:

package carbonfootprinttest;

public class CarbonFootprinttest {

public static void main(String[] args) {
building house = new building();
car fusion = new car();
bike trek = new bike();
double mytest = fusion.returncarbonfootprint();
System.out.print(mytest);
}
}

CAR CLASS:

public class car implements carbonfootprint {
private double mpg = 25;
public double yearly = 500;
public double carbonfootprint;

public void setmpg(){
    System.out.println("The mpg of a ford fusion is " + mpg + " MPG.");
}

@Override
public void getcarbonfootprint() {
   carbonfootprint = (yearly * mpg)/9;
}
public double returncarbonfootprint(){
    System.out.println(carbonfootprint);
    return carbonfootprint;
}
}




Change span class on click angularjs

Good day! I have a span in my code. The class contains image that is displayed via span. Once the user clicked the image, its class should change and when another span is clicked, it should go back to the original class

 <span alt="Mode1" ng-class="{'mode': isActive}" ng-click="activeButton()"  ></span></span>

on my controller

  $scope.isActive = false;
  $scope.activeButton = function() {
    $scope.isActive = !$scope.isActive;
  }  

It is already working but my problem is on the load there is nothing displayed and it only shows when I click it. Im using angularjs btw




How to create connected classes?

I am very confused on how to go about creating arrays that share classes, such as what this is suggesting:

You should create the Guitar class:

The song must be stored as a two-dimensional array. The rows represent each guitar string. The columns therefore represent each chord (a chord is just one or more notes played at the same time, like when you strum a guitar all of the strings play some frequency). There is an additional row at the bottom (the highest index row) which holds the number of beats each chord gets held. This two-dimensional array captures all the notes that the guitar will play and for how long it should play each one of them.

You should construct a guitar by taking in a number of strings and the song length in number of chords. These will fully determine the size of your 2D song array. Your main program (Songwriter class) will take in these values through command line parameters and can then use them to construct a guitar object.

Your guitar object will need a generateSong() method which populates the 2D song array with frequencies for all the notes, along with the number of beats for which each note should be held. You aren’t constrained to normal physical rules of guitars: the frequencies you use to generate the notes are random ranging between 27.5 Hz (inclusive) and 4186 Hz (exclusive). Each frequency is displayed with two decimal places accuracy but stored with its full accuracy.

Then, each chord will be played for a number of beats between 0 seconds (exclusive) and 3 seconds (exclusive). Fractional seconds are permitted. You randomly generate the duration of each chord.

Your guitar constructor should take care of initializing all of the member variables for itself, including generating the song. In other words your Guitar(int, int) constructor method calls the generateSong() method. The generateSong() method does not require any parameters because the values it needs are member variables in its same class, so it can just access their values as it needs to.

You should create the Vocalist class: Its constructor should initialize its member variables. The constructor will need to take in the necessary information (think about what values or objects you should pass to it) in order to do its initialization.

A vocalist has a mid-range frequency which constitutes the “center” of his or her vocal range. This frequency must be stored as a double. Since the vocalist will always sing a frequency from the guitar chord, the mid-range frequency will be used to determine which frequency from the guitar chord is closest.

A vocalist has a melody variable which is a 2D array. The first row stores the frequencies the vocalist will sing, and the second row stores the number of beats each note should be sung.

Implement a toString() method which returns the vocalist’s melody and number of beats as a string on two lines, formatted like this:

157.18 977.21 3051.07 1887.60 1339.81 182.63 984.57 2324.46

1.4 1.2 2.0 2.0 1.0 2.2 1.8 1.5

Before you proceed, stop and thoroughly test your methods which extract melody notes and then display them. Make sure they are correctly selecting the closest frequency from each guitar chord. Use lots of different tests with different sizes of arrays and different mid-range frequencies. (In other words, vary the command line parameters.)

Implement a sing() method within the Vocalist class which actually produces the sound of each melody note for the specified number of beats. You will be able to hear these notes through your computer’s audio. This is the song you have composed! In order to do this, you will use the StdAudio.java class which is being provided to you by calling StdAudio.playTone(double,double). The first double is the frequency of tone that should be played. The second double is how many seconds to play the tone.

Example output of entire program running with command line parameters 4 8 304.45

Guitar(): Generated new guitar with 4 strings. Song length is 8 chords.

1546.59 1986.61 3604.10 3469.56 3589.76 538.16 3664.72 2622.66

838.69 1204.43 3051.07 3941.62 1339.81 2385.39 984.57 2925.13

157.18 977.21 3471.75 1887.60 2943.96 182.63 1217.72 3485.39

3844.56 3162.71 3399.16 3411.66 1712.71 447.49 3773.18 2324.46

1.4 1.2 2.0 2.0 1.0 2.2 1.8 1.5

Guitar.simulateSong()

3844.56 157.18 838.69 1546.59..

3162.71 977.21 1204.43 1986.61..

3399.16 3471.75 3051.07 3604.10...

3411.66 1887.60 3941.62 3469.56...

1712.71 2943.96 1339.81 3589.76.

447.49 182.63 2385.39 538.16...

3773.18 1217.72 984.57 3664.72..

2324.46 3485.39 2925.13 2622.66..

Vocalist(): midRangeFreq: 304.45

Vocalist(): songlength: 8

157.18 977.21 3051.07 1887.60 1339.81 182.63 984.57 2324.46

1.4 1.2 2.0 2.0 1.0 2.2 1.8 1.5




Undeclared Identifiers & Unknown type name 'class'

I am trying to write a program that manages a stores backend (i.e. keeping track of customers and products). I just started learning c++ in January and I am definitely a beginner with regards to classes and separate header files and such. I am getting a few undeclared identifier errors and a couple of unknown type name errors.

I am very aware that the code is rough, I am just trying to tackle this and get a good grip on how these interactions occur.

The main.cpp is MIA because it is hidden by a testing function created by my instructor.

The errors being received are as follows: http://ift.tt/1SqHM2D The locations of these errors are marked in the code by comments in order. Thank you so much in advance for any help, just want to get better at this.

Store.h

#ifndef Store_h
#define Store_h
#pragma once

#include <stdio.h>
#include <string>
#include <iostream>
#include <vector>

class Store{

    std::vector<Product*> products;              //Error 1-2
    std::vector<Customer*> customers;            //Error 3-4

public:
    Store();
    Store(std::string name);
    std::string getStorename();
    void setStorename(std::string name);
    void addProduct(int productNum, std::string productName);
    Customer* getCustomer(int customerID);          //Error 5
    void addCustomer(int customerID, std::string name, bool credit);
    Product* getProduct(int productNum);           //Error 6
    void takeShipment(int productNum, int quantity, double cost);
    void makePurchase(int customerID, int productNum, int quantity);
    void takePayment(int customerID, double amount);
    void listProducts();
    void listCustomers();





private:
    std::string name;
};


#endif /* Store_h */

Store.cpp

#include <iostream>
#include "Store.h"
#include "Product.h"
#include "Customer.h"
using namespace std;

Store::Store(){
}

Store::Store(string name): name(name) {

}


void Store::setStorename(string name) {
    this->name = name;
}

string Store::getStorename(){
    return name;

 }

void Store::addProduct(int productNum, string productName){

    Product* prod = new Product(productNum, productName);
    products.push_back(prod);


}

Product* Store::getProduct(int productNum){

    for (int i = 0; i < products.size(); ++i) {
        Product* a = products.at(i);
        if (a->getProductNum() == productNum) {
            return a;
        }
    }
    throw runtime_error("Invalid Product.");
}


void Store::addCustomer(int customerID, string name, bool credit){

    Customer* cust = new Customer(name, customerID, credit);
    customers.push_back(cust);


}

Customer* Store::getCustomer(int customerID){

    for (int i = 0; i < customers.size(); ++i) {
        Customer* a = customers.at(i);
        if (a->getID() == customerID) {
            return a;
        }
    }
    throw runtime_error("Invalid Customer.");

}

void Store::takeShipment(int productNum, int quantity, double cost){

    for (int i = 0; i < products.size(); ++i) {
        Product* a = products.at(i);
        if (a->getProductNum() == productNum) {



    }
}
throw runtime_error("Invalid Product.");


}

void Store::makePurchase(int customerID, int productNum, int quantity){

    Customer* a = getCustomer(customerID);
    a->processPurchase(productNum, quantity));


}

void Store::takePayment(int customerID, double amount){

    Customer* a = getCustomer(customerID);
    a->processPayment(amount);


}

void Store::listProducts(){
    for (int i = 0; i < products.size(); ++i) {
        Product* prod = products.at(i);
        prod->getInfo();
        cout << endl;
    }
}

void Store::listCustomers(){
    for (int i = 0; i < customers.size(); ++i) {
        Customer* prod = customers.at(i);
        prod->getInfo();
        cout << endl;
    }


}

Product.h

#ifndef Product_h
#define Product_h
#pragma once


#include <stdio.h>
#include "Customer.h"
#include "Store.h"
#include <string>
#include <iostream>
#include <vector>

class Product{

public:
    Product();
    Product(int productNum, std::string productName);
    void setDescription(std::string description);
    std::string getDescription();
    void setDefaultReturnPeriod(int days);
    int getReturnPeriod();
    int getNumberSold();
    double getTotalCost();
    void addShipment(int quantity, double cost);
    double getPrice();
    void processOrder(int quantity);
    int getProductNum();
    void getInfo();
protected:
    std::string productName;
private:

    int productNum;
    int inventory;
    int numSold;
    int totalCost;
    std::string description;
    int defaultReturnDays;
    int quantity;
    double cost;
};

#endif /* Product_h */

Customer.h

#ifndef Customer_h
#define Customer_h
#pragma once

#include <stdio.h>
#include <string>
#include <iostream>
#include "Store.h"
#include <vector>

class Customer{

public:
    Customer();
    Customer(std::string name, int customerID, bool credit);
    void setName(std::string name);
    std::string getName();
    int getID();
    void setCredit(bool hasCredit);
    bool getCredit();
    double getBalance();
    void processPayment(double amount);
    void processPurchase(double amount, Product product);  //Error 7
    void getInfo();


private:

    std::string memberName;
    std::string name;
    int customerID;
    bool credit;
    double balance;
    std::vector<Product*> productsPurchased;     //Error 8


};



#endif /* Customer_h */




Making a static reference to a non-static method in another class

I'm learning object-oriented programming in a Java course, and I'm doing a project where a program creates three types of objects: Address, Date, and Employee. The program stores data of several employees and then displays the data in an array of type Employee.

I'm using four different classes: an Address class, a Date class, and an Employee Class, and an EmployeeTest class that creates the array.

Here is the Address class:

public class Address {

    private String Street;
    private String City;
    private String State;
    private int ZipCode;

    public Address(String St, String Ci, String Sta, int Zip){
        Street = St;
        City = Ci;
        State = Sta;
        ZipCode = Zip;
    }

    public String getEmployeeAddress(){
        return (Street + ", " + City + ", " + State + " " + ZipCode);
    }
}

The Date Class:

public class Date {

    private int Month;
    private int Day;
    private int Year;

    public Date(int M, int D, int Y){
        Month = M;
        Day = D;
        Year = Y;
    }

    public String getDateString(){
        return (Month + "/" + Day + "/" + Year);
    }
}

And, the Employee Class:

public class Employee {
    private int EmployeeNum;

    public void setEmployeeNum(int ENum){
        EmployeeNum = ENum;
    }

    public int getNum(){
        return EmployeeNum;
    }

    public String getDate(){
        return Date.getDateString();
    }

    public String getName(){
        return Name.getEmployeeName();
    }
    public String getAddress(){
        return Address.getEmployeeAddress();
    }

}

All of these classes are in the same package (I'm using Eclipse). The point of the Employee class is to create an object of type Employee and be able to get it's Address, Name, and HireDate using the Address, Name, and Date classes.

The place where the array comes into play is here:

import java.util.Scanner;
import java.lang.*;

public class EmployeeTest {

    public static void main(String[] args){
        Scanner input = new Scanner(System.in);
        System.out.print("How many employees will have their data stored today?");
        int EmployeeAmount = Integer.parseInt(input.nextLine());

        Employee [] EmployeeArray = new Employee[EmployeeAmount];

        for (int i = 0; i < EmployeeArray.length; i ++){
            System.out.print("What is employee " + (i+1) + "'s employee number?");
            int EmployeeNumber = Integer.parseInt(input.nextLine());
            EmployeeArray[i] =  new Employee();
            EmployeeArray[i].setEmployeeNum(EmployeeNumber);

            System.out.println("What is the first name of employee " + EmployeeNumber + "?");
            String EmployeeFirstName = input.nextLine();

            System.out.println("What is the last name of employee " + EmployeeNumber + "?");
            String EmployeeLastName = input.nextLine();

            Name EmployeeName = new Name(EmployeeFirstName, EmployeeLastName);

            System.out.println("Please enter the street address: ");
            String StreetAddress = input.nextLine();
            System.out.println("Please enter the name of the city: ");
            String CityName = input.nextLine();
            System.out.println("Please enter the two character code for the state: ");
            String StateID = input.nextLine();
            System.out.println("Please enter this address's zip code: ");
            int ZipCode = Integer.parseInt(input.nextLine());

            Address EmployeeAddress = new Address(StreetAddress, CityName, StateID, ZipCode);

            System.out.println("Finally, what was the month(#) of the hire date?");
            int Month = Integer.parseInt(input.nextLine());
            System.out.println("What was the day(#)?");
            int Day = Integer.parseInt(input.nextLine());
            System.out.println("What was the year?");
            int Year = Integer.parseInt(input.nextLine());

            Date HireDate = new Date(Month, Day, Year);



        }

        for (int j = 0; j < EmployeeArray.length; j ++){
            System.out.println("Employee number: " + EmployeeArray[j].getNum());
            System.out.println("Employee Name: " + EmployeeArray[j].getName());
            System.out.println("Employee Address: " + EmployeeArray[j].getAddress());
            System.out.println("Employee Hiredate: " + EmployeeArray[j].getDate());
        }


    }

}

The program prompts the user for the number of employees to be stored in the array, then creates an Employee[] of size EmployeeAmount. The idea of the code is that for each Employee in the Array, all of the variables in the other classes are obtained: Employee Number, Employee Name (first and last), Address (Street Address, City, State Code, Zip Code), Hire Date (Month, Day, Year). After all this is obtained, the second for loop iterates through each Employee and displays the info.

The problem I am having is that in the Employeeclass, Eclipse gives me an error in the getDate(), getName(), and getAddress() methods. When I say for example, return Date.getDateString(), Eclipse says that I cannot make a static reference to a non-static method. It's solution is to make getDateString() static, and I tried this, but the problem is that by making all the methods and variables in the Address, Employee, and Date classes, the values are locked. Meaning that the same data will be displayed for all employees.

Here's what I mean. Below is a sample output if I made all the methods and variables static. The text in between the asterisks is what the user inputs.

How many employees will have their data stored today?**2** What is employee 1's employee number?**1** What is the first name of employee 1? **Bob** What is the last name of employee 1? **Jones** Please enter the street address: **300 1st Avenue** Please enter the name of the city: **New York** Please enter the two character code for the state: **NY** Please enter this address's zip code: **10001** Finally, what was the month(#) of the hire date? **1** What was the day(#)? **1** What was the year? **2001** What is employee 2's employee number?**2** What is the first name of employee 2? **Bobby** What is the last name of employee 2? **Robinson** Please enter the street address: **301 1st Avenue** Please enter the name of the city: **Los Angeles** Please enter the two character code for the state: **CA** Please enter this address's zip code: **90001** Finally, what was the month(#) of the hire date? **1** What was the day(#)? **2** What was the year? **2004** Employee number: 2 Employee Name: Bobby Robinson Employee Address: 301 1st Avenue, Los Angeles, CA 90001 Employee Hiredate: 1/2/2004 Employee number: 2 Employee Name: Bobby Robinson Employee Address: 301 1st Avenue, Los Angeles, CA 90001 Employee Hiredate: 1/2/2004

By making all of the variables and methods static, the values are locked as shown, which makes the program useless. Does anyone have a solution to this problem? I need a way to display the information of each employee while referencing the methods in the other classes. Now, normally I would just create all the variables and methods under one class called Employee, but the assignment instructions specify that I need to make individual classes.




Unable to sort windows form into separate classes

I've made a program where I am able to open, edit, save and delete text files in a windows form, the only issue is that all of the code is in one class. I would like to be able to separate it into separate classes such as ModuleInfo class and ModuleNotes class. I have tried ordering them into classes but I can only inherit from one class at a time, It does not allow me to inherit from the Form class and the main Modnote class at the same time.

public partial class Modnote : Form
{
    string filename;
    string writeFile;

    string gamesDesign1Module = "Game Design 1 Module Information.txt";
    string algorithmsAndComplexityModule = "Algorithms and Complexity Module Information.txt";
    string computerArchitecturersModule = "Computer Architectures Module Information.txt";
    string informationSystemsModule = "Information Systems in Practice Module Information.txt";
    string operatingSystemsModule = "Operating Systems Module Information.txt";
    string programmingModule = "Programming and Data Structures Module Information.txt";
    string webApplicationsDevelopmentModule = "Web Applications Development Module Information.txt";

    string gamesDesign1Notes = "Game Design 1 Notes.txt";
    string algorithmsAndComplexityNotes = "Algorithms and Complexity Notes.txt";
    string computerArchitecturersNotes = "Computer Architectures Notes.txt";
    string informationSystemsNotes = "Information Systems in Practice Notes.txt";
    string operatingSystemsNotes = "Operating Systems Notes.txt";
    string programmingNotes = "Programming and Data Structures Notes.txt";
    string webApplicationsDevelopmentNotes = "Web Applications Development Notes.txt";

    public Modnote()
    {
        InitializeComponent();
    }

    private void exitToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Application.Exit();
    }

    private void openToolStripMenuItem_Click(object sender, EventArgs e)
    {

    }


    private void saveToolStripMenuItem1_Click(object sender, EventArgs e)
    {
        File.WriteAllText(filename, richTextBox2.Text);
        MessageBox.Show("Saved");

    }

    private void richTextBox1_TextChanged(object sender, EventArgs e)
    {

    }

    private void Form1_Load(object sender, EventArgs e)
    {
        label4.Text = DateTime.Now.ToShortDateString();
    }

    private void fileToolStripMenuItem_Click(object sender, EventArgs e)
    {

    }
    private void panel1_Paint(object sender, PaintEventArgs e)
    {

    }
    private void createModuleNotesToolStripMenuItem_Click(object sender, EventArgs e)
    {

    }

    private void clearModulesToolStripMenuItem_Click(object sender, EventArgs e)
    {
        richTextBox1.Clear();
    }

    private void clearModuleNotesToolStripMenuItem_Click(object sender, EventArgs e)
    {
        richTextBox2.Clear();
    }
    private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
    {

    }

        private void gameDesign1ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamReader inputFile = new StreamReader(gamesDesign1Module);
            richTextBox1.Text = inputFile.ReadToEnd();
            inputFile.Close();
        }

        private void operatingSystemsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamReader inputFile = new StreamReader(operatingSystemsModule);
            richTextBox1.Text = inputFile.ReadToEnd();
            inputFile.Close();
        }


        private void informationSystemsInPracticeToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamReader inputFile = new StreamReader(informationSystemsModule);
            richTextBox1.Text = inputFile.ReadToEnd();
            inputFile.Close();
        }

        private void algorithmsAndComplexityToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamReader inputFile = new StreamReader(algorithmsAndComplexityModule);
            richTextBox1.Text = inputFile.ReadToEnd();
            inputFile.Close();
        }

        private void computerArchitecturesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamReader inputFile = new StreamReader(computerArchitecturersModule);
            richTextBox1.Text = inputFile.ReadToEnd();
            inputFile.Close();
        }

        private void programmingAndDataStructuresToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamReader inputFile = new StreamReader(programmingModule);
            richTextBox1.Text = inputFile.ReadToEnd();
            inputFile.Close();
        }

        private void webApplicationsDevelopmentToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamReader inputFile = new StreamReader(webApplicationsDevelopmentModule);
            richTextBox1.Text = inputFile.ReadToEnd();
            inputFile.Close();
        }

        private void algorithmsAndComplexityNotesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamReader inputFile = new StreamReader(algorithmsAndComplexityNotes);
            richTextBox2.Text = inputFile.ReadToEnd();
            inputFile.Close();
            filename = algorithmsAndComplexityNotes;
        }

        private void computerArchitectureNotesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamReader inputFile = new StreamReader(computerArchitecturersNotes);
            richTextBox2.Text = inputFile.ReadToEnd();
            inputFile.Close();
            filename = computerArchitecturersNotes;
        }

        private void gameDesign1NotesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamReader inputFile = new StreamReader(gamesDesign1Notes);
            richTextBox2.Text = inputFile.ReadToEnd();
            inputFile.Close();
            filename = gamesDesign1Notes;
        }

        private void informationSystemsInPracticeNotesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamReader inputFile = new StreamReader(informationSystemsNotes);
            richTextBox2.Text = inputFile.ReadToEnd();
            inputFile.Close();
            filename = informationSystemsNotes;
        }

        private void operatingSystemsNotesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamReader inputFile = new StreamReader(operatingSystemsNotes);
            richTextBox2.Text = inputFile.ReadToEnd();
            inputFile.Close();
            filename = operatingSystemsNotes;
        }

        private void programmingAndDataStructuresNotesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamReader inputFile = new StreamReader(programmingNotes);
            richTextBox2.Text = inputFile.ReadToEnd();
            inputFile.Close();
            filename = programmingNotes;
        }

        private void webApplicationsDevelopmentNotesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            StreamReader inputFile = new StreamReader(webApplicationsDevelopmentNotes);
            richTextBox2.Text = inputFile.ReadToEnd();
            inputFile.Close();
            filename = webApplicationsDevelopmentNotes;
        }


    private void createToolStripMenuItem_Click(object sender, EventArgs e)
    {
        SaveFileDialog sfd = new SaveFileDialog();
        sfd.Filter = "Text File|*.txt";
        sfd.FileName = "Game Design 1 Lecture Notes";
        if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
            string path = sfd.FileName;
            using (var fs = File.Create(path))
            using (StreamWriter bw = new StreamWriter(fs))
            {
                bw.Write(writeFile);
                bw.Close();
            }
        }
    }


        private void createOperatingSystemsNotesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Text File|*.txt";
            sfd.FileName = "Operating Systems Lecture Notes";
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string path = sfd.FileName;
                using (var fs = File.Create(path))
                using (StreamWriter bw = new StreamWriter(fs))
                {
                    bw.Write(writeFile);
                    bw.Close();
                }
            }
        }

        private void createInformationSystemsInPracticeNotesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Text File|*.txt";
            sfd.FileName = "Information Systems In Practice Lecture Notes";
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string path = sfd.FileName;
                using (var fs = File.Create(path))
                using (StreamWriter bw = new StreamWriter(fs))
                {
                    bw.Write(writeFile);
                    bw.Close();
                }
            }
        }
        private void createAlgorithmsAndComplexityNotesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Text File|*.txt";
            sfd.FileName = "Algorithms And Complexity Lecture Notes";
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string path = sfd.FileName;
                using (var fs = File.Create(path))
                using (StreamWriter bw = new StreamWriter(fs))
                {
                    bw.Write(writeFile);
                    bw.Close();
                }
            }
        }

        private void createComputerArchitecturesNotesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Text File|*.txt";
            sfd.FileName = "Computer Architectures Lecture Notes";
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string path = sfd.FileName;
                using (var fs = File.Create(path))
                using (StreamWriter bw = new StreamWriter(fs))
                {
                    bw.Write(writeFile);
                    bw.Close();
                }
            }
        }

        private void createProgrammingAndDataStructuresNotesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Text File|*.txt";
            sfd.FileName = "Programming And Data Structures Lecture Notes";
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string path = sfd.FileName;
                using (var fs = File.Create(path))
                using (StreamWriter bw = new StreamWriter(fs))
                {
                    bw.Write(writeFile);
                    bw.Close();
                }
            }
        }

        private void createWebApplicationsDevelopmentNotesToolStripMenuItem_Click(object sender, EventArgs e)
        {
            SaveFileDialog sfd = new SaveFileDialog();
            sfd.Filter = "Text File|*.txt";
            sfd.FileName = "Web Applications Development Lecture Notes";
            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string path = sfd.FileName;
                using (var fs = File.Create(path))
                using (StreamWriter bw = new StreamWriter(fs))
                {
                    bw.Write(writeFile);
                    bw.Close();
                }
            }
        }

        private void openModuleFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog file = new OpenFileDialog();
            file.InitialDirectory = @"C:\Users\antho\Desktop\Folder\\Uni\Programming and data structures\Assignment 2\Module Notes";

            if (file.ShowDialog() == DialogResult.OK)
            {
                filename = file.FileName;
                StreamReader inputFile = new StreamReader(file.FileName);
                richTextBox2.Text = inputFile.ReadToEnd();
                inputFile.Close();
            }
       }

    }
}




Reaching servlet's getServletContext() from another class

I want to get

String webInfPath = getServletConfig().getServletContext().getRealPath("WEB-INF");

from another java file in my project. Servlet and class is looking like this:

com.aaa.bbb Servlet.java

com.ccc.ddd Class.java

public class Servlet extends HttpServlet {

public class Class {

So what is the easiest and efficient way to reach .getServletContext() function inside from the Class.java? Thanks in advance...




How do I change a class in HTML using PHP?

I have the code below in all of my pages, except for each page, the class is on that specific page.

<li><a href="../index.html">Homescreen</a></li>
<li><a href="socialstuff.html">Social Stuff</a></li>
<li><a href="sops.html">SOP's</a></li>
<li><a href="login.php">FTO Documents</a></li>
<li><a class="selected" href="changelog.html">Changelog</a></li>

I am working on throwing these inside of an include folder, that way each page I create does not have to have this line of code in each page. My only question is, how do I detect what page I'm on, and then automatically remove the old class slected and add the new one to the current page?




Error: Could not find or load main class

When I run my program this says:

Error: Could not find or load main class Hello world

Every setting I did several times but I get the same result. Win 8.1 64 bit Path settings ok eclipse jre setting ok




Calling methods from extended classes on array from abstract class

I am trying to call a certain method from a class that extendes an abstract class, on a array from the abstract superclass. Is there any possiblity to do that?

users[findUser(userName)].setVehicle(vehicles[counterVehicles])




How can a static method change a variable? (Java)

I have this class:

class Inventory {
    boolean smallknife = false;
    boolean SRLockerkey = false;
    void checkinv () {
        System.out.println("You have the following items in your inventory: ");
        System.out.println(smallknife);
        System.out.println(SRLockerkey);
    }
}

The Inventory test class

class InvTester {
    public static void main(String args[]) {
        Inventory TestInv = new Inventory();
        System.out.println("This program tests the Inventory");
        SKTrue.truth(TestInv.smallknife);
        TestInv.checkinv();
    }
}

and this class with a method to try to change the inventory

class SKTrue {
    static boolean truth(boolean smallknife) {
        return true;
    }
}


class SKTrue {
   static void truth(boolean smallknife) {
    smallknife = true;
  }
}

I would like to avoid using TestInv.smallknife = SKTrue.truth(TestInv.smallknife) and still change the variable but with a method. Is there a way that this can be done? I want that the truth method does the variable changing and I don't want to do the pass by reference part in the Inventory Test class. Thanks. Is there a way to do this in Java? (I also tried the second version which I think makes more sense)




int and string errors in the class file in Python

I am writing a python program where I have 3 files. One is the main file, one is the class file and one is data file. The data file reads from 2 text files and splits and arranges the data for use by the class and main file. Anyways, I am pretty much done with the data and main files but I am having problems with the class file. Its a general string formatting issue but I am failing to understand what I can possibly do to fix it. I am getting the error

" File "/Users/admin/Desktop/Program 6/FINAL/classFile.py", line 83, in repr if len(self._birthDay[0])<2: TypeError: object of type 'int' has no len()

This is my code

# Import datetme for calculating the age and date.
import datetime

# Creating a student class where different methods will be stored and formulated
class Student:

    # Creating the constructor and including techID, first and last names, birth day and grades.
    def __init__(self, techID, first, last, birthDay, grades):
       # Instance variable for first name
        self._first = first
       # Instance variable for last name
        self._last = last
       # Instance variable for birth day
        self._birthDay = birthDay
       # Instance variable for tech ID
        self._techID = techID
       # Instance variable for grades
        self._grades = grades
       # Instance variable for total number of credits. Setting it to 0 for counting
        self._totalCredits = 0

    # Method to formulate current age of a person
    def currentAge(self):
        # now determines the current day, month and year
        now = datetime.datetime.now()
        # year is the current year
        year = now.year
        # month is the current month
        month = now.month
        # day is the current day
        day = now.day
        # myYear is the given birth year of the person
        myYear = self._birthDay[2]
        # myYear is the given birth month of the person
        myMonth = self._birthDay[0]
        # myYear is the given birth day of the person
        myDay = self._birthDay[1]

        # This statement checks if the current month and current day are less than or equal to the birth
        # month and day of the given person.
        if myMonth <= month and myDay <= day:
            return year - myYear
        # If not, it is one year less than the current estimated age.
        else:
            return year - myYear - 1

    # Ths method calculated the GPA of the person using the data from the text files.
    def currentGPA(self):
        # Set gradeSum and checkSum to 0 for calculation
        gradeSum = 0
        creditSum = 0
        # Looping to read through all the grades
        for grade in self._grades:
            # Letter Grade is at the second position
            letterGrade = grade[1]
            # Credits are at the third position
            creditsTaken = grade[2]
            # If Elif statements to equalize letter grades to grade points.
            if letterGrade == "A":
                num = 4.0
            elif letterGrade == "B":
                num = 3.0
            elif letterGrade == "C":
                num = 2.0
            elif letterGrade == "D":
                num = 1.0
            elif letterGrade == "F":
                num = 0.0
            creditSum = creditSum + creditsTaken
            gradeSum = gradeSum + (num * creditsTaken)
        # Updates my totalCredits instance variable with the new actual value
        self._totalCredits = creditSum
        # The formula for GPA is sigma(grade*credits) divided by sigma(credits)
        return gradeSum / creditSum

    # def __repr__(self): is used for string printing. It is very efficient and eliminated the need for using print
    #  statements over and over again.

    def __repr__(self):
        if len(self._birthDay[0])<2:
            self._birthDay[0] = "0" + self._birthDay[0]
        elif len(self._birthDay[1])<2:
            self._birthDay[1] = "0" + self._birthDay[1]
        return self._first + " " + self._last + " (#" + self._techID + ")\nAge: " + str(self.currentAge()) + \
               " (" + str(self._birthDay[0]) + "/" + str(self._birthDay[1]) + "/" + str(self._birthDay[2]) + ")" + \
               "\nGPA: %0.2f" % (self.currentGPA()) + " (" + str(self._totalCredits) + " Credits" + ")\n"

Can someone please help me with the if statements in the def repr(self) and the string formatting?




Class implementation help needed PHP

I am trying to implement a class here, that takes two variables and can calculate the greatest common divisor. I think I have managed to set the values of my variables, but I am struggling to create a function, that could find the GCD. I would appreciate your help, as I am not so professional in OOP :) Thank you!

class Template implements testInterface
{

   private  $A;
   private  $B;

  function setA($value)
  {
      $this->A = $value;
      return $this;
  }

  function setB($value)
  {
      $this->B = $value;
      return $this;
  }

  function findGCD()
  {

  }
}
$A = new Template();
$A->setA(10);
$B = new Template();
$B->setB(5);
$GCD = new Template();
$GCD->findGCD();




How to call a method of the parent of Class A from another Class B (which is included in A)?

I have this ClassA.h:

#include "ClassB.h"

class ClassA : public BigClass {
public:
    ClassA ();
    ~ClassA ();

private:

};

BigClass contains the method I want to call:

bool BigClass::MyMethod(MyType* type)

Now, on ClassB.cpp (included in ClassA) I want to call that method:

void ClassB::InternalMethod() {
    ...
    MyMethod(myType);
}

But it says it is undefined...




Class accessor and mutator functions in c++

I'm a newbie in c++. I've been trying to write a program which takes integer value from user. The integer value will be changed by mutator function and another function prints on the screen. Thanks for your helps. Here is my effort until now:

#include <iostream>

using namespace std;

class bank 
{
public:
  bank();

  void output(ostream out);

  int revised(int acc);

  void set_account(int a);

  int get_account();


private:

int account;

};

bank::bank()
{
 account =0;
}

bank::revised(int acc)
{
 acc=acc+acc*2;
}

bank::set_account(int a)
{
account = a;
}

bank::get_account()
{
return account; 
}

bank::output(ostream out)
{
out<<account;
}

int main()
{
bank obj1;
int i;
cout>> "Enter your money";
cin<<i;

obj.set_account(int i);
obj.output(ostream out);

return 0;
}




How should i get BtnSubmit data on another Class

private HBox addHBox() {

    HBox hbox = new HBox();
    hbox.setPadding(new Insets(15, 12, 15, 12));
    hbox.setSpacing(10);   // Gap between nodes
    hbox.setStyle("-fx-background-color: #336699;");

    TextField txtSearch = new TextField ();
    Button btnSubmit = new Button("Submit");

    hbox.getChildren().addAll(txtSearch, btnSubmit);

    return hbox;
} } 

this show my button code on an class and i want to use that button on another class.

Basically, this is the code in my another class and i want to link BtnSubmit on this class, how should i do it?

   ConfigurationBuilder configBuilder = new ConfigurationBuilder();
    configBuilder.setOAuthConsumerKey("");
    configBuilder.setOAuthConsumerSecret("");
    configBuilder.setOAuthAccessToken("");
    configBuilder.setOAuthAccessTokenSecret("");

    //Create instance of Twitter for searching etc.
    TwitterFactory tf = new TwitterFactory(configBuilder.build());
    Twitter twitter = tf.getInstance();

    btnSubmit.setOnAction((javafx.event.ActionEvent event) -> {
        Query query = new Query(txtSearch.getText());
        query.setLang("en");
        QueryResult result;
        query.setCount(100);
        int count = 0; 

        try {
            result = twitter.search(query);
            List<Status> tweets = result.getTweets();
            for (Status tweet : tweets) {
               String userName = tweet.getUser().getName();
               long userId = tweet.getUser().getId();
             //Date creationDate = tweet.getCreatedAt();
               String tweetText = tweet.getText();
               count++;

      System.out.println("Tweet created by " + userName + "(" + userId + ")" + count);
      System.out.println("Tweet text " + tweetText);
             }
        }
        catch(TwitterException ex){
        }
    });




Why does this VB6 ActiveX Class Terminates Instantly?

Given the following ( extremely simple ) example :

VERSION 1.0 CLASS
BEGIN
  MultiUse = -1  'True
  Persistable = 0  'NotPersistable
  DataBindingBehavior = 0  'vbNone
  DataSourceBehavior  = 0  'vbNone
  MTSTransactionMode  = 0  'NotAnMTSObject
END
Attribute VB_Name = "Foo"
Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = False
Attribute VB_Exposed = False
Private Sub Class_Initialize()
    MsgBox "Initialized!"
End Sub

Private Sub Class_Terminate()
    MsgBox "Terminated! ( FFFUUUUUUUUU )"
End Sub

When I declare this class within another class and attempt to instantiate it :

'Bar Class
Dim FooClassObject As Foo
Private Sub Class_Initialize( )
    FooClassObject = New Foo
End Sub

Foo is instantiated, but then immediately terminates.

Why?




How can I define a node class, which extends another node class, in the metamodel of Soley Studio?

Any Soley Studio users?
I started to define the metamodel for my graph. I want to define two node classes (ProdFunction and ProdPart), which both extend another node class (ArchitectureRelated).

But everytime I check for errors or build the solution it gives mit the error:

"ArchitectureRelated" is a error type but a node type is expected

I tried different names for the class but it did not change. Are there special keywords to define a "node type"? The code for my node meta model is:

node class ProdFunction extends ArchitectureRelated{
mode:string;
name:string;
}

node class ProdPart extends ArchitectureRelated{
name:string;
partnumber:int;
hierLevel:int;
}




VB.NET class that with property based predefined values

I'm trying to create a Class called Nozzle. This class has properties that represent the nozzle Code, Type, Size and rating

Public Class Nozzle
   Public Property Code As CodeEnum
   Public Property Type As TypeEnum
   Public Property Size As Integer
   Public Property Rating As Integer
End Class

The nozzle size and rating are based by code (to get technical ASME B16.5 or EN 1092-2) lets call the code A & B

Now, I would like to have a list where I can find all to nozzle sizes and ratings based on the input.

The input sequence is fixed.

  1. For Code A there are type 1, 2, 3, 4, ..
  2. For Type 1 within: Code A there are size 1, 2, 3, 4, ..
  3. For Size 1 within: Type 1: Code A there are rating 1, 2, 3, 4, ..

(the sizes and types are just made up not the actual sizes)

It seems best for me to have an external document to hold the values rather than hard-code them. So it's easy for the client to add sizes and ratings.

What kind of document would suit best for this?

I know this question is probably very opinion based, but I searched a lot on this, and can't really find a good topic on this.




Put clickable Icon next to bootstrap navbar toggle

I would like to put a clickable icon next to the navbar toggle on a website using bootstrap.

I've tried playing with pull and align classes, but with no luck.

Regards




Setting a css class to a custom row in a table with backbone

I would like to insert a css class to a custom row, but i have no idea of how can i do it.

i thought it could work with "this.modelRows.models[0].$el.addClass('NewClass');"

Here's the code:

render: function () {
        var margin, i = 0, length = 0, tbody, self = this;

        this.modelRows = new Project.Collections.CalcCollection();

        for (i = 1; i <= 1; i++) {
            var modelCalc = new Project.Models.CalcModel();
            //modelCalc.set({ Description: 'Descr' + i});
            this.modelRows.add(modelCalc);
        }


        this.modelRows.models[0].set({ Research: 10 });
        this.modelRows.models[0].$el.addClass('NewClass'); //This is what i want to work

        this.viewRows = [];
        _.each(this.modelRows.models, function (linha) {
            self.viewRows.push(new Project.Views.RowCalc({ model: row }));
        });

        length = this.viewRows.length;
        tbody = this.$el.find(".tbCalcBody");
        for (i = 0; i < length; i++) {
            this.viewRows[i].render();
            tbody.append(this.viewRows[i].$el);
        }
        return this;
    }




C++ undefined reference to `Class::Ctor'

I have this error massage

In function 'int main()':| unused variable 'Bobi' In function `main':|

undefined reference to `Student::Student()'|

||=== Build failed: 1 error(s), 1 warning(s) (0 minute(s), 1 second(s)) ===|

Can you help me to fix this problem and check my method declaration

This is my main.cpp

    #include <iostream>
#include "Student.h"
using namespace std;

int main()
{
    Student *Bobi= new Student();

    return 0;
}

This is my header

    #ifndef STUDENT_H
#define STUDENT_H
#include <string>

class Student
{
    public:
        Student();
        virtual ~Student();
        std::string getName()
        {
            return this->name;
        }
        void setName(std::string name)
        {
            this->name=name;
        }
        int getNumber()
        {
            return this->number;
        }
        void setNumber(int number)
        {
            this->number=number;
        }
        std::string getSurname()
        {
            return this->surname;
        }
        void setSurname(std::string surname)
        {
            this->surname=surname;
        }
        double setDiploma1(double diploma1)
        {
            return this->diploma1;
        }
        void getDiploma1()
        {
            this->diploma1=diploma1;
        }
        double setDiploma2(double diploma2)
        {
            return this->diploma2;
        }
        void getDiploma2()
        {
            this->diploma2=diploma2;
        }
        double setIzpit1(double izpit1)
        {
            return this->izpit1;
        }
        void getIzpit1()
        {
            this->izpit1=izpit1;
        }
        double setIzpit2(double izpit2)
        {
            return this->izpit2;
        }
        void getIzpit2()
        {
            this->izpit1=izpit2;
        }
        double Bal(double setDiploma1,double setDiploma2,double setIzpit1,double setIzpit2)
        {
            double bal=setDiploma1+setDiploma2+setIzpit1+setIzpit2;
            return bal;
        }
    protected:
    private:
        int number;
        std::string name;
        std::string surname;
        double diploma1;
        double diploma2;
        double izpit1;
        double izpit2;
};

#endif // STUDENT_H

Student.cpp

#include "Student.h"
#include <iostream>
using namespace std;
Student::Student()
{
}
Student::~Student()
{
}




TimeTable function not working

I'm trying to write a code that'll generate a timetable. The function compiles fine but the results aren't what I'm expecting.

The method:

         public String generateTimeTable(){
    //2 arrays for all the months of the year and days of the week.
    String[] months = {"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"};
    String[] days = {"Mon","Tue","Wed","Thur","Fri","Sat","Sun"};



    DateTime today = new DateTime();
    DateTime start = today.plusDays(1).withTime(8, 0, 0, 0); // this makes it start at 8am the next day
    String finalString = "On" + " " + days[start.getDayOfWeek()-1] + " "+ start.getDayOfMonth() + " " + months[start.getMonthOfYear() - 1] + "\n"; //This is the string for the first day.
    // It should return something like "On Mon 13 February
    ArrayList<Course> list = listOfCourses(); //get a sorted list of courses



    while (start.toLocalDate().isBefore(this.startOfExams)) { // loop for everyday up until the start of exams
        String sub1 = list.get(0).toString() + "...from " + new Interval(start, start.plusHours(3)).toString().substring(11, 16) + " to " + new Interval(start, start.plusHours(3)).toString().substring(41, 46) + "\n";
        finalString += sub1;
        finalString += "\n";




        String break1 = "break...from " + new Interval(start.plusHours(3), start.plusHours(4)).toString().substring(11, 16) + " to " + new Interval(start.plusHours(3), start.plusHours(4)).toString().substring(41, 46) + "\n";
        // String break1 = "break..." + new Interval(start.plusHours(3), start.plusHours(4)) + "\n";
        finalString += break1;
        finalString += "\n";


        String sub2 = list.get(1).toString() + "..." + new Interval(start.plusHours(4), start.plusHours(7)) + "\n";
        finalString += sub2;
        finalString += "\n";


        String break2 = "LunchBreak...You need to eat! " + new Interval(start.plusHours(7), start.plusHours(8)) + "\n";
        finalString += break2;
        finalString += "\n";



        String sub3 = list.get(2).toString() + "..." + new Interval(start.plusHours(8), start.plusHours(10)) + "\n";
        finalString += sub3;
        finalString += "\n";


        String break3 = "break..." + new Interval(start.plusHours(10), start.plusHours(11)) + "\n";
        finalString += break3;
        finalString += "\n";


        String sub4 = list.get(3).toString() + "..." + new Interval(start.plusHours(11), start.plusHours(13)) + "\n";
        finalString += sub4;
        finalString += "\n";


        String break4 = "break..." + new Interval(start.plusHours(13), start.plusHours(14)) + "\n";
        finalString += break4;
        finalString += "\n";


        String sub5 = list.get(4).toString() + "..." + new Interval(start.plusHours(14), start.plusHours(15)) + "\n";
        finalString += sub5;
        finalString += "\n";


        String sub6 = list.get(5).toString() + "..." + new Interval(start.plusHours(15), start.plusHours((int) 15.5)) + "\n";
        //finalString += sub6;
        //finalString += "\n";


        start = start.plusDays(1); // Move along to the next day.

        finalString += "\n";
        finalString += "On" + " " + days[start.getDayOfWeek()-1] + " "+ start.getDayOfMonth() + " " + months[start.getMonthOfYear() - 1] + "\n";


    }
    return finalString + "EXAMM DAYYY!";


}

However after taking this data, I tried to test it with sample info:

                  public static void main(String[] args) {
    // TODO Auto-generated method stub
    LocalDate examStart = new LocalDate(2016, 3, 1);

    Course chem = new Course("Chemistry", 2, examStart);
    Course math = new Course("Mathematics", 5, examStart);
    Course phys = new Course("physics", 8, examStart);
    Course french = new Course("French", 5, examStart);
    Course Bio = new Course("Biology", 3, examStart);
    Course eng = new Course("English", 6, examStart);


    TimeTable tt = new TimeTable(2016, 3, 1);

    tt.addCourse(chem);
    tt.addCourse(math);
    tt.addCourse(phys);
    tt.addCourse(french);
    tt.addCourse(Bio);
    tt.addCourse(eng);

    //FIRST THINGS FIRST: complete testing of updating confidence.
    //tt.updateConfidence("French", 1);

    String finals = tt.generateTimeTable();

    System.out.print(finals);




}

But instead of printing out my timetable, it only prints out On Fri 1 Apr EXAMM DAYYY!

Anyone get why that may be so?




Array of moving objects stacking up

My question concerns creating an array of moving objects. The goal is to have each created "symbol" starts at x=200 when created and then moves along the x-axis. This is possible by creating individual objects, though when I try to make them appear in an array they just appear on top of each other (made the balls transparent so you can see them stack). Is there a way to create an array of individual array objects so that this doesn't happen.

int numSymbols = 100;
int symbolXPos;
int i;

Symbol[] symbols = new Symbol[numSymbols];   

void setup(){
for(int i = 0; i < numSymbols; i++){
   symbols[i] = new Symbol(); 
  }

  size(748,1024);
    }

    void draw(){
  background(255,255,255);
  i++;
  if(i > 10){
symbols[1].addSymbol(i);
  }
  if(i > 100){
symbols[2].addSymbol(i);
  }
  if(i > 200){
symbols[3].addSymbol(i);
  }

}

  int symbolY = 748-2*6-89-180;
  int symbolX = 200; 
  int symbolPos;
  boolean firstLoop = true;
int xSpeed;

class Symbol{

   void addSymbol(int xSpeed){

if(firstLoop == true){
symbolXPos = xSpeed;
firstLoop = false;
}else{

  xSpeed = symbolX + (xSpeed - symbolXPos);    

fill(0,0,0,20);
noStroke();
rect(xSpeed,symbolY, 36, 36, 18);
}
}
}




Additional Info to Arrays

Please, can anyone assist me on how to add the additional info (which is the 'rating') to the array already created. In my menu, option 5 gives me the option to 'add additional dvd details', which is the rating, as shown below.

        System.out.println("DVD System");
        System.out.println("1. Add a DVD");
        System.out.println("2. Remove a DVD");
        System.out.println("3. Check if DVD Shop is empty");
        System.out.println("4. Check if DVD Shop is full");
        System.out.println("5. Add Additional DVD details");
        System.out.println("6. DVD Details");
        System.out.println("7. Update DVD Length of Time in Store");
        System.out.println("8. Exit System");
        System.out.println();

In my switch menu, ive added the option to create a method that will do this as shown below:

        switch(option)
        {
            case 1: addDvd(dvd);
            break;
            case 2: removeDvd(dvd);
            break;
            case 3: checkIfEmpty(dvd);
            break;
            case 4: checkIfFull(dvd);
            break;
            case '5': addDetails(dvd);
            break;
            case 6: displayDetails(dvd);
            break;
            case 7: updateLengthTime(dvd);
            break;
            case 8: break;
            default: System.out.println("Invalid entry.");
        }

But the problem seems to lay in the following code, and I am not quite sure why this code is incorrect. It may be something obvious, but I just cant wrap my head around it. Here is all my potential code that I've managed to come up with so far:

private static void addDetails(DVDShop dvd)
{
    String dvdId; 
    int rating;

    System.out.println("Enter Dvd id: ");
    dvdId = EasyScanner.nextString();

    System.out.println();
    System.out.println("Enter Dvd Rating: ");
    rating = EasyScanner.nextInt();

    boolean ratingUpdated;
    dvd.rating(dvd1);
    if(ratingUpdated == false) //Meaning that it was NOT successful
    {
        System.out.println();
        System.out.println("Can not add new DVD. This list is full");
        System.out.println();
    }
    else
    {
        System.out.println();
        System.out.println("DVD added"); 
        System.out.println();
    }

}

Can someone please assist me and point out where I'm going wrong? I'd appreciate if I was corrected also, thanks.




Swift Replacing/Redefining Method or Class of Library

I'm searching quite a while now but I cannot find anything. Is there a possibility in Swift to supply an own implementation of a class or a method without touching the library. Subclassing would not be an option.

As Example from ios charts (http://ift.tt/1Mb9Klt) I only want to replace the LineScatterCandleRadarChartRenderer class (http://ift.tt/1V9b5f8) or the single method it is implementing. It is a subclass of a subclass of a subclass used somewhere in the library when plotting the chart.

What would be the best practice to do this?

I found an answer for python: Cast base class to derived class python (or more pythonic way of extending classes)




property of class doesnt restrict the attribute

So i made a class and want, that attribute hp stays always between 0 and maxhp In theory making hp a property should give me the wished result: Somehow it doesnt work though.

Is there way to link attributes for and back? So i have stored the position of the unit class object. At 2 places, once the attribute position which contains a [x,y] array and the other time its stored in 2 attributes x and y and each contains a int. Changing self.x or self.y should changes self.position and the other way around too.

 class units(object):

    def __init__(self,typus, position, stats):
        self.type = typus

        #they should be linked both directions
        self.position = position
        self.x = self.position[0]
        self.y = self.position[1]

        self.attack = stats[0]
        self.defense = stats[1]
        self.maxhp = stats[2]
        self.hp = self.maxhp

    def __repr__(self):
        text = "This a %s at position [%s,%s].\n  Attack: %s \n Defense: %s \n Hp : %s/%s \n "  \
               % (self.type,self.position[0],self.position[1],  self.attack, self.defense, self.hp, self.maxhp)
        return text


    # hp set to always be in between 0 and maxhp
    @property
    def hp(self):
        return self.__hp

    @hp.setter
    def hp(self, hp):
        if hp < 0:
            self.__hp = 0
        if hp > self.maxhp:
            self.__hp = self.maxhp
        else:
            self.__hp = hp

    def takedmg(self,dmg):
        self.hp -= max(dmg-self.defense, 0)
        if self.hp <= 0:
            self.alive = False
        return self.hp



p = units("peasant", [1,1],  [2,0,30])
p.takedmg(100)
print (p.hp)     # it should be 0!




Use keywords in class to call a specific method

Suppose a Python class has different methods, and depending on what the user specifies, a different method is carried out in the main function calculate().

In the example below the user needs to specify the keyword argument 'methodOne' or 'methodTwo'. If no or an incorrect keyword is specified it should default to 'methodOne'.

class someClass(object):
    def __init__(self,method=None):
        methodList = ['methodOne','methodTwo']
        if method in methodList:
            self.chosenMethod = method
        else:
            self.chosenMethod = self.methodOne

    def methodOne(self):
        return 1

    def methodTwo(self):
        return 2

    def calculate(self):
        return self.chosenMethod()

The above clearly does not work since method is a string and not a function. How can I select self.methedOne() or self.methedOne() based on my keyword argument method? In principle the following works:

def __init__(self,method=None):
    if method == 'methodOne':
        self.chosenMethod = self.methodOne
    elif method == 'methodTwo':
        self.chosenMethod = self.methodTwo
    else:
        self.chosenMethod = self.methodOne

But if I have more than two methods this becomes rather ugly. Is there a way to do this similar to my original code?




Updating details of an array (Classes and objects)

private static void updateLengthTime(DVDShop dvd)
{
    String dvdIdIn;



    boolean update;
    update = dvd.updateLenOfTime(1);
    if(update == false)
    {
        System.out.println("Sorry could not update at this time");
    }

    else

    {
        System.out.println("All information updated.");
    }

}

Would anyone please be able to tell me why the length time still displays '1' even though I have clicked the option to update the details multiple times

    public boolean updateLenOfTime(int lenOfTime)      
    if(isEmpty() == true) //meaning that the array is empty
    {
      return false;   
    }
    else
    {
      DVD.setLenOfTime(lenOfTime);
      return true;
    }



}

public boolean isEmpty() // Checking to see if the system is empty
{
    if(total == 0)
    {
        return true; // Meaning the system is empty
    }
    else
    {
        return false; // Meaning the system is NOT empty  
    } 
}


public static void setLenOfTime(int lenOfTimeIn)
{
   lenOfTime = lenOfTimeIn;
}

Additional information added to help with the diagnostic.




TypeScript: Access global type hidden by local class definition?

Lets assume i have a class which has the same name as an previously defined type which is defined inside lib.d.ts. How would i make use of that type within this class.

For example, i have the class Event, which has to deal with the browsers Event object, which is defined as an interface in lib.d.ts.

export class Event { // own definition of Event which hides original Event

  public dealWithBrowserEvent(event: Event): void { // Event object defined by lib.d.ts
    // deal with it
  }

}

How would i tell Typescript that this are two different types. Of course i could simply rename my class, but i don't want to do that, because the name is perfect for my use case.




mercredi 30 mars 2016

Instance variables in Python? Keep getting an assignment error

Hi I am trying to write a simple program that calculates the base content of each base in DNA. I keep getting an assignment error 'no_c referenced before assignment' or 'no_c not defined" in my current configuration and I can't figure out how to solve the issue.

#!/usr/bin/python

#computing the atgc content of a DNA string 


class Base_counter(object):
    def __init__(self, DNA):
        self.DNA = DNA
        no_c = 0
        no_a = 0
        no_g= 0
        no_t= 0

    def c_counter(self):
        for base in self.DNA:   
            if base == 'c':
                no_c = no_c + 1 
        return no_c

    def g_counter(self):
        for base in self.DNA:   
            if base == 'g':
                no_g+=1 
        return no_g

    def a_counter(self):
        for base in self.DNA:   
            if base == 'a':
                no_a+=1 
        return no_a

    def t_counter(self):
        for base in self.DNA:   
            if base == 't':
                no_a+=1 
        return no_t

    def gc_percentage(self):
        return no_c + no_g / len(self.DNA)

    def at_percentage(self):
        return no_a + no_t / len(self.DNA)

    def g_percentage(self):
        return no_g / len(self.DNA)

    def a_percentage(self):
        return no_a / len(self.DNA)

    def t_percentage(self):
        return no_t / len(self.DNA)

    def c_percentage(self):
        return no_c / len(self.DNA)     

def main():
    dna= 'gcgctat'
    analyzer = Base_counter(dna)

    print analyzer.no_c
    print analyzer.c_counter()
    #print analyzer.c_percentage()

if __name__ == '__main__':
    main()




How to allow Object creation of a class on only particular classes in PHP?

In PHP, let there be four classes A, B, C, and D. None of them inherits the other. They are all independent classes. Now, I want only B and C to be able to create Objects of the class A. D Should not be able to create the Object of class A.

Can this be done in PHP? If So, how? I tried refreshing my object oriented concepts, but can't seem to find an appropriate answer in PHP.

Little help would be much appreciated.




UML class diagram - represent attribute with initial value

How is an attribute with initial value (such as a static constant) represented in UML?

public class Foo {
    public static final int BAR = 17;
}




Factual API and coldfusion

I took the java implementation of the Factual API (reference http://ift.tt/zaz9Cm) and made a JAR file for factual. I did this by opening a new project in eclipse with the factual java files and then exporting to a new jar file.

I put that jar file in my coldfusion installation's /WEB-INF/lib/ folder.

After restarting Coldfusion, I tried to create a new cfobject like so

<cfscript>

     // Initialize the Java class. 
     factualClass=CreateObject("java", "src.main.java.com.factual.driver.Factual"); 

</cfscript>

I get an error indicating that it cannot find the Factual class.

Can anybody give me some guidance?




Tell if two 3D cubes are intersecting

I am trying to come up with some code that tells me if two 3D objects are intersecting. My general idea for this is to get each point on the CubeA so 8 points and see if CubeB's 8 points are equal or to the right. I am not sure where to go from here.




Where to put required behavior on close in Python

I have a class that creates a temporary file on construction and should remove it once it is finished. Note that I understand creating a temporary file may not be the ideal solution to the original problem but assume that that cannot be changed.

Which is the most ideal place to delete the file?

Option 1:

import sys
import os

class Foo:
    def __init__(self):
        self.file = open("temp.txt", 'wb')

    def do_something(self):
        # ...

    def close(self):
        self.file.close()
        os.remove("temp.txt")

foo = Foo()
foo.do_something()
foo.close()

Option 2:

import sys
import os

class Foo:
    def __init__(self):
        self.file = open("temp.txt", 'wb')

    def do_something(self):
        # ...

    def __del__(self):
        self.file.close()
        os.remove("temp.txt")

with Foo() as foo:
    foo.do_something()

I'm hesitant to use option 2 because I've heard it is a bad practice to put required actions in the destructor. However, option 2 seems more readable to me.




C++ State change not deleting old state?

I'm working with Visual Studio and SDL to create a simple RPG game, however I noticed (when adding the music) that the music kept playing when I changed the gamestate, even though I stoped it in the destructor. If I stop the music right before changing the state though, the music stops (which made me realize that everytime i change the game state, the old state still remains, which I assume is using up a lot of memory (if i make the game big and change the state a lot).

My state classes are set up like this:

// Gamestate.h
#pragma once
// includes here

class GameState
{
public:
  virtual ~GameState() {}
  virtual void Update() {}
  virtual void HandleEvents() {}
  virtual void Logic() {}
  virtual void Draw(Graphics& gfx) {} // Graphics is my own class

  GameState* getCurrentState()
  {
    return currentState;
  }

protected:
  SDL_Renderer* renderer;
  GameState* currentState;
  Timer timer; // my own timer class
};

// GameStates.h; different than GameState.h
#pragma once
// includes here

class IntroGameState : public GameState
{
public:
  IntroGameState(SDL_Renderer* renderer, KeyboardClient& kbd);
  ~IntroGameState();
  void HandleEvents();
  void Logic();
  void Draw(Graphics& gfx);

private:
  Mix_Music* theme;
  // other variables defined here
};

// GameStates.cpp
IntroGameState::IntoroGameState(SDL_Renderer* renderer, KeyboardClient& kbd)
{
  GameState::renderer = renderer;
  currentState = this;
  timer.Start();

  theme = Mix_LoadMUS("theme.wav");
  Mis_PlayMusic(theme, 0);
}
IntroGameState::~IntroGameState()
{
  // This line does nothing (destructor not being called?)
  Mix_HaltMusic();

  delete theme;
  theme = NULL;
};
void IntroGameState::Logic()
{
  if (timer.ElapsedTime() >= 5) // if 5 seconds pass
  {
    // This line works
    Mix_HaltMusic();
    // I tried:
    // delete this;
    // delete currentState;
    // currentState = NULL; realized this was pointless when I just initialize it next

    currentState = new MovieSceneState(renderer, kbd);
}

// Game.cpp (where i actually change the state
Game::Game()
{
  // currentState here is defined within game.h
  currentState = new IntroGameState(renderer, kbd);
}
void Game::ComposeFrame()
{
  currentState->HandleEvents();
  ChangeState();
  currentState->Logic();
  currentState->Draw(gfx);
}
void ChangeState()
{
  GameState* s = currentState->GetCurrentState();
  currentState = s;
}




What is the right way of doing javascript inheritance [duplicate]

This question already has an answer here:

Asuming:

function Animal(name) {
  this.name = name;
}
Animal.prototype.move = function() {
  // move
};
function Rabbit() {
  // do rabbit stuff
}

I've seen people do inheritance differently. See code below, but Which is the correct way? They all seem to work the same way

Rabbit.prototype = Rabbit.prototype;
// or
Rabbit.prototype = Rabbit.prototype.__proto__;
// or
Rabbit.prototype = new Rabbit();




Access class from class effectively

I happen to be in situation where I use two or more times the same(or a little bit altered) functions in more classes more often than I should. Therefore, it seems reasonable to me making either a new class for them, or a completely separated package. The functions I want to separate use self of some other existing classes.

I would like to ask what is the most effective way to access an another existing class from my custom functions "pack"? I came up with passing the existing class into a new instance of my new class as an argument the way I pass and set for it a variable through __init__(self, existing), though I don't think this is the effective way.

Is there something else for me that doesn't take longer to code and is efficient?




Add an array of multiple choice to jdialog [duplicate]

This question is an exact duplicate of:

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class VocabHelper {
private JFrame mainFrame;
private JPanel mainPanel;
private JPanel animalPanel;
public JDialog quizDialog;

public VocabHelper() {

    mainGUI();
}

public static void main(String[] args) {
    VocabHelper vocabHelper = new VocabHelper();
    vocabHelper.showActionEvents();
}

private void mainGUI() {
    mainFrame = new JFrame("VocabHelper");
    mainFrame.setSize(500, 500);
    mainFrame.setLayout(new GridLayout(3,1,10,0));




    mainFrame.add(new Label("Vocab Helper"));

    mainFrame.add(new Label("Press Start to take Quiz")); 

    mainPanel = new JPanel();
    mainFrame.add(mainPanel);



    mainFrame.setVisible(true);
}

public void quizGUI() {
    quizDialog = new JDialog();
    quizDialog.setName("Quiz");
    quizDialog.setSize(500,500);
    quizDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    quizDialog.setVisible(false);

    addQuizEvent();
}

public void showActionEvents() {

    JButton quizButton = new JButton("Start");
    /*JButton biologyButton = new JButton("Biology");
    JButton geologyButton = new JButton("Geology");
    JButton historyButton = new JButton("History");
    JButton sportsButton = new JButton("Sports");
    JButton techButton = new JButton("Technology");*/

    quizButton.setActionCommand("Start");
    /*biologyButton.setActionCommand("Biology");
    geologyButton.setActionCommand("Geology");
    historyButton.setActionCommand("History");
    sportsButton.setActionCommand("Sports");
    techButton.setActionCommand("Technology");*/

    quizButton.addActionListener(new ButtonClickListener());
    /*biologyButton.addActionListener(new ButtonClickListener());
    geologyButton.addActionListener(new ButtonClickListener());
    historyButton.addActionListener(new ButtonClickListener());
    sportsButton.addActionListener(new ButtonClickListener());
    techButton.addActionListener(new ButtonClickListener());*/

    mainPanel.add(quizButton);
    /*mainPanel.add(biologyButton);
    mainPanel.add(geologyButton);
    mainPanel.add(historyButton);
    mainPanel.add(sportsButton);
    mainPanel.add(techButton);*/

    mainFrame.setVisible(true);
}

public void addQuizEvent() {
    JButton nextButton = new JButton("Next");
    nextButton.setActionCommand("Next");
    nextButton.addActionListener(new ButtonClickListener());
    quizDialog.add(nextButton);
    quizDialog.setVisible(true);
}

private class ButtonClickListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        if (command.equals("Start")) {
            quizGUI();
             }
         }
     }
 }

//Then there are these classes

// the classes that will be used for logic

  import java.util.ArrayList;

/**
   A question with multiple choices.
*/
     public class ChoiceQuestion {
     private ArrayList<String> choices;

   /**
      Constructs a choice question with no choices.
   */
       public ChoiceQuestion() {
       choices = new ArrayList<String>();
      }

   /**
      Adds an answer choice to this question.
      @param choice the choice to add
      @param correct true if this is the correct choice, false otherwise
   */
       public void addChoice(String choice, boolean correct) {
       choices.add(choice);
        if (correct) {
         // Convert choices.size() to string
           String choiceString = "" + choices.size();
           setAnswer(choiceString);
        }
     }


     public void display() {
        // Display the question text
        super.display();
        // Display the answer choices
         for (int i = 0; i < choices.size(); i++) {
            int choiceNumber = i + 1;
          System.out.println(choiceNumber + ": " + choices.get(i));     
         }
       }
      }

//then a class that is the actual quiz
//a class where the questions are all stored



import java.util.ArrayList;
     import java.util.Scanner;

    /**
      A quiz contains a list of questions.
     */
public class Quiz {
   private ArrayList<Question> questions;

   /**
      Constructs a quiz with no questions.
   */
   public Quiz() {
      questions = new ArrayList<Question>();
   }

   /**
      Adds a question to this quiz.
      @param q the question
   */
   public void addQuestion(Question q) {
      questions.add(q);
   }

   /**
      Presents the questions to the user and checks the response.
   */
   public void presentQuestions() {
      Scanner in = new Scanner(System.in);

      for (Question q : questions) {
         q.display();
         System.out.print("Your answer: ");
         String response = in.nextLine();
         System.out.println(q.checkAnswer(response));
      }
   }
}

So really what what my question is how do i edit the Jdialog so that i can have a multiple choice question (an array of them) so when the user presses the start button he can take a so called quiz and after a set number of questions he can get a score. I just need help implementing one question into the jdialog after that if there are any advice thank you so much for you help!




3 Vb.net Forms - Can get Ttitle from one but not the other?

Ok so I have 3 forms in my solution file. Each one has a Public class in it.

(Form1 - MainControlWindow Class), (Form3 - ShaneTestFormVersion2 Class), (New_Popup_Chords - New_Popup_Chords Class)

The program starts off in Form1 in the MainControlWindow Class, i give it a title name and I dim the second form, ShaneTestFormVersion2 class as frmSongDisplay2 and display it.

        Me.Text = "Window_A"
        Dim frmSongDisplay2 As New ShaneTestFormVersion2
        frmSongDisplay2.Show()

And then, in the ShaneTestFormVersion2 class on the Form3.vb page, i dim the last form as a dialog so the second forms processing halts while its open:

        Me.Text = "Window_B"
        Dim NewChordsPopup As New New_Popup_Chords
        NewChordsPopup.ShowDialog()

Now this all works fine and dandy until I try to use the 3rd form (NewChordsPopup) to display the window titles of the other 2:

    MsgBox(ShaneTestFormVersion2.Text) 'Second Form opened
    MsgBox(MainControlWindow.Text) 'First Form Opened

The msgsboxes come up as the default window title as "Form3" not "Window_B", but the first window msgbox comes up fine as "Window_A".

The titles were all set the same way, the windows were dimed and displayed the same way. Why does ShaneTestFormVersion2 in Form3 come up as "Form3" instead of the title i assigned it, "Window_B"?

Side Note:

I also notice that I can access MainControlWindow variables (MainControlWindow.Var1) fine (Public Var1) but cant access ShaneTestFormVersion2 varables (ShaneTestFormVersion2.Var1) without it being "Public Shared Var1".




Java Sudoku game [on hold]

I write my sudoku software in Java 8. I have Cell class, where is an array for visualize candidates and result. This is my array for components jLabels:

private final static JLabel[][] candidates = new JLabel[3][3];

Here are many methods for manage cell, (getCandidateState, getResult, setCandidateState, setResult, and many others.. Also I have a Grid class, where are an other array for cells:

private final Cell[][] screenCells = new Cell[9][9];

How I call cells method for example screencells[row][col]'s setResult? Maybe it was too dificult, but the program is harder. :)

Please help me hurry,

Thanks,




C++ - Conditional virtual functions

My question is, if I have something like

class Base {
 ...
 public:
  virtual void func();
}

void Base::func() {
 //Implementation # 1
}

class Derived1 : public Base {
 ...
 public:
  void func();
}

void Derived1::func() {
 //Implementation # 1
}

class Derived2 : public Base {
 ...
 public:
  void func();
}

void Derived2::func()
 //Implementation # 1
}

class Derived3 : public Base {
 ...
 public:
  void func();
}

void Derived3::func() {
 //Implementation # 2
}

What I'm trying to do is I want Derived1 and Derived2 to use the implementation of func() that was used in Base, but I want Derived3 to use func() a little differently. The problem is, if I make func() virtual in Base, then both Derived1 and Derived2 will need to implement it differently which I don't want. However, if I don't make it virtual, then all derived classes will have the same implantation for func(). How can I get past this problem?




Finding Main Class in "Hello World" program in Java

I have a seemingly simple program in Java, but when I run it, I get the error:

Error: Could not find or load main class

Here is my code.

public class HelloPrinter
{
    public static void main(String[] args)
    {
        System.out.println("Hello, World!");
    }
}

I'm entirely new to the Java language, and I don't know what else to do. My program file is named "hello_world.java", and when attempting to run the program, I type in "java hello_world.java". Am I doing something fundamentally wrong? I've also attempted "java -cp hello_world", but that gave me the same error.

What am I doing wrong?




Is it possible to return a child class from the constructor of it's parent class

I know this doesn't work this way, since the constructor of a class is a void:

class ParentClass
{
    public ParentClass(int case)
    {
       if(case==1) 
           return new ChildClass1();
       else 
           return new ChildClass2();
    }
}

Is there any way of doing this.




Add multiple choice to Dialog and make it functioning

plz help i have 48 hours to do all of this.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class VocabHelper {

    private JFrame mainFrame;

    private JPanel mainPanel;

    private JPanel animalPanel;

    public JDialog animalDialog;

    private JLabel titleLbl;

private JLabel subtitle;

//Call main GUI

public VocabHelper() {

    mainGUI();
}

//Main Method

public static void main(String[] args) {
    VocabHelper vocabHelper = new VocabHelper();
    vocabHelper.showActionEvents();
}

//Edit the mainGUI

private void mainGUI() {
    mainFrame = new JFrame("VocabHelper");
    mainFrame.setSize(500, 500);


    /*titleLbl = new JLabel("Vocab Helper", JLabel.CENTER);
    subtitle = new JLabel("Choose a category to continue", JLabel.CENTER);
    mainFrame.add(titleLbl);
    mainFrame.add(subtitle);*/

    mainFrame.addWindowListener(new WindowAdapter() {
        public void windowClosing(WindowEvent windowEvent) {
            System.exit(0);
        }
    });
    mainPanel = new JPanel();
    mainFrame.add(mainPanel);
    mainFrame.setVisible(true);
}

//Create quizGUI

public void quizGUI() {
    quizDialog = new JDialog();
    quizDialog.setName("Quiz 1");
    quizDialog.setSize(500,500);
    quizDialog.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
    quizDialog.setVisible(false);

    addQuizEvent();
}

//add Buttons and listeners

public void showActionEvents() {

    JButton quizButton = new JButton("quiz");
    JButton biologyButton = new JButton("Biology");
    JButton geologyButton = new JButton("Geology");
    JButton historyButton = new JButton("History");
    JButton sportsButton = new JButton("Sports");
    JButton techButton = new JButton("Technology");

    quizButton.setActionCommand("Quiz");
    biologyButton.setActionCommand("Biology");
    geologyButton.setActionCommand("Geology");
    historyButton.setActionCommand("History");
    sportsButton.setActionCommand("Sports");
    techButton.setActionCommand("Technology");

    QuizButton.addActionListener(new ButtonClickListener());
    biologyButton.addActionListener(new ButtonClickListener());
    geologyButton.addActionListener(new ButtonClickListener());
    historyButton.addActionListener(new ButtonClickListener());
    sportsButton.addActionListener(new ButtonClickListener());
    techButton.addActionListener(new ButtonClickListener());

    mainPanel.add(QuizButton);
    mainPanel.add(biologyButton);
    mainPanel.add(geologyButton);
    mainPanel.add(historyButton);
    mainPanel.add(sportsButton);
    mainPanel.add(techButton);

    mainFrame.setVisible(true);
}

//add events to quiz dialog this is where i want to create the multiple choice questins the classes will be below.

public void addQuizEvent() {
    JButton nextButton = new JButton("Next");
    nextButton.setActionCommand("Next");
    nextButton.addActionListener(new ButtonClickListener());
    quizDialog.add(nextButton);
    quizDialog.setVisible(true);
}

//When button quiz is pressed open dialog

private class ButtonClickListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
        String command = e.getActionCommand();
        if (command.equals("Quiz")) {
            quizGUI();
        }
    }
}

}

//Class tester for the multiple choice im thinking this is what goes in the dialog i just dont know how.

public class QuizTester
{
public static void main(String[] args)
{

//Multiple choice question
  ChoiceQuestion second = new ChoiceQuestion();
  second.setText("In which country was the inventor of Java born?");
  second.addChoice("Australia", false);
  second.addChoice("Canada", true);
  second.addChoice("Denmark", false);
  second.addChoice("United States", false);

//create quiz and add the questions to the quiz then present the quiz
  Quiz q = new Quiz();
  q.addQuestion(first);
  q.addQuestion(second);
  q.presentQuestions();

} }

//new class for multiple choice logic

import java.util.ArrayList;

/** A question with multiple choices. */

public class ChoiceQuestion {
private ArrayList<String> choices;

/** Constructs a choice question with no choices. */

public ChoiceQuestion()
{
   choices = new ArrayList<String>();
}

/** Adds an answer choice to this question. @param choice the choice to add @param correct true if this is the correct choice, false otherwise */

 public void addChoice(String choice, boolean correct)
 {
  choices.add(choice);
  if (correct) 
  {
     // Convert choices.size() to string
     String choiceString = "" + choices.size();
     setAnswer(choiceString);
  }

}

public void display()
{
    // Display the question text
    super.display();
    // Display the answer choices
    for (int i = 0; i < choices.size(); i++)
    {
      int choiceNumber = i + 1;
      System.out.println(choiceNumber + ": " + choices.get(i));     
      }
    }
 }

//class for the quiz where the quiz is created.

  import java.util.ArrayList;
  import java.util.Scanner;

/** A quiz contains a list of questions. */

  public class Quiz
  {
  private ArrayList<Question> questions;

/** Constructs a quiz with no questions. */

 public Quiz()
 {
   questions = new ArrayList<Question>();
 }

/** Adds a question to this quiz. @param q the question */

 public void addQuestion(Question q)
 {
   questions.add(q);
 }

/** Presents the questions to the user and checks the response. */

 public void presentQuestions()
 {
    Scanner in = new Scanner(System.in);

    for (Question q : questions)
    {
       q.display();
       System.out.print("Your answer: ");
       String response = in.nextLine();
       System.out.println(q.checkAnswer(response));
   }
}

}




Making a custom class in c++ with constructor values

I'm still learning c++ and have a lot more experience with Java. In Java, creating a class can be as simple as this:

public class vertex 
{

public double x, y, z;

 public boolean eliminated = true; 


 public vertex(double x, double y, double z)
 {
     //vertex constructor
 }

}

I'm trying to do something pretty much identical in C++, save for built in "get" functions for returning the values that should be set when creating an instance of the class, and want to know if my syntax is correct. Here is the class:

#include <iostream>
#include <stdlib.h>

using namespace std;

class Vertex // Standard way of defining the class
{

public:
  // This means that all of the functions below this(and any variables) are accessible to the rest of the program.

    Vertex(double x, double y, double z);
    //constructor

    double getX();
    double getY();
    double getZ();

    double x;
    double y;
    double z;


};

double Vertex:: getX()
{
    return x;
}

I would also like advice on creating a class that has instances of custom classes like the one aboce within them.




How can I Create Classes with dynamically created names

I need to write data to a class from my app config file. The number of classes that I will need to create is dependent on the length of an array I am reading from my app.config like so:

char[] activeConnArray = ConfigurationManager.AppSettings.Get("ActiveConnection").ToArray();

I am wanting to dynamically create the classes like so:

for (int i = 1; i < activeConnArray.Length; i++)
            {
                string className = "Conn" + i;
                Conn thisClass = new Conn();
                thisClass.SectionNumber = activeConnArray[i];
                thisClass.SqlServer = ConfigurationManager.AppSettings["SQLServer_" + activeConnArray[i]];
                thisClass.Database = ConfigurationManager.AppSettings["Database_" + activeConnArray[i]];
                thisClass.Username = ConfigurationManager.AppSettings["Username_" + activeConnArray[i]];
                thisClass.Password = ConfigurationManager.AppSettings["Paassword_" + activeConnArray[i]];
            }

Basically what I would like to do is replace "thisClass" with my className variable, or find another way to dynamically create the class name. If this is not possible I may have to store this data in a dictionary but I would really like to use a class. Thanks




Declaring variables within if/else block [duplicate]

This question already has an answer here:

I'm writing a program which creates a variable of an instance of a certain class if the first command line argument is "-1," and an instance of one of its child classes otherwise. The parent and child class share all the same methods and method names, but the child class overrides the parent for some of them. In other words the rest of the program after the declaration is exactly the same regardless of which class I use. Here's the declaration I have at the moment:

    if(args[0].compareTo("-1") == 0){
        BST Tree = new BST();
    }
    else{
        RBT Tree = new RBT();
    }

Which throws a "cannot be resolved" error when Tree is referenced later. Is there any solution to this problem without a bunch of redundant code? I could obviously just put the entire main function within these if/else blocks but I'd like to avoid that if there's a more concise solution.




How do I add this code into my Flash Project?

I'm making an animated movie with Flash and I found this code for a cool bouncing ball effect. I'm unsure about how to add it to my project in Flash and would appreciate a walkthrough of it! Thanks!

CODE:

private const NUM_BALL:int = 24;
private var loadingBall:Vector.<Shape> = new Vector.<Shape>(NUM_BALL);
private var timeStep:int = 0;
private const BALL_HEIGHT:int = 40;

public function animateBalls(e:Event):void
{
    for (var i:int = 0; i < NUM_BALL; i++ )
    {
        loadingBall[i].graphics.clear();
        loadingBall[i].graphics.beginFill(0x0B5F95);
        loadingBall[i].graphics.drawCircle(455+5*i,getY(i,timeStep),2);
    }
    timeStep++;
}

public function getY(i:int, t:int):int
{
    return 260 + BALL_HEIGHT/2 * (1 + Math.sin((timeStep * (i/500 + 0.02)) % 2*Math.PI));
}




Python - How to create more then one object in a single class?

I am trying to instantiate more then one object in a single class. I am trying to instantiate them in the class instead of the main function. I am new to python, so trying to learn. Example, I have this piece of code, my input file is a text file with all strings. I want to instantiate the object when my regex in region is true and/or subregion is true. I want to instantiate them there and NOT in the main function. How can I do that? since everytime I run my code I can have zero or one or two objects:

class Tracker(object):

  def __init__(self):
      self.region = ""
      self.subregion = ""

  def updateRegion(self,input):
      if self.endingRegion:
          self.region = ""
      if self.endingSubRegion:
         self.subregion = ""

      #Regions
      temp = re.search(r'CLI Command: \'(.*)\'', input)
      if temp:
          self.region = temp.group(1)
          print self.region

      #SubRegions  
      temp = re.search(r'Equipped Type \(if different\)',input)
      if temp:
         self.subregion = "Equipped Type"
         print self.subregion


def main():
  with open ('/home/thamer/TS_ncren202_XRS-20_20150624_12.0.R6.txt','r') as f:
    tracker = Tracker()
    for line in f: 
      tracker.updateRegion(line)
      region = tracker.getRegion()
      subregion = tracker.getSubRegion()

if __name__ == '__main__':
  main()




Why are there 2 identical class options for Visual C# in Visual Studio 2015?

I have seen this before when working in Visual Studio and always wondered why. I could not find any explanation online.

In Visual Studio Professional 2015 (May be the case in other versions but I have not tested) when adding a new class to a project

Right click project --> Add --> class -

I see 2 seemingly identical options for Visual C# classes. The description of these are exactly the same. I have tried adding both and can not find any difference in the 2.

Is this a bug? Or does anybody know why I see 2 different Class options?

vs class




usage of explicit keyword for constructors

I was trying to understand the usage of explicit keyword in c++ and looked at this question on SO What does the explicit keyword in C++ mean?

However, examples listed there (actually both top two answers) are not very clear regarding the usage. For example,

// classes example
#include <iostream>
using namespace std;

class String {
public:
    explicit String(int n); // allocate n bytes to the String object
    String(const char *p); // initializes object with char *p
};

String::String(int n)
{
    cout<<"Entered int section";
}

String::String(const char *p)
{
    cout<<"Entered char section";
}

int main () {

    String mystring('x');
    return 0;
}

Now I have declared String constructor as explicit, but lets say if I dont list it as explicit, if I call the constructor as,

String mystring('x');

OR

String mystring = 'x';

In both cases, I will enter the int section. Until and unless I specify the type of value, it defaults to int. Even if i get more specific with arguments, like declare one as int, other as float, and not use explicit with constructor name and call it this way

String mystring(2.5);

Or this way

String mystring = 2.5;

It will always default to the constructor with double as argument. So, I am having hard time understanding the real usage of explicit. Can you provide me an example where not using explicit will be a real failure?




How to define member functions of templated class outside? [duplicate]

This question already has an answer here:

I've write this:

myclass.h

template<typename T> class a {
    std::queue<T> q;
    void fun(T b);
}

myclass.cpp

#include "myclass.h"
template<typename T> a<T>::fun(T b){
    q.push(b);
}

main.cpp

#include "myclass.h"
struct c{int a;};
myclass test<c>;
blah...

And then I got this:

error LNK2019: UNRESOLVED EXTERNAL SYMBOL "public: void __thiscall myclass<struct c>::fun(struct c b)" (???),referenced by xxx

How to fix it?