lundi 29 février 2016

Error in Returning a Class Object in C++

I've been working on a Matrix library for personal use lately. I've tried writing code that returns my Matrix class (such as operator overloads, transformations, and inversions), but a strange error occurs. Visual Studio says that it throws a break point, possibly due to a corrupted heap, and then it says something about a debug error. I've tried several members of my code, and only the code that returns a Matrix fails in this manner.

I was thinking about passing a preallocated object's pointer through the member's arguments, but that just doesn't work with the operator overloads apparently. Any help? Here's the code:

//In Matrix.cpp
Matrix Matrix::operator+(const Matrix& fuz)
{
if (( fuz.data.size() == this->getSize()[0]) && (fuz.data[0].size() == this->getSize()[1]))
{
    Matrix ret = *this;
    for (int i = 0; i < this->getSize()[0]; i++)
    {
        for (int j = 0; j < (int) this->getSize()[1]; j++)
        {
            ret[i][j] += fuz.data[i][j];
        }
    }
    return ret; //Error
}
return *(new Matrix(1, 1));
}

//In ProjectSapphire.cpp (entry point)
//Within the main method
Matrix test = *(new Matrix(2,3));

int size[] = { test.getSize()[0], test.getSize()[1] };

test[0][0] = 1;
test[0][1] = 2;
test[0][2] = 3;
test[1][0] = 4;
test[1][1] = 5;
test[1][2] = 6;

Matrix foo = test;

Matrix deet = foo + test; //Error




Sharing a piece of code with methods inside a class in Python

I started making a draft for one of the classes that are supposed to be used in my programm and I first wrote this piece of code:

import math
import numpy as np

R = 6.371e6

phi_src, theta_src = 10, 40
phi_det,theta_det = -21, 10

depth_src, depth_det = 0,0 # both on the surface

l = 0

class Trajectory:

    def __init__(self,
                 phi_src,
                 theta_src,
                 phi_det,
                 theta_det,
                 depth_src,
                 depth_det,
                 l):

        self.phi_src = phi_src
        self.theta_src = theta_src
        self.phi_det = phi_det
        self.theta_det = theta_det
        self.depth_src = depth_src
        self.depth_det = depth_det
        self.l = l
    @property

    def r(self):
        r_src = R - self.depth_src
        r_det = R - self.depth_det

        x_src = r_src * math.cos(self.phi_src) * math.cos(self.theta_src)
        y_src = r_src * math.cos(self.phi_src) * math.sin(self.theta_src)
        z_src = r_src * math.sin(self.phi_src)

        x_det = r_det * math.cos(self.phi_det) * math.cos(self.theta_det)
        y_det = r_det * math.cos(self.phi_det) * math.sin(self.theta_det)
        z_det = r_det * math.sin(self.phi_det)

        coord_src = np.array((x_src, y_src, z_src))
        coord_det = np.array((x_det, y_det, z_det))

        L = np.linalg.norm(coord_src - coord_det)

        return math.sqrt(r_src**2 + self.l * (1.0 - L - (r_src - r_det) * (r_src + r_det)/L))

    def phi(r):
        pass


trajectory = Trajectory(phi_src,theta_src,phi_det,theta_det,depth_src,depth_det,l)

print(trajectory.r)

But then realized that the

        r_src = R - self.depth_src
        r_det = R - self.depth_det

        x_src = r_src * math.cos(self.phi_src) * math.cos(self.theta_src)
        y_src = r_src * math.cos(self.phi_src) * math.sin(self.theta_src)
        z_src = r_src * math.sin(self.phi_src)

        x_det = r_det * math.cos(self.phi_det) * math.cos(self.theta_det)
        y_det = r_det * math.cos(self.phi_det) * math.sin(self.theta_det)
        z_det = r_det * math.sin(self.phi_det)

        coord_src = np.array((x_src, y_src, z_src))
        coord_det = np.array((x_det, y_det, z_det))

        L = np.linalg.norm(coord_src - coord_det)

part is common for all the methods of the class and hence there's no point in calculating it numerous times in every method, this piece should be shared with all the methods. What would be the best way to do that? Do I have to put it into the __init__ method? I've heard it's not a good practice to make any calculations inside the __init__ method.




Data will be in a two-dimensional data array as follows. getting issue while running booktest.

Im having issue with below, java code. so far I've done this.

   BookTest.java:24: error: class expected
(dataArray[i][5]), new Book(double.parseDouble(dataArray[i][6]),dataArray[i][7])));
                                   ^
BookTest.java:24: error: ')' expected
(dataArray[i][5]), new Book(double.parseDouble(dataArray[i][6]),dataArray[i][7])));

Write class, Publisher, with attributes name and state

public class Publisher

{
    private String name;
     private String state;

public Publisher()
{
    setName("");
    setState("");
}

public Publisher(String n, String s)
{
    setName(n);
    setState(s);
}

public void setName(String n)
{
    name = n; 
}

public void setState(String s)
{
    state = s;
}

public String getName()
{
    return name;
}

public String getState()
{
    return state;
}

public String toString()
{
    return ("Name:"+ name + "State:" + state);
}

}

Write Book class with attributes, title, author, isbn, publisher, and price. Book class has method calculateCharge that accepts the quantity sold and returns the total charge.

  public class Book 
{
private String title;
private String author;
private String isbn;
private Publisher publisher;
private double price;

public Book()
{
    setTitle("");
    setAuthor("");
    setIsbn("");
    setPublisher(new Publisher());  
    setPrice(0.0);
}

public Book(String t, String a, String i, Publisher Publisher, double m)  

{
    setTitle(t);
    setAuthor(a);
    setIsbn(i);
    setPublisher(publisher);
    setPrice(m);

 }

 public void setTitle(String t)
 {
    title = t;
 }

 public void setAuthor(String a)
 {
    author = a;
 }
 public void setIsbn(String i)
 {
    isbn = i;
 }
 public void setPublisher(Publisher publisher) 
 {
    this.publisher = publisher;
 }
 public void setPrice(double m)
 {
    price = m ;
 }

 public String getTitle()
 {
    return title;
  }
  public String getAuthor()
  {
    return author;
  }
  public String getIsbn()
  {
    return isbn;
  }

  public Publisher getPublisher()
  {
    return publisher;
  }
  public double getPrice()
  {
    return price;
  }

public double calculatecharge(int qtySold)
{
    double totalCharge; 
    totalCharge = qtySold * getPrice();
    return totalCharge; 
}

public String toString()
{
    return ( "Title :" + title + "Author :" + author + "ISBN :" + isbn + "Publisher :" + publisher + "Price :" + price);
 }

 }

And wrote the non-fiction and fiction class as follows.

public class Fiction extends Book  
{
private String fictionCode;

public Fiction()
{
    super(); 
    setFictionCode("");
}

public Fiction(String t, String a, String i, Publisher Publisher, double m)
{ 
    super(t,a,i,Publisher,m);   
    setFictionCode(fictionCode);

 }

 public void setFictionCode(String fc)

 {
    fictionCode = fc;
 }

 public String getFictionCode()

 {
    return fictionCode;
 }
 public String toString()

 {
    return super.toString();
 }
 }   

But I'm having issue with calling it in the booktest. Data will be in a two-dimensional data array as follows:

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

{
 String dataArray  [][]=
 {{ "Fiction", "Abraham Lincoln Vampire Hunter", "Grahame-Smith, Wiley", "NY",       "978-0446563079", "13.99", "222"},
 {"Fiction", "Frankenstein", "Shelley", "Prescott", "GA", "978-0486282114", "7.99", "321"},
 {"NonFiction", "Life of Kennedy", "Jones", "Pearson", "MT", "758-29304566", "12.90", "biography"},
 {"Fiction", "Dracula", "Stoker", "Addison", "CA", "978-0486411095","5.99", "145"},
 {"Fiction", "Curse of the Wolfman", "Hageman", "Wesley", "MA", "B00381AKHG", "10.59", "876"},
 {"NonFiction", "How to Pass Java", "Willis", "Wiley"," NY", "444-395869790", "1.99", "technology"},
 {"Fiction", "The Mummy", "Rice", "Addision", "CA", "978-0345369949", "7.99", "954"},
 {"NonFiction", "History of Texas", "Smith", "Prescott", "CA", "123-683947687", "9.75", "history"}};

 Book bookArray = new Book [8];

 for (int i=0; i<bookArray.length;i++)

 if (dataArray [i][0].equals("Fiction"))

 {
  bookArray[i]= new Fiction(dataArray[i][1],dataArray[i][2],dataArray[i][3],      new Publisher (dataArray[i][4],
(dataArray[i][5]), new Book(double.parseDouble(dataArray[i][6]),dataArray[i][7])));
 }  
 if (dataArray [i][0].equals("NonFiction"))
  {     
    bookArray[i]= new NonFiction(dataArray[i][1],dataArray[i][2],dataArray[i][3], new Publisher (dataArray[i][4],dataArray[i][5],
new Book(double.parseDouble(dataArray[i][6]),dataArray[i][7])));
 }

 for (book b:bookArray)
 { 
    system.out.println(b.toString());
}
}
 }




Passing different parameters to an overloaded operator function

I currently have a class called Complex:

class Complex{
public:
    Complex();
    Complex(double, double);
    double r, i;
    void read(istream &in);
    void display(ostream &out) const;
    double real, imaginary;

That I am using to overload the addition operator. Currently I have three separate function declarations to handle 3 different cases: 2 complex numbers, 1 complex number and 1 int on the right, and 1 int and 1 complex number on the right.

Complex operator+ (const Complex& num1, const Complex& num2);
Complex operator+ (const int num1, const Complex& num2);
Complex operator+ (const Complex& num1,const int num2);

The function declarations all just add up the "real" and "imaginary" parts of complex numbers and add the integers to the real parts of the complex numbers.

Complex operator+ (const Complex& num1,const Complex& num2) {
    Complex result;
    result.real += num1.real + num2.real;
    result.imaginary += num1.imaginary +num2.imaginary;
    return result;
}
Complex operator+ (const int num1, const Complex& num2){
    Complex result;
    result.real += num1;
    result.imaginary += num2.imaginary;
    return result;
}
Complex operator+ (const Complex& num1, const int num2){
    Complex result;
    result.real += num2;
    result.imaginary += num1.imaginary;
    return result;
}

There has to be a better way to do this right? Or do all three cases have to be explicitly declared?




Why am I getting a Syntax error when using "class" in Javascript

I am making a game in javascript, and I'm using making a class to hold all the sprites. However when I try to run it, safari gives me "SyntaxError: Unexpected use of reserved word 'class'". I can't find a reason it should be doing this. Below is my code:

var spritesContext;

//Sprite class
class sprite{
    constructor(imageName, imageX, imageY, imageHeight, imageWidth, context, canvas){
        this.imageName = imageName;
        this.imageX = imageX;
        this.imageY = imageY;
        this.imageHeight = imageHeight;
        this.imageWidth = imageWidth;
        this.canvas = canvas;
        this.context = context;
        spritesContext = context;
        console.log("Sprite constructed");
    }

    draw(){
        var character = new Image();
        character.src = "../Images/" + this.imageName + ".png";
        character.onload = function(){
            spritesContext.drawImage(character, this.imageX, this.imageY, this.imageWidth, this.imageHeight);
            console.log("Inner Draw is working.");
        }
        console.log("Draw is working.");
    }

    function getHeight(){
        return this.imageHeight;
    }

    function getWidth(){
         return this.imageWidth;
    }

    function getX(){
        return this.imageX;
    }

    function getY(){
       return this.imageY;
    }

    function moveUpX(e){
        this.imageX = (this.imageX + e);
    }

    function moveUpY(e){
        this.imageY = (this.imageY + e);
    }

    function moveBackX(e){
        this.imageX = (this.imageX - e);
    }

    function moveBackY(e){
       this.imageY = (this.imageY - e);
    }

    function changeImage(e){
        this.imageName = e;
    }

    function getImage(){
       return this.imageName;
    }

    function changeX(e){
         this.imageX = e;
    }

    function changeY(e){
        this.imageY = e;
    }

}




How to call overloaded method

I have the following structure:

# file1.py
class BaseExporter:

    def do_something(self):
        self._inner_call()

    def _inner_call(self):
        print 'do not execute this!'

if __name__ == '__main__':
    x = MyExporter()
    x.do_something()

# file2.py
class MyExporter(BaseExporter):

    def _inner_call(self):
        print 'execute this!!!'

How do I get the _do_something() to call the _inner_call in my MyExporter class?




Removing a class from a list

I am trying to remove classes from a list based on their hp. I am making a large scale battle simulator for a D&D campaign. Its a simple program that makes two lists of classes and pits them against each other.

I am running into a problem when it comes to removing dead fighters. It works fine if one fighter dies in a round, but when multiple die, it goes wonky.

def check_human_deaths():
    for i in range(len(goodguys)):
        if goodguys[i].hp <= 0:
            print('{} has died...'.format(goodguys[i].name))
            goodguys.remove(goodguys[i])

Removing the dead fighter changes the length of the list, throwing an index error:

IndexError: list index out of range

I am not to sure how to proceed with removing the dead from the battlefield. Any tips are appreciated. Let me know if I am going about this in a fundamentally wrong way.




R packages to run python scripts (classes and methods) in R

I want to run python scripts (classes and methods) in "R", someone please suggest

R packages (other then rPython) with full documentation to perform this task,

smoothly and reliably. Thanks




Passing attributes from one class to another + instaiation in java

I am tying to wrap my head around using a method of an object in one class (in this case the Category class) and having it pass attributes/fields into an object of another class (in this case subCategory class). You can see in my main method below the actual results I am getting from the compiler versus the results I am trying to obtain.

I think the biggest challenge for me is trying the following:

  1. Passing a class as an argument in a method(I could not find online references that talk about it.)
  2. Instantiating an object of an external class inside a method of a local class.

Thanks for the help.

Category class

public class Category {

private String name;
private SubCategory subCategory = new SubCategory();

public String getName() {
    return name;
}

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

public void createSubcategory(SubCategory subCategory, String name){
    SubCategory m = new SubCategory();
    m.setParent(Category.this);
    m.setName(name);

}

SubCategory class

public class SubCategory {


private String name;
private Category parent;

public String getName() {
    return name;
}

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

public Category getParent() {
    return parent;
}

public void setParent(Category parent) {
    this.parent = parent;
}    }

Main (method)

public static void main(String[] args) {


        Category mainCat = new Category();
        SubCategory m = new SubCategory(); // I want to instantiate this inside the method of class Category called createSubCategory()

        mainCat.setName("TITLE");
        System.out.println(mainCat.getName()); // Returns --> "TITLE" THIS IS OK!


        mainCat.createSubcategory(m, "SUBTITLE1");
        System.out.println(m.getName()); // Returns "null", I'm trying to make it return --> "SUBTITLE1"
        System.out.println(m.getParent());// Returns "null", I'm trying to make it return --> "mainCat (object)"

    }




Error: Could not find or load main class

Firstly thank you for your helps. I viewed and tried all of titles like mine but none of them help me to solve my problem. I tried this command in order to compile in current folder that includes ExampleProgram.java:

java -Xms16m -Xmx64m -cp ".:boilerpipe-1.2.0.jar:lib/nekohtml-1.9.13.jar:lib/xerces-2.9.1.jar:lib/langdetect.jar:lib/jsonic-1.2.8.jar" ExampleProgram.java

Then it gives this error:

Error: Could not find or load main class ExampleProgram.java

This is ExampleProgram.java:

import java.io.InputStream;
import java.io.FileReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.IOException;

import org.xml.sax.InputSource;

import de.l3s.boilerpipe.document.TextDocument;
import de.l3s.boilerpipe.extractors.ArticleExtractor;
import de.l3s.boilerpipe.sax.BoilerpipeSAXInput;


// Language detect librarys
import com.cybozu.labs.langdetect.*;

import net.arnx.jsonic.JSON;
import net.arnx.jsonic.JSONException;


import java.io.*;
import java.net.*;


import java.util.concurrent.Executors;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

class ExampleProgram {

  public static void main(String[] args) throws Exception {

EveryDetector evr = new EveryDetector();
InetSocketAddress addr = new InetSocketAddress("127.0.0.1",8080);
HttpServer server = HttpServer.create(addr, 0);

MyHandler hndl = new MyHandler();
hndl.setDetector(evr);

MyHandlerExtractContent hnd2 = new MyHandlerExtractContent();
hnd2.setDetector(evr);

MyHandlerDetectLanguage hnd3 = new MyHandlerDetectLanguage();
hnd3.setDetector(evr);

server.createContext("/",hndl);
server.createContext("/extractcontent",hnd2);
server.createContext("/detectlanguage",hnd3);
server.setExecutor(Executors.newCachedThreadPool());
server.start();
System.out.println("Server is listening on port 8080" );


 }
}

Source: http://ift.tt/1QGSGQL

How can I solve my problem?




Android/Java creating a helper class to create graphs

Goal:

To create a helper class for graph generation

Background:

I have 3 fragments that each collect some sensor data (accelerometer, gyroscope, rotation) and plots a graph using GraphView. Here is what the code looks like for one of those fragments (this code currently works correctly):

public class GyroscopeFragment extends Fragment implements SensorEventListener {

    private final short TYPE_GYROSCOPE = Sensor.TYPE_GYROSCOPE;
    private final short POLL_FREQUENCY = 100; //in milliseconds
    private final short MAX_POINTS_DISPLAYED = 50;
    private SensorManager sensorManager;
    private Sensor sensor;
    private Sensor gyroscope;
    private long lastUpdate = -1;

    float curGyroX;
    float curGyroY;
    float curGyroZ;

    private LineGraphSeries<DataPoint> gyroXSeries;
    private LineGraphSeries<DataPoint> gyroYSeries;
    private LineGraphSeries<DataPoint> gyroZSeries;
    private double graphXTime = 1d;

    public GyroscopeFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_gyroscope, container, false);

        //Set the nav drawer item highlight
        MainActivity mainActivity = (MainActivity) getActivity();
        mainActivity.navigationView.setCheckedItem(R.id.nav_gyroscope);

        //Set actionbar title
        mainActivity.setTitle("Gyroscope");

        //Sensor manager
        sensorManager = (SensorManager) getContext().getSystemService(Context.SENSOR_SERVICE);
        gyroscope = (Sensor) sensorManager.getDefaultSensor(TYPE_GYROSCOPE);

        return view;
    }


    @Override
    public void onResume() {
        super.onResume();
        sensorManager.registerListener(this, gyroscope, SensorManager.SENSOR_DELAY_FASTEST);

        //Create graph
        GraphView gyroGraph = (GraphView) getView().findViewById(R.id.gyroGraph);

        gyroGraph.getLegendRenderer().setVisible(true);
        gyroGraph.getLegendRenderer().setFixedPosition(0,0);

        gyroGraph.getGridLabelRenderer().setHighlightZeroLines(false);

        gyroXSeries = new LineGraphSeries<DataPoint>();
        gyroYSeries = new LineGraphSeries<DataPoint>();
        gyroZSeries = new LineGraphSeries<DataPoint>();

        gyroXSeries.setTitle("X");
        gyroYSeries.setTitle("Y");
        gyroZSeries.setTitle("Z");

        gyroXSeries.setColor(Color.RED);
        gyroYSeries.setColor(Color.GREEN);
        gyroZSeries.setColor(Color.BLUE);

        gyroGraph.addSeries(gyroXSeries);
        gyroGraph.addSeries(gyroYSeries);
        gyroGraph.addSeries(gyroZSeries);

        gyroGraph.getViewport().setYAxisBoundsManual(true);
        gyroGraph.getViewport().setMinY(-10);
        gyroGraph.getViewport().setMaxY(10);

        gyroGraph.getViewport().setXAxisBoundsManual(true);
        gyroGraph.getViewport().setMinX(0);
        gyroGraph.getViewport().setMaxX(MAX_POINTS_DISPLAYED);
    }

    @Override
    public void onPause() {
        super.onPause();
        sensorManager.unregisterListener(this);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        sensorManager.unregisterListener(this);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        sensorManager.unregisterListener(this);
    }

    @Override
    public void onSensorChanged(SensorEvent event) {
        sensor = event.sensor;

        curGyroX = event.values[0];
        curGyroY = event.values[1];
        curGyroZ = event.values[2];

        long curTime = System.currentTimeMillis();
        long diffTime = (curTime - lastUpdate);

        // only allow one update every POLL_FREQUENCY.
        if (diffTime > POLL_FREQUENCY) {
            lastUpdate = curTime;

            graphXTime += 1d;
            gyroXSeries.appendData(new DataPoint(graphXTime, curGyroX), true, MAX_POINTS_DISPLAYED);
            gyroYSeries.appendData(new DataPoint(graphXTime, curGyroY), true, MAX_POINTS_DISPLAYED);
            gyroZSeries.appendData(new DataPoint(graphXTime, curGyroZ), true, MAX_POINTS_DISPLAYED);
        }
    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {
        //Safe not to implement
    }
}

I find that across the 3 fragments I am repeating a lot of the graph generation code in onResume so I wanted to create a GraphHelper class that I can instantiate to do the graph creation, with the benefit of only having to change code in one place if I wanted to alter the look of a graph. However, I am new to Java so having trouble wrapping my head around creating this new class.

Attempted solution:

I have managed to come up with the following class in an attempt to solve the problem:

public class GraphHelper {

    private final GraphView graph;
    private final LineGraphSeries<DataPoint> xSeries;
    private final LineGraphSeries<DataPoint> ySeries;
    private final LineGraphSeries<DataPoint> zSeries;

    public GraphHelper(GraphView graph, LineGraphSeries<DataPoint> xSeries,
                            LineGraphSeries<DataPoint> ySeries, LineGraphSeries<DataPoint> zSeries, short maxDisplayed){
        this.graph = graph;
        this.xSeries = xSeries;
        this.ySeries = ySeries;
        this.zSeries = zSeries;

        graph.getLegendRenderer().setVisible(true);
        graph.getLegendRenderer().setFixedPosition(0, 0);

        graph.getGridLabelRenderer().setHighlightZeroLines(false);

        xSeries = new LineGraphSeries<DataPoint>();
        ySeries = new LineGraphSeries<DataPoint>();
        zSeries = new LineGraphSeries<DataPoint>();

        xSeries.setTitle("X");
        ySeries.setTitle("Y");
        zSeries.setTitle("Z");

        xSeries.setColor(Color.RED);
        ySeries.setColor(Color.GREEN);
        zSeries.setColor(Color.BLUE);

        graph.addSeries(xSeries);
        graph.addSeries(ySeries);
        graph.addSeries(zSeries);

        graph.getViewport().setYAxisBoundsManual(true);
        graph.getViewport().setMinY(-10);
        graph.getViewport().setMaxY(10);

        graph.getViewport().setXAxisBoundsManual(true);
        graph.getViewport().setMinX(0);
        graph.getViewport().setMaxX(maxDisplayed);
    }
}

And have changed my fragment onResume to look like this (everything else is the same):

@Override
public void onResume() {
    super.onResume();
    sensorManager.registerListener(this, gyroscope, SensorManager.SENSOR_DELAY_FASTEST);

    //Create graph
    GraphView gyroGraph = (GraphView) getView().findViewById(R.id.gyroGraph);

    new GraphHelper(gyroGraph, gyroXSeries, gyroYSeries, gyroZSeries, MAX_POINTS_DISPLAYED);
}

Problem #1:

I am getting the following error whenever I try to view the graph fragment:

java.lang.NullPointerException: Attempt to invoke virtual method 'void com.jjoe64.graphview.series.LineGraphSeries.appendData(com.jjoe64.graphview.series.DataPointInterface, boolean, int)' on a null object reference

This is referring to the onSensorChanged method where I'm trying to append data to the series. It doesn't seem to know what gyroXSeries is because I'm adding it to the graph within the helper.

Problem #2:

Currently I'm declaring gyroXSeries in the main fragment class, as well as the top of the helper class, and also creating a new LineGraphSeries object in the helpers constructor. Is there a way to reduce the repetition of this code?




Parent Class : Inheritance

 Public class PO
 {
      public string pono { get; set; };
      public string status { get; set; };
 }

 Public class PORegion : PO
 {
      public string region;
      public string location;

      public PORegion(PO po)
      {
           this.pono = po.pono;
           this.status = po.status;
      }
 }

Now when i send PORegion to my WEBAPI i got an error of

" Object reference not set to an instance of an object"

Thanks in advance again!




Java: How do i determine whether a local class defined in an initializer block requires an enclosing instance for instantiation?

Right now I'm implementing a method that has one parameter of the type Class and this method returns a boolean if the given class object requires an instance of it's enclosing class for it to be instantiated.

This method currently works as follows:

    if (clazz.getEnclosingClass() == null) {
        return false;
    }
    if (clazz.isAnonymousClass() || clazz.isMemberClass()) {
        return !Modifier.isStatic(clazz.getModifiers());
    }
    if (clazz.getEnclosingConstructor() != null) {
        return true;
    }
    final Method enclosingMethod = clazz.getEnclosingMethod();
    if (enclosingMethod != null) {
        return !Modifier.isStatic(enclosingMethod.getModifiers());
    }

To explain why it is designed as such:

  1. It first checks if it's a top-level class, if so, the algorithm can safely return false
  2. If the class is anonymous or a member class, it requires a closing instance if it's not static (an anynmous class is automatically static if it's declared in a static constructor/method/initializer-block)
  3. The class can now be assumed to be a local class (disregarding arrays and primitives), so it's defined in either a constructor, method or initializer. However, unlike an anonymous class, a local class is never considered static, but still requires an enclosing instance if the local class is defined in a non-static block.
  4. A constructor is never static, so in that case return true
  5. If it's defined in a method, return true if the method isn't static

I need step 6 to determine whether the local class resides in either a Static Initializer Block or an Instance Initializer Block, so I'm done with the implementation for this function.

So here's where the reflection API falls a bit short. There's no method Class.getEnclosingInitializer() or such, nor is there a class that represents an initializer in the reflection package.

Isn't an initializer block a member of a class? In the java 1.8 spec the Member interface only has the implementation classes Field, Executable (with subclasses Constructor and Method), and then there's MemberName that's out of the scope for most users of reflection.

I'm not really sure if the people behind the spec forgot about this situation and local classes actually should be static if declared in a static method/initializer (like anonymous classes). But it seems to me that it's lacking this last bit of consistency from this point of view.

So does anybody have an idea on how to ascertain in which type of initializer block the local class is declared?

I'm not really keen on digging through fields for a synthetic one of a type that equals it's enclosing class, or looping through it's constructors for something akin to that (sidenote: Parameter objects from Constructor.getParameters() always return false on isImplicit() and isSynthetic() no matter what i try... that just seems wrong). So if I can avoid such solutions that would be great.




How do I print a list of all variable created for a class in order in Python?

I have the following class:

class Countries(object):
    def __init__(self, country_capital, country_population):
        self.capital = country_capital
        self.population = country_population

And a list of variables connected to the class:

france = Countries("Paris", "66")
england = Countries("London", "53")
usa = Countries("Washington, DC", "318")
germany = Countries("Berlin", "80")

How do I go about the Countries() Capitals in order of population? e.g. ["London", "Paris", "Berlin", "Washington, DC"]




Private function error with PHPUnit testing

I am getting the following error in my PHPunit test

Warning: Invalid callback Vc_Manager::__sleep, cannot access private method Vc_Manager::__sleep()

This is caused because the function __sleep() is private and the __contruct() function for the class is also private.

How can I using this function in my phpunit testing without turning the function public?

Full code:

require_once('../splitTestNew.php');



class SplitTestTest extends PHPUnit_Framework_TestCase
{


    public function setUp(){

    }
    public function tearDown(){ }
    /**
     * @runInSeparateProcess
     */
    public function testDefaultParameterValues()
    {

        $obj = new BSSplitTest();
        $this->assertTrue($obj->params['A'] == 50);
        $this->assertTrue($obj->params['B'] == 50);
        $this->assertTrue($obj->params['SplitCookieA'] == 'ACounter');
        $this->assertTrue($obj->params['SplitCookieB'] == 'BCounter');
        $this->assertTrue($obj->params['TableA'] == 'counter_a');
        $this->assertTrue($obj->params['TableB'] == 'counter_b');

    }




When creating a reference type, what are we exactly doing?

Noob here, with some questions about fundamental things in java.

When we have a class (or super-class, I'll get back to that) Person with a constructor (also Person) we can create a reference type like this:

Person johnny = new Person();

We have just created in a new class People (e.g.) an object, johnny. It holds an "address" to where the object and its values are kept, unlike objects of primitives types do (e.g. int x = 5; has the value 5, johnny is a "link" to the value - if I've understood things correctly.)

1st word: 'Person' is a class type, but:

  • What does a class type do? What does it entail?

  • Perhaps: what does a type do, if it is not a 'primitive type'?

2nd word: 'johnny' is a reference variable, of type Person. - If I am missing something, please enlighten me :)

3rd word: 'new' this just states that we are creating the new object.

4th word: second 'Person:

  • This is the object we are creating?
  • Is this the constructor or the class we are referring to?

ALSO:

  • The value (address) that the variable is referring to is everything after the equal sign? The address is 'new Person'?

LASTLY: Polymorphism. So if we have a sub-classes 'Adult', which extends the super-class 'Person', then we can do this:

Person amanda = new Adult();

  • What are we doing now?
  • Is 'amanda' of class type Person and an object in the class 'Adult'?

Thanks for your help :)




difference between 'global varName' and 'self.varName' in python [duplicate]

what is the use of writing 'global varName' in the body of constructor ? I mean we can achive the same goal by writting 'self.varName' ? For Example

class Mine_Global:
    def __init__(self):
        global varName
        varName = 3
        self.newInsVar = 7

if __name__ == "__main__":
    global varName
    obj1 = Mine_Global()
    print varName, obj1.newInsVar;
    varName = varName + 2
    print varName, obj1.newInsVar;

    obj2 = Mine_Global()
    print varName, obj2.newInsVar




How to use more than one method?

So, I've got to write an invoice for a video store that has a Customer class which takes six attributes, the customer name (string), the street address (string), the city(String), the state(string), the zip code(string), and the telephone number. I had to use a parameterized constructor that receives the attributes as parameters as well as provide getters and setters. I believe I did this correctly.

Next I had to make a Video class that had four attributes, the video name (string), the year the video was released(integer), the video copy number(integer), and the daily rental rate(double). I had to do a parameterized constructor and getters and setters for this as well.

The problems start on my Invoice class which is to represent the rental of a video to a given customer, it is not finished, but is supposed to have four attributes, the customer renting the video, the video being rented, the date it was rented(as a inputted string), and the daily rental rate(double). It was also supposed to have three methods, the subtotal, the tax and the total. My problem is I've got the preset methods for the customers and the videos setup, I just have no clue how to effectively use them in an if statement. I don't know what I would put in my fourth test class to allow this to work. I am all but lost at this point, any push in the right direction would be greatly appreciated. here are my classes.

Customer:

public class Customer {
private String customerName;
private String streetAddress;
private String custCity;
private String custState;
private String custZip;
private String custPhone;
public Customer(String customerName, String streetAddress, String custCity, String custState, String custZip,
        String custPhone) {
    super();
    this.customerName = customerName;
    this.streetAddress = streetAddress;
    this.custCity = custCity;
    this.custState = custState;
    this.custZip = custZip;
    this.custPhone = custPhone;
}
public String getCustomerName() {
    return customerName;
}
public void setCustomerName(String customerName) {
    this.customerName = customerName;
}
public String getStreetAddress() {
    return streetAddress;
}
public void setStreetAddress(String streetAddress) {
    this.streetAddress = streetAddress;
}
public String getCustCity() {
    return custCity;
}
public void setCustCity(String custCity) {
    this.custCity = custCity;
}
public String getCustState() {
    return custState;
}
public void setCustState(String custState) {
    this.custState = custState;
}
public String getCustZip() {
    return custZip;
}
public void setCustZip(String custZip) {
    this.custZip = custZip;
}
public String getCustPhone() {
    return custPhone;
}
public void setCustPhone(String custPhone) {
    this.custPhone = custPhone;
}



}

Video:

public class Video {
private String videoName;
private int videoYear;
private int copyNum;
private double rentalRate;
public Video(String videoName, int videoYear, int copyNum, double rentalRate) {
    super();
    this.videoName = videoName;
    this.videoYear = videoYear;
    this.copyNum = copyNum;
    this.rentalRate = rentalRate;
}
public String getVideoName() {
    return videoName;
}
public void setVideoName(String videoName) {
    this.videoName = videoName;
}
public int getVideoYear() {
    return videoYear;
}
public void setVideoYear(int videoYear) {
    this.videoYear = videoYear;
}
public int getCopyNum() {
    return copyNum;
}
public void setCopyNum(int copyNum) {
    this.copyNum = copyNum;
}
public double getRentalRate() {
    return rentalRate;
}
public void setRentalRate(double rentalRate) {
    this.rentalRate = rentalRate;
}

Invoice (incomplete) :

    import java.util.Scanner;

public class Invoice {
     public static void main(String[] args){
    Scanner in = new Scanner(System.in);
    Customer Brandon = new Customer("Brandon James" , "112 Oak Street" 
        , "CityVille" , "Alabama" , "18229",
        "912-2248");

Customer Judy = new Customer("Judy Vermooth" , "8008 Ribbit Ln.",
        "Metropolis" , "Pennsylvania" , "24057", "241-8009");

Video Easter = new Video("Easter 2", 2002, 4, 2.49);

Video DareDevil3 = new Video ("Dare Devil 3", 2012, 2, 3.62);




if( Prog4.newRental = "Brandon"){
    Customer Brandon = newCust

}
}
}

Prog4(incomplete):

import java.util.*;

public class Prog4 {
private String newRental;
private String vidName;
private String rentalDate;
private String daysRented;

public static void main(String[] args){
Scanner in = new Scanner(System.in);


System.out.println("Enter Customer Name: ");
 String newRental = in.nextLine();

System.out.println("Enter Video Name: ");
String vidName = in.nextLine();

System.out.println("Enter Rental date in mm/dd/yyyy format: ");
String rentalDate = in.nextLine();

System.out.println("Enter Number of Days Rented");
int daysRented = in.nextInt();
}

public String getNewRental() {
    return newRental;
}

public void setNewRental(String newRental) {
    this.newRental = newRental;
}

public String getVidName() {
    return vidName;
}

public void setVidName(String vidName) {
    this.vidName = vidName;
}

public String getRentalDate() {
    return rentalDate;
}

public void setRentalDate(String rentalDate) {
    this.rentalDate = rentalDate;
}

public String getDaysRented() {
    return daysRented;
}

public void setDaysRented(String daysRented) {
    this.daysRented = daysRented;
}

}




dimanche 28 février 2016

What is the benefit of using Class?> instead of Class as a method parameter type?

I've written a utility method that accepts a parameter 'cl' of type Class and performs logic by using cl.isInstance(objectInstance) method.

However I've seen example code that declares parameters using the generic wildcard Class<?>.

Why not just use Class without the generic wildcard? Can't Class represent all possible class types including generics? What is the benefit, if any of using Class<?> in my situation?

The accepted answer in an existing related question (see below) does not actually provide a useful answer.

What does Class<?> mean in Java?




I can't use methods from another class from imported libraries in Android Studio

I used

dependencies { compile 'com.macroyau:thingspeakandroid:0.2.0' }

to download the external libraries I need. I created an instance of one of the classes of the lib and upon calling the methods, it seems I can only call the interfaces instead of the actual methods as you can see here!

enter image description here

It's the first time I am using Android Studio, is it the right way to import external libraries?




How do I access an instance of a class in Swift

I have a user class defined in UserClass.swift like this:

class User {
    var id:Int
    var name:String
    var phone:String
    var email:String

    init(id:Int, name:String, phone:String, email:String){
        self.id = id
        self.name = name
        self.phone = phone
        self.email = email
    }
}

In my ProfileViewController I call a method on viewDidLoad called getUserData.

class ProfileViewController: UIViewController {

    @IBOutlet weak var userNameLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        getUserData { myUser in
            self.userNameLabel.text = myUser.name
        }
}

getUserData pings my API and then instantiates and instance of the User class.

func getUserData(completionHandler:(User)->()) {

    Alamofire.request(.GET, "apiEndPoint")
        .responseJSON { response in

        if let value: AnyObject = response.result.value {

            let userData = JSON(value)
            let userName = userData["name"].string!
            let userId = userData["id"].int!
            let userPhone = userData["phone"].string!
            let userEmail = userData["email"].string!

            let myUser = User(id:userId, name:userName, phone:userPhone, email:userEmail)

            print("user: \(myUser.name)")

            completionHandler(myUser)

        }
    }
}

I then pass that instance with a callback to the ProfileViewController so that I can update a label. This works great.

The problem is that now I want to look at a different property of the User instance myUser in a different place, outside of the callback. Eventually I want to get the user's id, but for now I'm just trying to access the instance at all, so I'm looking again at updating a label with the user's name:

class MyActivitiesViewController: UIViewController {

    @IBOutlet weak var myActTempLabel: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
            self.myActTempLabel.text = myUser.name
    }
}

This is giving me an error of Use of unresolved identifier 'myUser'. How do I access the instance of User that I already created?




User controlled sprite stuck in box. Python 2.7.9 w/Pygame

Thanks for looking at my question and helping me out. I have a user controlled sprite that should cause the screen to shift around the sprite's position, kinda like an old Gameboy Pokemon game, yet that does not happen. Instead my sprite is stuck inside a box of coordinates that I used to help define parameters for background shift. This is the code I believe is causing this:

    # Shift world left (-x)
    if player.rect.right >= 510:
        diff = player.rect.right - 510
        player.rect.right = 510
        current_level.shift_world_x(-diff)

    # Shift world right (+x)
    if player.rect.left <= 130:
        diff = 130 - player.rect.left
        player.rect.left = 130
        current_level.shift_world_x(diff)

    # Shift world up (-y)
    if player.rect.top <= 100:
        diff = 100 - player.rect.top
        player.rect.top = 100
        current_level.shift_world_y(diff)

    # Shift world down (y)
    if player.rect.bottom >= 380:
        diff = player.rect.bottom - 380
        player.rect.bottom = 380
        current_level.shift_world_y(-diff)

If I put a # next to player.rect.right = 510, or any of the other three varients, my sprite can move freely, yet the screen will not shift.

Zip file with all assets is here: http://ift.tt/1Qf0xI4

The entirety of my code is as follows:

import pygame

"""---Global Constants---""" 

# Colors
BLACK = (0, 0, 0)

# Screen Variables
screen_x = 720
screen_y = 480

# Background variables
back_x = 0
back_y = -243
back_x_change = 0
back_y_change = 0

class Player(pygame.sprite.Sprite):
    """---User Controled Character---"""

    # Methods
    def __init__(self):
        """---Contructor Function---"""

        # Call parent's constructor
        pygame.sprite.Sprite.__init__(self)

        # Load player image
        self.image = pygame.image.load("player.png").convert()

        # Set referance to image "hit box"
        self.rect = self.image.get_rect()

        # Set speed of player
        self.change_x = 0
        self.change_y = 0


    def update(self):
        """---Move the Player---"""

        # Move left/right
        self.rect.x += self.change_x

        # Move up/down
        self.rect.y += self.change_y

    # User controlled movements
    def go_left(self):
        self.change_x = -3
    def go_right(self):
        self.change_x = 3
    def go_up(self):
        self.change_y = -3
    def go_down(self):
        self.change_y = 3
    def stop_x(self):
        self.change_x = 0
    def stop_y(self):
        self.change_y = 0

class Barrier(pygame.sprite.Sprite):
    """---Barriers that prevent player from passing---"""

    def __init__(self,width,height):
        """ Barrier constructor """
        pygame.sprite.Sprite.__init__(self)

        self.image = pygame.Surface([width,height])
        self.image.fill(BLACK)

        self.rect = self.image.get_rect()

class Level():
    """---All levels will spawn from this generic class---"""

    def __init__(self,player):
        """ Needed for when sprites collide with player """
        self.barrier_list = pygame.sprite.Group() 
        self.enemy_list = pygame.sprite.Group()
        self.player = player

        # Distance world has been shifted left/right
        self.world_shift_x = 0

        # Background image
        background_base = None
        background_layera = None

        # Distance world has been shifted up/down
        self.world_shift_y = 0


    def update(self):
        """ Update everything on level """
        self.barrier_list.update()
        self.enemy_list.update()

    def draw(self,screen):
        """ Draw everything on level """

        # Draw barriers
        self.barrier_list.draw(screen)

        # Draw the base layer
        screen.blit(self.background_base,(back_x,back_y))

        # Draw all sprites
        self.enemy_list.draw(screen)

        # Draw Layer A
        screen.blit(self.background_layera,(back_x,back_y))

    def shift_world_x(self,shift_x):
        """ When character moves left/right, everything must follow """

        # Track shift amount
        self.world_shift_x += shift_x

        # Go through all list and shift
        for barrier in self.barrier_list:
            barrier.rect.x += shift_x

        for enemy in self.enemy_list:
            enemy.rect.x += shift_x

    def shift_world_y(self,shift_y):
        """ When character moves up/down, everything must follow """

        # Track shift amount
        self.world_shift_y += shift_y

        # Go through all list and shift
        for barrier in self.barrier_list:
            barrier.rect.y += shift_y

        for enemy in self.enemy_list:
            enemy.rect.y += shift_y

class Level_1(Level):
    """---Forest 1---"""

    def __init__(self,player):
        """ Create the level """

        # Call parent constructor
        Level.__init__(self,player)

        self.level_limit_x = -1912
        self.level_limit_y = 1080

        # Make background
        self.background_base = pygame.image.load("base1.png").convert()
        self.background_layera = pygame.image.load("layera1.png").convert()
        self.background_layera.set_colorkey(BLACK)


        # List with w, h, x = 32, y = 32 of barriers
        # Remove comment to activate-> level = []

        # Go through the list above and add barriers
        # Remove comment to activate-> for barriers in level:


def main():
    """---Main Program---"""
    pygame.init()

    # Set screen size and caption
    size = (screen_x,screen_y)
    screen = pygame.display.set_mode(size)
    pygame.display.set_caption("DoneGeon")

    # Create Player
    player = Player()

    # Create all levels
    level_list= []
    level_list.append(Level_1(player))

    # Set current level
    current_level_no = 0
    current_level = level_list[current_level_no]

    # Add all sprites
    active_sprite_list = pygame.sprite.Group()

    # Add player
    player.level = current_level
    player.rect.x = 360
    player.rect.y = 240
    active_sprite_list.add(player)

    # Loop until closed
    done = False

    # Screen update rate
    clock = pygame.time.Clock()

    # -------- Main Program Loop -----------
    while not done:

        """---Main event loop---"""

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                done = True

            """---User Controls---"""

            # Key Pressed
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    player.go_left()
                if event.key == pygame.K_RIGHT:
                    player.go_right()
                if event.key == pygame.K_UP:
                    player.go_up()
                if event.key == pygame.K_DOWN:
                    player.go_down()

            # Key Released
            if event.type == pygame.KEYUP:
                if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
                    player.stop_x()
                if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
                    player.stop_y()

        """---Game Logic---"""

        # Update Player
        active_sprite_list.update()

        # Update items in level
        current_level.update()

        # Shift world left (-x)
        if player.rect.right >= 510:
            diff = player.rect.right - 510
            player.rect.right = 510
            current_level.shift_world_x(-diff)

        # Shift world right (+x)
        if player.rect.left <= 130:
            diff = 130 - player.rect.left
            player.rect.left = 130
            current_level.shift_world_x(diff)

        # Shift world up (-y)
        if player.rect.top <= 100:
            diff = 100 - player.rect.top
            player.rect.top = 100
            current_level.shift_world_y(diff)

        # Shift world down (y)
        if player.rect.bottom >= 380:
            diff = player.rect.bottom - 380
            player.rect.bottom = 380
            current_level.shift_world_y(-diff)


        """---Draw below here---"""
        current_level.draw(screen)
        active_sprite_list.draw(screen)

        pygame.display.flip()
        clock.tick(60)


    pygame.quit()

if __name__ == "__main__":
    main()

Thank you for any advice!




CSS Selectors - change width if last image id is X

i try now several hours to figure out how i could change the width of a class if there is a image id before the element.

Currently my code looks like that

<blockquote>
<img id="bp_avatar" src="...">
<p>Text</p>
</blockquote 

The problem is now that the image and image id are dynamicly, in some cases it will be there in some other it wont. I tried now to wrap the image inside the text, but to fit into it the blockquote p needs a width of 90%.

So here is the issue, it should be 90% if it's there and 100% if its not there. I would like to use css instead of jquery, i found on w3 some documents about Level 4 Selectors and tried to use them, the goal was to apply the style if #bp_avatar is there.

So i tried ways like

#bp_avatar ~ #bluepostq blockquote p  {
width: 90%!important;
}


#bluepostq blockquote p! > #bp_avatar{
width: 90%!important;
        }

None of them worked yust nothing happens, i think i missunderstood something and hope someone could tell me what i have done wrong.




Null Pointer Exception in array passed class

So I have a project that requires a generic class that extends Number and also finds the largest and smallest value in the array, the average of all the values, and the size of the array. This seems easy enough to implement, but I have a problem before even putting the generic part of this in place, I get a runtime error of Null Pointer Exception at x.length, regardless of which method I call, always in the same place.

 import java.util.Comparator;

public class test
{
   public int x[];

   public test(int x[])
   {

   }

   public void setx(int newx[])
   {
   x = newx;
   }

   public int[] getx()
   {
   return x;
   }



public int findSmallest()
{
  int i = 0;
  int temp = x[i];

  while (i < x.length)
  {
      i++;
      if(x[i] < temp)
      {
      temp = x[i];      
      }
      else
      {

      }

   }

   return temp;

   }



public int findLargest()
{
  int i = 0;
  int temp = x[i];


  while (i < x.length)
  {
      i++;
      if(x[i] > temp)
      {
         temp = x[i];
      }
      else
      {

      }

   }

   return temp;

   }

public double findMean()
{
  int i = 0;
  double sum = 0.0;
  double avg = 0.0;

  while (i < x.length)
  {
      sum += x[i];
      i++;
  }

  avg = sum / x.length;
  return avg;
}

public int findTotal()
{

  int i = x.length;

  return i;

}

public static void main (String args[])
{

int[] ia = {1, 2, 3, 4, 5, 6};

test intTest = new test(ia);

System.out.println(intTest.findTotal());

}


}



Any help on how to fix this would be amazing.




Command Interpreter Class help for Agents and Spaces

Below is my code. My problem is that for the CommandInterpreter Class, I am getting the wrong output. For example when I input "where" I get "Harry Potter". I should get "classroom". When I input "look" I get "Harry Potter is in classroom" instead of "classroom: a large lecture hall with a door that goes outside to sidewalk". Go should move from one room to the next but it doesn't seem to do anything. I don't know what I'm calling wrong. I've tried changing the something to many things from Portal to student but keep getting an error. I can't change anything to static. Any help would be great. Thanks

    public class Space {
        private String _name; 
        private String _description;
        private Portal _portal;

        public String getName() {
            return _name;
        }

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

        public String getDescription() {
            return _description;
        }

        public void setDescription(String _description) {
            this._description = _description;
        }

        public Portal getPortal() {
            return _portal;
        }

        public void setPortal(Portal _portal) {
            this._portal = _portal;
        }
        public String toString() {
            return _name;
        }
        public String toStringLong() {
            if (_portal != null){
                return (_name + ": " + _description + " with a " + _portal.toStringLong());
            }
            return (_name + ": " + _description);
        } }


public class Portal {
    private String _name; 
    private String _direction;
    private Space _destination;

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

    public String getName() {
        return _name;
    }

    public void setDirection(String _direction) {
        this._direction = _direction;
    }

    public String getDirection() {
        return _direction;
    }

    public void setDestination(Space _destination) {
        this._destination = _destination;
    }

    public Space getDestination() {
        return _destination;
    }

    public  String toString() {
        return (_name + "that goes " + _direction);
    }

    public String toStringLong() {
        return (_name + " that goes " + _direction + " to " + _destination);
    }

    public void transport (Agent student) {
        student.setLocation(_destination);
    }

}


public class Agent {
    private Space _location; 
    private String _name;

    public void setLocation (Space _location) {
        this._location = _location;     
    }

    public Space getLocation() {
            return _location;
    }

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

    public String getName() {
        return _name;
    }

    public String toString() {
        return _name;
    }

    public String toStringLong() {
        return (_name + " is in " + _location);
    }

    public void usePortal () {
        if (_location.getPortal() != null) {
            _location.getPortal().transport(this);
        } else {
            //do nothing
        }
    }
} 

import java.util.Scanner;

public class CommandInterpreter {

    public static void run(Agent something) {
        Scanner input = new Scanner(System.in); 
        boolean b = true; 
        String user;

        do {
             System.out.print("==>");
             user = input.next();
             if (user.equals("quit")) {
                 b = false;
             } else if (user.equals("help")) {
                 System.out.println("Enter one of the following options: \n"
                        + "go \n"
                        + "help \n"
                        + "look \n"
                        + "where \n"
                        + "quit");
             } else if (user.equals("where")) {
                 System.out.println(something.toString());
             } else if (user.equals("look")) {
                 System.out.println(something.toStringLong());
             } else if (user.equals("go")) {
                    something.usePortal();
             } else {
                 System.out.println("Sorry I don't understand " + user + ".");
             }
        } while (b);

    }

}


public class Main {

    public static void main(String[] args) {
        Space classroom = new Space();
         classroom.setName("classroom");
         classroom.setDescription("a large lecture hall");
         Space sidewalk = new Space();
         sidewalk.setName("sidewalk");
         sidewalk.setDescription("a plain concrete sidewalk with weeds growing through the cracks");
         Portal door = new Portal();
         door.setName("door");
         door.setDirection("outside");
         door.setDestination(sidewalk);
         classroom.setPortal(door);
         Agent student = new Agent();
         student.setName("Harry Potter");
         student.setLocation(classroom);
         CommandInterpreter.run(student);
    }
}




php class set properties

I can't understand this code:

$obj = new stdClass();
$obj->s = new stdClass();
$obj->s->p = new stdClass();
$obj->s->p->v = 1;
$obj->p = $obj->s->p;

echo $obj->s->p->v; //Return 1, OK
echo $obj->p->v; //Return 1, OK

$obj->p->v = 2; //Set the new value

echo $obj->p->v; //Return 2, OK
echo $obj->s->p->v; //Return 2, why??? I didn't set it!

I tested this code without using stdClass and result is same.




Cannot create DAO instance from generic abstract singleton

I have a class which I believe si a singleton, abstract and generic:

public abstract class GenericDaoImpl<E, K extends Serializable> implements GenericDao<E, K> {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;

private final Class<? extends E> daoType = DaoTypeInit();
private static Class<?> DAO;

public static <T> T getDAO(Class<T> T) throws InstantiationException, IllegalAccessException {
    if (DAO == null) {
        Class currentClass = new Object() { }.getClass().getEnclosingClass();
        DAO = (Class<?>)currentClass.newInstance();
    }
    return (T) DAO;
}

In the subclass that extends GenericDaoImpl it cannot seem to find getDAO although it is clearly there and inherited.

    StudentDaoImpl studentDAO = StudentDaoImpl.getDAO(Student.class);

What am I doing wrong, thanks?




parsing a variable from class to class

I would like to parse a variable example number from one class to another as show in the code below:

public class Gettemp // is the "public" will affect the passing of variable operation?
{
    public void temp(string temp)
    {
        temp = "123";  // things that i wanted to pass from this class 

    }

}



     public partial class Form1 : Form
    {
     private void STARTbtn_Click(object sender, EventArgs e)
    {

        MessageBox.Show() // i wan to show the variables here

    }
    }




How do i prevent object creation in es6?

I am willing to create an object using es6 class syntax.Basicly what i want is if there are missing parameters given to the constructor while creation of the object with the new keyword i wanna throw and error.

what i have done is

class something{
    constructor(data){
      if(!data)throw new Error("Data cannot be empty");
       this.data=data;
    }
}

If i try to create the object now as new something() without passing an argument it ain't break the code and i see no exception thrown on the terminal.

How can i claim this and prevent object creation ?

---UPDATE--- im working with nodejs not browser.




How can I devide a class java into many classes?

I have a main class with over 600 lines code :/ ! my app contains a toolbar,menubar and a field to draw a network nodes how can I devide my main class and what criteria to choose fo dividing ?




Overriding a base class public method in derived class in C++

I'm trying to create a custom stack that can add additional member functions specific to an application. So I first created a base class for stack using std::vector<T>. Then I inherits this class to create a derived class that can have a member function to find the "min" value of the stack. The derived class must override the base class so instead of taking a single argument in push(T const&) it should now take two arguments push(T const&, T const&). So that way the I can pass a second argument which is a current min value of the stack. However, when I try to access an instance of the derived class and the overridden function push(T const&, T const&) it only allows me to see the base class push() function.

#include <iostream>
#include <vector>

template <class T>
class CustomStack {

protected:
    std::vector<T> elements;

public:
    virtual void push(T const&); // Push an element
    void pop(); // Pop an element
    T top() const; // return the top element
    bool isEmpty() const {    // Return true if empty
        return elements.empty();
    } 
};


template <class T>
virtual void CustomStack::push(T const& element) {
    elements.push_back(element);   
}


template <class T>
void CustomStack::pop() {
    if (elements.empty())
        throw std::out_of_range("CustomStack<>::pop : Empty Stack");

    elements.pop_back();
}

template <class T>
T CustomStack::top() const {
    if (elements.empty())
        throw std::out_of_range("CustomStack<>::pop : Empty Stack");

    return elements.back;
}

// Creating a derived class
template <class T>
class CustomStackMin : public CustomStack {

private:
    T min;

public:
    // Member function for min
    T CustomStackMin::min() const;
    void CustomStackMin::push(T const&, T const&);
};

template <class T>
T CustomStackMin::min() const {
    if (elements.empty()) {
        throw std::out_of_range("CustomStackMin<>::min : Empty Stack");
    }

    return min;
}

template <class T>
void CustomStackMin::push(T const& element, T const& minVal) {
    elements.push_back(element);
    min = minVal;
}

int main() {

    CustomStackMin<int> myStack;
    mystack.push(5, 5); // ERROR: Too many arguments for push()
}




How to define member class operator based on the class parameters

Is it possible to define different = operators for different template arguments. Let's assume that I want to use different methods for converting arguments of different types:

template <class T,class U>
class cTest
{
  private:
  public:
    T x;
    U y;

  //typical case
  cTest<T,U>& operator =(const cTest<T,U> &that)
  {
     return *this;
  }

  //operator = based on the LHS type 1
  cTest<uint16_t,U>& operator =(const cTest<int,U> &that)
  {
     cout<<"cTest<uint16_t,U>& operator =(const cTest<int,U> &that)"<<endl;
     return cTest<uint16_t,U>();
   }
  //operator = based on the LHS type 2
   cTest<uint8_t,U>& operator =(const cTest<int,U> &that)
   {
      cout<<"cTest<uint8_t,U>& operator =(const cTest<int,U> &that)"<<endl;
      return cTest<uint16_t,U>();
   }
};




How to design Java Contract class for an Employee

I am making class design for employee management system.
Class Employee has following fields:

:Employee  
id:int  
firstName:String  
lastName:String  
contract:Contract

Class Contract has following fields:

:Contract  
-contractNo:int  
-contractDate:Date  
-contractType:Type  
-rate:Double  
-function:Function  
-contractCopy:File

When employee employs to the company, he sign contract with agreed rate, function etc. Then time by time manager revises the contract and changes: rate, function.
Could somebody advise, how to design a class that stores revisions of the contract? Because it needs to be seen original information of the contract and all revisions including changes.




IntelliJ: How to access files in the bin folder?

I've got this code where I search for groovy plugins in the bin folder. In eclipse it works but in IntelliJ it doesn't, because there doesn't seem to be a bin folder.

static def provide() {
    List<Class<?>> listeners = init "./bin/plugin/"
    listeners.each { World.getPluginHandler().submit it }
}

I've tried following advice from other stackoverflow posts... and these are now my settings.

enter image description here enter image description here

However my bin folder is still empty(it did create though), which is odd. Hopefully someone here know's what's up and can help me, thanks in advance!




How to Handle Job Category Hierarchies?

I'm making a gig site that allows users to post gigs and also claim gigs through "offers" that the poster can accept or reject. But I'm having some trouble getting my head wrapped around how to handle the different gig categories. Here are my 3 major classes:

class Gig
  belongs_to :seller, class_name: "User", foreign_key: :user_id
  has_many :buyers, class_name: "User", through: :offers

class User
  # Seller Associations
  has_many :gigs_selling, class_name: "Gig"
  has_many :offers_received, class_name: "Offer", through: :gigs_selling, source: :offers

  # Buyer Associations
  has_many :offers_made, class_name: "Offer"
  has_many :gigs_buying, class_name: "Gig", through: :offers_made, source: :gig  

class Offer
  belongs_to :gig
  belongs_to :buyer, class_name: "User", foreign_key: :user_id
  has_one :seller, class_name: "User", through: :product

I have two levels of categories - for example, a "yard work" major category and a "lawn mowing" minor category. What is the best way to handle allowing each category to inherit the "gig" metaclass while still having individual addons for each minor category that determine the price (like "grass bagged", "hedges trimmed", etc)?

I thought about making a class hierarchy with Minor Category < Major Category < Gig, but I'm worried about the offer and user inter-dependencies. If I do this, I'm thinking I'll have to call out "has_many through" relationships for offers and users for each category, which doesn't seem very scale-able.

I also thought about adding a "gig category" and "gig subcategory" integer to the gig class for use as an enumerated set, where I could set "user addon" variables that depend on the category chosen.

What is the best way to handle this situation? I'm new to Rails and would REALLY appreciate any advice. Thank you!!!




Operator overload doubts

I was trying to write some operator overload functions, especially the << operator to use it with a custom class and an std::ofstream object, but I was a bit confused by the syntax used in various examples found online. For example, let's consider the operator<< overload as a non-member function for a simple custom class:

#include <fstream>

class Example{
 public:
   int first;
   int second;
};

//i found this kind of operator on internet
std::ofstream& operator<< (std::ofstream& out, Example obj){
      out << obj.first << endl << obj.second;
      return out;
}

int main(){
    Example a={1,2};
    ofstream out;
    out.open("test");
    out << a;
    out.close();   

}

I don't really get why It should return std::ofstream& to work properly. I tried using the following operator

void operator<< (std::ofstream& out, Example obj){
     out << obj.first << endl << obj.second << endl;
}

and it worked as well. I mean, can't out << obj; be interpreted as operator<< (out , obj); ? Why does it have to return something since I'm passing a reference to the std::ofstream object?

The same doubt arose when I was trying to write an operator= overload as a member function for a custom class, as the simple example that follows

class Custom{
 public:
        int up;
        int down;

        Custom& operator= (Custom a){
             up=a.up;
             down=a.down;
             return *this;
        }

};

I used the copy-swap idiom for the assignment operator, so don't mind the operator definition too much, it's just an example. Again, writing

Custom obj1, obj2;
obj1=obj2;

since i can interpret obj1=obj2; as obj1.operator=(obj2), why is the return type Custom& required instead of void?




How java treat classes with similar names? [duplicate]

This question already has an answer here:

Many classes in Java have similar names. In case , if we are going to use two classes with same name in our program, how Java identify which is the class that we meant?

For example, in the below code, how Java treat List list ?

import java.util.List;
import java.awt.List;

public class Example{

List list; 

} 




imitational registration app with c++

I am new at c++ and I could not understand the basics of object orientation at c++. I am familiar with python...

I have code a simple registration app but it is not working.

#include<iostream>
#include<string>
using namespace std;

class users{
        public:
        string username;
        string password;
        void setUser();
        bool isValid(string username, string password);
};

//creating a new username and a new password
void users::setUser(){
    string name, pw;
    cout << "Username: ";
    cin >> name;
    this->username = name;
    cout << "Password: ";
    cin >> pw; 
    this->password = pw;
}

//checking username and pw is equal to objects
bool users::isValid(string name, string pw){
    if(this->username == name && this->password == pw){
        return true;
    }
    else{
        return false;
    }
}

int main(){
    while(true){
        int ask;
        bool isOkey=false;
        cout << "Press 1 to create user; 2 to log in: ";
        users newuser;
        cin >> ask;
        if(ask==1){
            newuser.setUser();
        }
        else if(ask==2){
            string username, password;
            cout << "username: ";
            cin >> username;
            cout << "password: ";
            cin >> password;
            isOkey = newuser.isValid(username, password);
        }
        while(isOkey){
            cout << "welcome";
        }
    }
} 

This is my code and the problem is isValid function does not return true or false if I got understand right. What is the right code would be like?




Teaching OOP with PHP

I need some ideas with my new book but I am having an authors blocker I guess.

What examples could you use to teach OOP in PHP. In my philosophy, using something useless (foo, bar) is stupid. It's also not possible to give an example like user login because it's complex. And don't tell me about the To-Do example because it is useless and also boring. There should be some funnier and useful examples.

What do you think? What would be a clear approach to teach PHP to beginners?




Java: Using method in another class

I am trying to use the String returned by this method in another class. This is the method:

public String toString(){ return String.format("(%f, %f, %f)",longitude, latitude, elevation);}

This is the other class method:

void addPoint(){
  coordinates.add(Point.toSting);
}

I know that I could create an object, but neither of these classes has a main method.




Is this class design wrong?

I'm starting as a java developer. I'm developing a stock app with java and mysql.

I have big question. I can not figured out where I should place method to save datas. Should I create a new class for DB operatios, or should I place them in inventory class.

Thanks!!

My classes are:

package inventory;

public class Item
{
private String bc; // ITEM BARCODE
private String description; // ITEM DESCRIPTION
private int nItm; // NUMBER OF ITEMS IN A PACK OR ITEMS

/**
 * Constructor for objects of class item
 *  - Initialise instance variables bc, description to null and nItm to 0
 */
public Item()
{
    // initialise instance variables
    bc = null;
    description = null;
    nItm = 0;
}

/**
 * Constructor for objects of class item
 *  - Initialise instance variables to a given parameters.
 *  @param bc           String item codebar.
 *  @param description  String description of the item.
 *  @param nItm         int items or number of items in a pack
 */
public Item(String bc,String description,int nItm)
{
    this.bc = bc;
    this.description = description;
    this.nItm = nItm;
}

/**
 * Gets a codebar from the item
 *
 * @return     A String with the codebar item.
 */
public String getBarcode()
{
    // put your code here
    return bc;
}

/**
 * Gets description from the item
 * 
 * @return     A String with the description item.
 */
public String getDescription()
{
    return description;
}

/**
 * Gets the number of items in stock
 * 
 * @return     Number of items in stock.
 */
public int getNumberOfItems()
{
    return nItm;
}

/**
 * Set the value for codebar
 * 
 * @param  bc  Barcode item. 
 */
public void setBarcode(String bc)
{
    this.bc = bc;
}

/**
 * Set the value for description
 * 
 * @param  description   Description item.
 */
public void setDescription(String description)
{
    this.description = description;
}

/**
 * Set the value for nItm
 * 
 * @param  nItm   Number of items or items in a pack
 */
public void setNumberOfItems(int nItm)
{
    this.nItm = nItm;
}
/**
 * Shows an item with this template "| %-16s | %-44s | %5d |" 
 */
public void showItem()
{
    System.out.print("\f");
    System.out.printf("+------------------+----------------------------------------------+-------+\n");
    System.out.printf("| BARCODE          | DESCRIPTION                                  | STOCK |\n");
    System.out.printf("+------------------+----------------------------------------------+-------+\n");
    System.out.printf("| %-16s | %-44s | %5d |",this.bc,this.description,this.nItm);
    System.out.printf("+-------------------------------------------------------------------------+\n");
}

}

package inventory;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import DataBases.*;
import java.util.Scanner;
import java.sql.*;
public class Inventory
{
// instance variables - replace the example below with your own
private Item[] inventory; // array of items
public int nreg; // NUMBER OF ITEMS STORED

/**
 * Constructor for objects of class Inventory
 */
public Inventory() throws SQLException,ClassNotFoundException,InstantiationException,IllegalAccessException
{
    // initialise instance variables

    this.inventory = new Item[100];
    loadData();
}

/**
 * An example of a method - replace this comment with your own
 * 
 * @param  y   a sample parameter for a method
 * @return     the sum of x and y 
 */
public void addItem(String bc,String description,int nItm)
{
    // put your code here
    Item item;
    item = new Item(bc,description,nItm);
    inventory[nreg] = item;
    nreg++;
}

/**
 * An example of a method - replace this comment with your own
 * 
 * @param  y   a sample parameter for a method
 * @return     the sum of x and y 
 */
public void loadData() throws SQLException,ClassNotFoundException,InstantiationException,IllegalAccessException
{
    Mysql c = new Mysql();
    ResultSet rs;

    c.On();
    rs = c.ExeGet("SELECT * FROM item");
    while(rs.next())
    {
        inventory[nreg] = new Item(rs.getString("barcode"),rs.getString("description"),rs.getInt("nItems"));
        this.nreg++;
    }
    c.Off();
}

/**
 * An example of a method - replace this comment with your own
 * 
 * @param  y   a sample parameter for a method
 * @return     the sum of x and y 
 */
public void searchItem()
{
    System.out.print("\f");
    int op;
    System.out.printf("\tSEARCH MENU\n");
    System.out.printf("\t===========\n\n");
    System.out.printf("\t1.BY BARCODE.\n");
    System.out.printf("\t2.BY ITEM.\n");
    System.out.printf("\t3.BY NUMBER OF ITEMS.\n");
    System.out.printf("\t0.EXIT.\n\n");
    System.out.printf("\tOPTION: ");

    Scanner reader = new Scanner(System.in);
    op = reader.nextInt();
    switch(op)
    {
        case 0: break;
        //case 1: searchByBarcode();break;
        //case 2: searchByItem();break;
        case 3: searchByNumberOfItems();break;
        default: break;
    }
}

/**
 * An example of a method - replace this comment with your own
 * 
 * @param  y   a sample parameter for a method
 * @return     the sum of x and y 
 */
/*
private void searchByBarcode()
{
    int op;
    int flag = 0;
    Item reg = new Item();

    do{
        System.out.print("\f");
        System.out.println("OPTION 1. OK");
        System.out.printf("BARCODE: ");
        String bc;
        Scanner reader = new Scanner(System.in);
        bc = reader.nextSt();
    //  AQUI VA UN TRY COMO UNA CASA
        for(int i=0;i<nreg;i++)
        {
            if (inventory[i].getBarcode() == bc)
            {
                reg = inventory[i];
                flag = 1;
                break;
            }
        }
        if (flag == 1)
        {
            reg.showItem();
        }
        else
        {
            System.out.printf("I CAN NOT FIND %d",bc);
        }
        System.out.println("CONTINUE SEARCHING (0/1): ");
        op = reader.nextInt();

    }while(op != 1);
}
*/

/**
 * An example of a method - replace this comment with your own
 * 
 * @param  y   a sample parameter for a method
 * @return     the sum of x and y 
 */
private void searchByNumberOfItems()
{
    System.out.print("\f");
    System.out.println("OPTION 3. OK");
}

/**
 * An example of a method - replace this comment with your own
 * 
 * @param  y   a sample parameter for a method
 * @return     the sum of x and y 
 */
public void addNewItem(String barcode,String description,int nItm) throws SQLException,ClassNotFoundException,InstantiationException,IllegalAccessException
{
    Mysql c = new Mysql();
    Item i = new Item(barcode,description,nItm);
    String q = "INSERT INTO inventory.item (barcode,description,nItems) VALUES ('" + i.getBarcode() + "','" 
                + i.getDescription() + "'," + i.getNumberOfItems() + ");";

    c.On();
    c.Exe(q);
    c.Off();
    nreg++;
}

/**
 * An example of a method - replace this comment with your own
 * 
 * @param  y   a sample parameter for a method
 * @return     the sum of x and y 
 */
public void listItems() throws SQLException,ClassNotFoundException,InstantiationException,IllegalAccessException
{
    Mysql c = new Mysql();
    ResultSet rs;

    c.On();
    rs = c.ExeGet("SELECT * FROM item");
    System.out.print("\f");
    System.out.printf("+------------------+----------------------------------------------+-------+\n");
    System.out.printf("| BARCODE          | DESCRIPTION                                  | STOCK |\n");
    System.out.printf("+------------------+----------------------------------------------+-------+\n");
    while(rs.next())
    {
        //System.out.println("" + rs.getString("barcode") + "     " + rs.getString("description") + "     " + rs.getInt("nItems"));

        System.out.printf("| %-16s | %-44s | %5d |\n",rs.getString("barcode"),rs.getString("description"),rs.getInt("nItems"));
    }
    System.out.printf("+-------------------------------------------------------------------------+\n");
    c.Off();
}

public void listArray()
{
    System.out.print("\f");
    System.out.printf("+------------------+----------------------------------------------+-------+\n");
    System.out.printf("| BARCODE          | DESCRIPTION                                  | STOCK |\n");
    System.out.printf("+------------------+----------------------------------------------+-------+\n");
    for(int i = 0;i<nreg;i++)
    {
        System.out.printf("| %-16s | %-44s | %5d |\n",inventory[i].getBarcode(),inventory[i].getDescription(),inventory[i].getNumberOfItems());
    }
    System.out.printf("+-------------------------------------------------------------------------+\n");
    System.out.printf("| NUMBER OF ITEMS: %3d                                                    |\n",nreg);
    System.out.printf("+-------------------------------------------------------------------------+\n");
}

}

package DataBases;
import java.sql.*;


public class Mysql
{
// instance variables - replace the example below with your own
private String host;
private String user;
private String pass;
private String db;
private int port;
private Connection connection;

/**
 * Constructor for objects of class Mysql
 */
public Mysql()throws ClassNotFoundException,InstantiationException,IllegalAccessException
{
    // initialise instance variables
    this.host = "localhost";
    this.user = "inventory";
    this.pass = "123456";
    this.port = 3306;
    this.db = "inventory";
    this.Init();
}

public Mysql(String host,String user,String pass,int port,String db) throws ClassNotFoundException,InstantiationException,IllegalAccessException
{
    this.host = host;
    this.user = user;
    this.pass = pass;
    this.port = port;
    this.db = db;
    this.Init();
}


public void Init() throws ClassNotFoundException,InstantiationException,IllegalAccessException
{
    // put your code here
    Class.forName("com.mysql.jdbc.Driver").newInstance();
}

public void On() throws SQLException
{

    this.connection = DriverManager.getConnection("jdbc:mysql://"+ this.host +"/" + this.db,this.user,this.pass);
}

public void Off() throws SQLException
{

    this.connection.close();
}

public ResultSet ExeGet(String Query) throws SQLException
{
    Statement st = this.connection.createStatement();
    return (ResultSet) st.executeQuery(Query);
}

public int Exe(String Query) throws SQLException
{

    Statement st = this.connection.createStatement();
    return st.executeUpdate(Query);
}

}




Error:request for member of non class type [duplicate]

This question already has an answer here:

I was just trying a simple program that calculates the volume of a cube. I have declared the object in main and when I try accessing the function of the class with user input arguments it shows an error : request for member 'volume cube' in 'vol', which is of non class type 'Vellimi()'. Why does this occur ?

#include <iostream>
using namespace std;

class Vellimi {
private:

double width;
double height;
double length;

public:
Vellimi(double,double,double);
double volume_cube (double width,double height,double length)
{
    return width*height*length;
}

};
  Vellimi::Vellimi(double a,double b,double c){
  width=a;
   height=b;
   length=c;
}
int main()
{
   double x,y,z;

   Vellimi vol();

   cout<<"Input the width : "<<endl;
   cin>>x;
   cout<<"Input the height : "<<endl;
   cin>>y;
   cout<<"Input the length : "<<endl;
   cin>>z;
   cout<<"The volume is "<<vol.volume_cube(x,y,z)<<endl;
   return 0;

}




samedi 27 février 2016

Data will be in a two-dimensional data array as follows. getting issue while running booktest.

Im having issue with below, java code. so far I've done this.

   BookTest.java:24: error: class expected
(dataArray[i][5]), new Book(double.parseDouble(dataArray[i][6]),dataArray[i][7])));
                                   ^
BookTest.java:24: error: ')' expected
(dataArray[i][5]), new Book(double.parseDouble(dataArray[i][6]),dataArray[i][7])));

Write class, Publisher, with attributes name and state

public class Publisher

{
    private String name;
     private String state;

public Publisher()
{
    setName("");
    setState("");
}

public Publisher(String n, String s)
{
    setName(n);
    setState(s);
}

public void setName(String n)
{
    name = n; 
}

public void setState(String s)
{
    state = s;
}

public String getName()
{
    return name;
}

public String getState()
{
    return state;
}

public String toString()
{
    return ("Name:"+ name + "State:" + state);
}

}

Write Book class with attributes, title, author, isbn, publisher, and price. Book class has method calculateCharge that accepts the quantity sold and returns the total charge.

  public class Book 
{
private String title;
private String author;
private String isbn;
private Publisher publisher;
private double price;

public Book()
{
    setTitle("");
    setAuthor("");
    setIsbn("");
    setPublisher(new Publisher());  
    setPrice(0.0);
}

public Book(String t, String a, String i, Publisher Publisher, double m)  

{
    setTitle(t);
    setAuthor(a);
    setIsbn(i);
    setPublisher(publisher);
    setPrice(m);

 }

 public void setTitle(String t)
 {
    title = t;
 }

 public void setAuthor(String a)
 {
    author = a;
 }
 public void setIsbn(String i)
 {
    isbn = i;
 }
 public void setPublisher(Publisher publisher) 
 {
    this.publisher = publisher;
 }
 public void setPrice(double m)
 {
    price = m ;
 }

 public String getTitle()
 {
    return title;
  }
  public String getAuthor()
  {
    return author;
  }
  public String getIsbn()
  {
    return isbn;
  }

  public Publisher getPublisher()
  {
    return publisher;
  }
  public double getPrice()
  {
    return price;
  }

public double calculatecharge(int qtySold)
{
    double totalCharge; 
    totalCharge = qtySold * getPrice();
    return totalCharge; 
}

public String toString()
{
    return ( "Title :" + title + "Author :" + author + "ISBN :" + isbn + "Publisher :" + publisher + "Price :" + price);
 }

 }

And wrote the non-fiction and fiction class as follows.

public class Fiction extends Book  
{
private String fictionCode;

public Fiction()
{
    super(); 
    setFictionCode("");
}

public Fiction(String t, String a, String i, Publisher Publisher, double m)
{ 
    super(t,a,i,Publisher,m);   
    setFictionCode(fictionCode);

 }

 public void setFictionCode(String fc)

 {
    fictionCode = fc;
 }

 public String getFictionCode()

 {
    return fictionCode;
 }
 public String toString()

 {
    return super.toString();
 }
 }   

But I'm having issue with calling it in the booktest. Data will be in a two-dimensional data array as follows:

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

{
 String dataArray  [][]=
 {{ "Fiction", "Abraham Lincoln Vampire Hunter", "Grahame-Smith, Wiley", "NY",       "978-0446563079", "13.99", "222"},
 {"Fiction", "Frankenstein", "Shelley", "Prescott", "GA", "978-0486282114", "7.99", "321"},
 {"NonFiction", "Life of Kennedy", "Jones", "Pearson", "MT", "758-29304566", "12.90", "biography"},
 {"Fiction", "Dracula", "Stoker", "Addison", "CA", "978-0486411095","5.99", "145"},
 {"Fiction", "Curse of the Wolfman", "Hageman", "Wesley", "MA", "B00381AKHG", "10.59", "876"},
 {"NonFiction", "How to Pass Java", "Willis", "Wiley"," NY", "444-395869790", "1.99", "technology"},
 {"Fiction", "The Mummy", "Rice", "Addision", "CA", "978-0345369949", "7.99", "954"},
 {"NonFiction", "History of Texas", "Smith", "Prescott", "CA", "123-683947687", "9.75", "history"}};

 Book bookArray = new Book [8];

 for (int i=0; i<bookArray.length;i++)

 if (dataArray [i][0].equals("Fiction"))

 {
  bookArray[i]= new Fiction(dataArray[i][1],dataArray[i][2],dataArray[i][3],      new Publisher (dataArray[i][4],
(dataArray[i][5]), new Book(double.parseDouble(dataArray[i][6]),dataArray[i][7])));
 }  
 if (dataArray [i][0].equals("NonFiction"))
  {     
    bookArray[i]= new NonFiction(dataArray[i][1],dataArray[i][2],dataArray[i][3], new Publisher (dataArray[i][4],dataArray[i][5],
new Book(double.parseDouble(dataArray[i][6]),dataArray[i][7])));
 }

 for (book b:bookArray)
 { 
    system.out.println(b.toString());
}
}
 }




Adding objects into a vector and outputting it by overloading the << operator

I have two classes: a Bank class, and a BankAcct class. The problem is the vector of BankAcct objects is not working properly.

This is what I am trying to print out and display.

== 2 total accounts created ==           
Account 1                         
Owner(s) of this account: Bill Gates, Melinda Gates
Total: $7000.00
Account 2
Owner(s) of this account: Carlos Slim
Total: $5000.00

In main I create two accounts and use the openAcct function in the Bank class. However, in the Bank.cpp I am getting a lot of errors from these two lines when adding a BankAcct object into the vector and when I try to output the data by overloading the << operator.

accounts.push_back(BankAcct(v, money));

ostr << "Account " << (i+1) << objec.accounts[i].print() << endl;

I think I am not adding the BankAcct objects into the vector correctly. This could be the cause of the errors in the two lines from above? I'm not sure how I could fix this. Any help would be awesome.

int main()
{
    Bank myBank;

    vector<string> v = { "Bill Gates", "Melinda Gates" };   
    myBank.openAcct(v, 7000);

    v.clear(); 
    v.push_back("Carlos Slim"); 
    myBank.openAcct(v, 5000);

    cout << myBank;
    return 0;
}

The Bank class has a vector of BankAcct objects in Bank.h

class Bank
{
    private:
    vector<BankAcct> accounts;

    public:
    void openAcct(vector<string> v, int money);
    friend ostream & operator<< (ostream &ostr, const Bank &objec);
};

This is the Bank.cpp

void Bank::openAcct(vector<string> v, int money)
{
    accounts.push_back(BankAcct(v, money));
}

ostream & operator<< (ostream &ostr, const Bank &objec)
{

  ostr << "== " << objec.accounts.size() << "total accounts created ==" << endl;

    for (unsigned int i = 0; i < objec.accounts.size(); i++)
    {
       ostr << "Account " << (i+1) << objec.accounts[i].print() << endl;
    }

   return ostr;
}

This is the BankAcct.h

 class BankAcct
 {
     private:
     string* namelist;
     int numOwners;
     double amount;

     public:
     BankAcct(vector<string> v, int money);
     ~BankAcct() { delete [] namelist; }

     void print();

};

This is its BankAcct.cpp

 BankAcct::BankAcct(vector<string> v, int money)
 {
     numOwners = v.size();
     amount = money;
     namelist = new string[numOwners];
     for (unsigned int i = 0; i < v.size(); i++)
     {
        namelist[i] = v[i];
     }

 }

 void BankAcct::print()
 {
    cout << "Owner(s) of this account: ";
    for (int i = 0; i < numOwners; i++)
    {
        cout << namelist[i] << ", " << endl;
    }

    cout << fixed << setprecision(2) << "Total: $" << amount << endl;

 }




While evaluating length of a list that is defined as a class

For example, I got a class named stack,

class stack: #Will be used for probable files!
    def __init__(self):
            self.data = []

    def add(self, element):
            self.data.append(element)

    def number_of_elements(self):
            return len(self.data)

    def stackType(self):
        if self.number_of_elements == 0:
            return 0
        elif self.number_of_elements == 1:
            return 1
        else:
            return -1

I then do this:

foo = stack()
print foo.stackType()

I get -1 however I was expecting a return of 1

Why is it so and how can I handle with it?




Python/SqlAlchemy: Binding attributes (100s) to Base sub-classes sensibly

My project involves data-wrangling some government form filings. I have a decade of filings, about a dozen sections per year, in the form of CSV. Each CSV is paired with a file with the field names, types, and sizes. Since the data is originally from a relational DB of some sort, I figured the most sensible way to handle the data is pop it into Sqlite and use SqlAlchemy to query it.

I'm just getting my feet wet with SqlAlchemy and it seems the typical way of creating database objects is to create a class with a Column attribute for each field, as such:

Base = declarative_base()
class Person(Base):
    __tablename__ = 'person'
    id = Column(Integer, primary_key=True)
    name = Column(String(250), nullable=False)
    ...

and then access rows from the table with something like

person = session.query(Person).filter(Person.name == 'bob').all()

However, there are over a hundred of these such tables, and some tables have upwards of 150 fields. Yikes, not coding that by hand. I wrote a quick script to generate the .py file from the list of fields, which works, but feels a bit un-pythonic.

It seems like from some examples I need to pass the class, not the instance, but I could be missing some nuance here. I tried binding attributes using setattr to a base class, but after some mucking with factory functions and mangling inheritance in various ways, it was clear python's type management was not going to play ball. The only other thing that comes to mind is trying messing around with class instances and deepcopy, but that also seems dodgy.

Is there a nice/elegant way of creating a hundred declarative_base subclasses with a hundred fields from a template, or more importantly, is there a better way in general of interfacing with these tables?




C++ and Sfml Inheritance

How can I use the dynamic variable by inherited. Sample;

 class car
{
public:
    car();
    sf::Vector2f whereİsCar();
    void event(); //veryLong code = change spriteCar Position

protected:
  sf::Sprite spriteCar;

};

car::car()
{

    spriteCar.setPosition(300, 10);


}


class Rocket : public car

{

public:

    Rocket();
    void collideCar();
    void update();

private:
    sf::Sprite spriteRocket;

}

void Rocket::collideCar()
{

  cout << spriteCar.position.x; << " " << spriteCar.position.y; // Console : 300 10
}

When i run my game,changing values ​​in a class does not change the class b. How do i fix it.

I hope understand me. Thank you for helping.




I am having hard time with my Homework




Access a list data member in a class

I have a class defined like:

public class Paths //class point definition
    {
        public List<Point> points;
        public Color color;
        public Paths(List<Point> POINTS, Color COLOR)
        {
            points = POINTS;
            color = COLOR;
        }
    }

in my source code I make a list: List<Paths> PATHS = new List<Paths>();

then I make a list of points: List<Point> newPath = null; then I add some stuff to it: newPath.Add(x, y);

now I want this newPath to be inserted in my PATHS list along with a color. How do I do this?




C++ class template copy contructor return type

I have declared operator= like this:

HashTable& operator=(const HashTable& aTable);

And I'm defining it outside the class the following way:

template <typename HashElement>
HashTable& HashTable<HashElement>::operator=(const HashTable& aTable)
{
    /*Do the copy thing*/
    return *this;
}

I'd expect it to compile with the following code:

HashTable<EngWord> hashTable;
HashTable<EngWord> hashTableA;
hashTableA = hashTable;

But the compiler doesn't like the signature of the definition. The error message is:

HashTable: suer of class template requires template argument list
HashTable<HashElement>::operation=': unable to match function definition or an existing declaration

On what I've seen on the internet it should be the way I've written. What's wrong?




Are base classes in inheritance copied to the derived class?

as the title says : are base classes in inheritance copied to the derived class I mean like #include the code from the base class is copied to the derived class or just an object from the base class is created and the children class just use is it at runtime ?